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 5 |
+
from nltk.stem.porter import PorterStemmer
|
| 6 |
+
import json
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def Training():
|
| 11 |
+
|
| 12 |
+
class NeuralNet(nn.Module):
|
| 13 |
+
|
| 14 |
+
def __init__(self,input_size,hidden_size,num_classes):
|
| 15 |
+
super(NeuralNet,self).__init__()
|
| 16 |
+
self.l1 = nn.Linear(input_size,hidden_size)
|
| 17 |
+
self.l2 = nn.Linear(hidden_size,hidden_size)
|
| 18 |
+
self.l3 = nn.Linear(hidden_size,num_classes)
|
| 19 |
+
self.relu = nn.ReLU()
|
| 20 |
+
|
| 21 |
+
def forward(self,x):
|
| 22 |
+
out = self.l1(x)
|
| 23 |
+
out = self.relu(out)
|
| 24 |
+
out = self.l2(out)
|
| 25 |
+
out = self.relu(out)
|
| 26 |
+
out = self.l3(out)
|
| 27 |
+
return out
|
| 28 |
+
|
| 29 |
+
Stemmer = PorterStemmer()
|
| 30 |
+
|
| 31 |
+
def tokenize(sentence):
|
| 32 |
+
return nltk.word_tokenize(sentence)
|
| 33 |
+
|
| 34 |
+
def stem(word):
|
| 35 |
+
return Stemmer.stem(word.lower())
|
| 36 |
+
|
| 37 |
+
def bag_of_words(tokenized_sentence,words):
|
| 38 |
+
sentence_word = [stem(word) for word in tokenized_sentence]
|
| 39 |
+
bag = np.zeros(len(words),dtype=np.float32)
|
| 40 |
+
|
| 41 |
+
for idx , w in enumerate(words):
|
| 42 |
+
if w in sentence_word:
|
| 43 |
+
bag[idx] = 1
|
| 44 |
+
|
| 45 |
+
return bag
|
| 46 |
+
|
| 47 |
+
with open("intents.json",'r') as f:
|
| 48 |
+
intents = json.load(f)
|
| 49 |
+
|
| 50 |
+
all_words = []
|
| 51 |
+
tags = []
|
| 52 |
+
xy = []
|
| 53 |
+
|
| 54 |
+
for intent in intents['intents']:
|
| 55 |
+
tag = intent['tag']
|
| 56 |
+
tags.append(tag)
|
| 57 |
+
|
| 58 |
+
for pattern in intent['patterns']:
|
| 59 |
+
w = tokenize(pattern)
|
| 60 |
+
all_words.extend(w)
|
| 61 |
+
xy.append((w,tag))
|
| 62 |
+
|
| 63 |
+
ignore_words = [',','?','/','.','!']
|
| 64 |
+
all_words = [stem(w) for w in all_words if w not in ignore_words]
|
| 65 |
+
all_words = sorted(set(all_words))
|
| 66 |
+
tags = sorted(set(tags))
|
| 67 |
+
|
| 68 |
+
x_train = []
|
| 69 |
+
y_train = []
|
| 70 |
+
|
| 71 |
+
for (pattern_sentence,tag) in xy:
|
| 72 |
+
bag = bag_of_words(pattern_sentence,all_words)
|
| 73 |
+
x_train.append(bag)
|
| 74 |
+
|
| 75 |
+
label = tags.index(tag)
|
| 76 |
+
y_train.append(label)
|
| 77 |
+
|
| 78 |
+
x_train = np.array(x_train)
|
| 79 |
+
y_train = np.array(y_train)
|
| 80 |
+
|
| 81 |
+
num_epochs = 1000
|
| 82 |
+
batch_size = 8
|
| 83 |
+
learning_rate = 0.001
|
| 84 |
+
input_size = len(x_train[0])
|
| 85 |
+
hidden_size = 8
|
| 86 |
+
output_size = len(tags)
|
| 87 |
+
print(">> Training The Chats Module :- Conciousness ")
|
| 88 |
+
|
| 89 |
+
class ChatDataset(Dataset):
|
| 90 |
+
|
| 91 |
+
def __init__(self):
|
| 92 |
+
self.n_samples = len(x_train)
|
| 93 |
+
self.x_data = x_train
|
| 94 |
+
self.y_data = y_train
|
| 95 |
+
|
| 96 |
+
def __getitem__(self,index):
|
| 97 |
+
return self.x_data[index],self.y_data[index]
|
| 98 |
+
|
| 99 |
+
def __len__(self):
|
| 100 |
+
return self.n_samples
|
| 101 |
+
|
| 102 |
+
dataset = ChatDataset()
|
| 103 |
+
|
| 104 |
+
train_loader = DataLoader(dataset=dataset,
|
| 105 |
+
batch_size=batch_size,
|
| 106 |
+
shuffle=True,
|
| 107 |
+
num_workers=0)
|
| 108 |
+
|
| 109 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 110 |
+
model = NeuralNet(input_size,hidden_size,output_size).to(device=device)
|
| 111 |
+
criterion = nn.CrossEntropyLoss()
|
| 112 |
+
optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate)
|
| 113 |
+
|
| 114 |
+
for epoch in range(num_epochs):
|
| 115 |
+
for (words,labels) in train_loader:
|
| 116 |
+
words = words.to(device)
|
| 117 |
+
labels = labels.to(dtype=torch.long).to(device)
|
| 118 |
+
outputs = model(words)
|
| 119 |
+
loss = criterion(outputs,labels)
|
| 120 |
+
optimizer.zero_grad()
|
| 121 |
+
loss.backward()
|
| 122 |
+
optimizer.step()
|
| 123 |
+
|
| 124 |
+
if (epoch+1) % 100 ==0:
|
| 125 |
+
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
|
| 126 |
+
|
| 127 |
+
print(f'Final Loss : {loss.item():.4f}')
|
| 128 |
+
|
| 129 |
+
data = {
|
| 130 |
+
"model_state":model.state_dict(),
|
| 131 |
+
"input_size":input_size,
|
| 132 |
+
"hidden_size":hidden_size,
|
| 133 |
+
"output_size":output_size,
|
| 134 |
+
"all_words":all_words,
|
| 135 |
+
"tags":tags
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
FILE = "intents.pth"
|
| 139 |
+
torch.save(data,FILE)
|
| 140 |
+
|
| 141 |
+
print(f"Training Complete, File Saved To {FILE}")
|
| 142 |
+
print(" ")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
Training()
|
| 148 |
+
|