-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
167 lines (146 loc) · 4.57 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import json
from torch.optim import optimizer
from utils import DataProcess
import numpy as np
import torch
import torch.nn.functional as f
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from model import Net
######################################################################
# Cargamos el Archivo json #
with open("../MIKOBOT/intents.json", "r", encoding="utf-8") as f:
data = json.load(f)
######################################################################
# Creamos algunas variables #
all_words = []
tags = []
xy = []
preprocess_dataset = DataProcess()
ignore_words = [
"!",
"#",
"$",
"%",
"&",
"(",
")",
"*",
"+",
"-",
",",
".",
"/",
":",
";",
"<",
"=",
">",
"¿",
"?",
"@",
"[",
"]",
"^",
"_",
"`",
"{",
"|",
"}",
"~",
"]",
]
X_train = []
Y_train = []
######################################################################
# Preparamos la data para el entrenamiento #
for intent in data["intents"]:
tag = intent["tag"]
tags.append(tag)
for pattern in intent["patterns"]:
w = preprocess_dataset.tokenize(pattern)
all_words.extend(w)
xy.append((w, tag))
all_words = [preprocess_dataset.stem(w) for w in all_words if w not in ignore_words]
all_words = sorted(set(all_words))
tags = sorted(set(tags))
for (patter_sentece, tag) in xy:
bag = preprocess_dataset.bag_word(patter_sentece, all_words)
X_train.append(bag)
label = tags.index(tag)
Y_train.append(label)
X_train = np.array(X_train)
Y_train = np.array(Y_train)
#############################################################################
class ChatDataset(Dataset):
def __init__(self):
'''
-Método:
- __init__: Este es el constructor de la clase ChatDataset que hereda de Dataset.
- Argumentos:
- self.n_samples: Tamaño de los datos de entrenamiento.
- self.x_data: Los datos de entrenamiento.
- self.y_data: Las etiquetas de los datos de entrenamiento.
'''
self.n_samples = len(X_train)
self.x_data = X_train
self.y_data = Y_train
def __getitem__(self, index):
'''
-Método:
- __getitem__: Este es un método especial para obtener elementos.
- Argumentos:
- index: El indice que nos dar la posición de un dato en x_data y y_data.
- Retorna:
- Nos retorana los valores de x_data e y_data en la posición index.
'''
return self.x_data[index], self.y_data[index]
def __len__(self):
'''
-Método:
- __len__ : Este método especial nos dara el tamño de los datos de ejemplo.
Retorna:
- nos retornara el tamñaño de los datos de ejemplo.
'''
return self.n_samples
###################################################################################
# Entrenammiento del modelo #
batch_size = 8
hidden_Size = 8
output = len(tags)
input = len(X_train[0])
learning_rate = 0.001
num_epoch = 1000
dataset = ChatDataset()
train_loader = DataLoader(dataset, batch_size, shuffle=True, num_workers=0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")#
model = Net(input, hidden_Size, output).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for epoch in range(num_epoch):
for (words, labels) in train_loader:
words = words.to(device=device)
words = words.float()
labels = labels.to(device=device)
labels = labels.type(torch.int64)
outputs = model(words)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 100 == 0:
print(f"epoch: {epoch+1}/{num_epoch}, loss = {loss.item():.4f}")
print(f"final loss = {loss.item():.4f}")
############################################################################################
# Descargamos el modelo #
data = {
"model_state":model.state_dict(),
"input_size": input,
"ouput_size":output,
"hidden_size":hidden_Size,
"all_words":all_words,
"tags":tags
}
FILE = "data.pth"
torch.save(data, FILE)
print(f'El entrenamiento ha terminado tu archivo {FILE} se ha guardado.')