add helper class
This commit is contained in:
parent
efa3663f42
commit
b013762aae
7 changed files with 171 additions and 105 deletions
BIN
loss.png
Normal file
BIN
loss.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 52 KiB |
Binary file not shown.
|
|
@ -3,30 +3,22 @@ import torch
|
||||||
import random
|
import random
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
import matplotlib.pyplot as plt
|
|
||||||
import matplotlib.ticker as ticker
|
import matplotlib.ticker as ticker
|
||||||
from VectorizeClass import Vectorize
|
from VectorizeClass import Vectorize
|
||||||
|
from helper import *
|
||||||
import time
|
import time
|
||||||
import math
|
|
||||||
|
|
||||||
from NN import RNN
|
|
||||||
|
from NN import *
|
||||||
|
|
||||||
class Train():
|
class Train():
|
||||||
def __init__(self,df_en,doLoad=False,testing=False):
|
def __init__(self,df_en):
|
||||||
self.df_en=df_en
|
self.df_en=df_en
|
||||||
self.vectorizer = Vectorize(1,1)
|
self.helper= Helper(df_en)
|
||||||
self.vectorizer.fit(doc=df_en["name"])
|
self.inputSize, self.n_category= self.helper.getIOSize()
|
||||||
|
|
||||||
self.inputSize=self.vectorizer.getVocabLen()
|
|
||||||
self.n_hidden = 256*4
|
self.n_hidden = 256*4
|
||||||
|
self.rnn= RNN(self.inputSize, self.n_hidden, self.n_category)
|
||||||
self.df_category = self.df_en.groupby('category')
|
|
||||||
self.all_category = list(self.df_category.groups.keys())
|
|
||||||
if testing:
|
|
||||||
self.all_category=random.choices(self.all_category,k=20)
|
|
||||||
|
|
||||||
self.n_category = len(self.all_category)
|
|
||||||
self.rnn= torch.load('ngram-rnn-classification.pt') if doLoad else RNN(self.inputSize, self.n_hidden, self.n_category)
|
|
||||||
self.learning_rate=0.005
|
self.learning_rate=0.005
|
||||||
self.criterion = nn.NLLLoss()
|
self.criterion = nn.NLLLoss()
|
||||||
|
|
||||||
|
|
@ -59,59 +51,37 @@ class Train():
|
||||||
return output, loss.item()
|
return output, loss.item()
|
||||||
|
|
||||||
|
|
||||||
def randomTrainingExample(self):
|
|
||||||
|
|
||||||
randcategory = random.choice(self.all_category)
|
randcategory = random.choice(self.all_category)
|
||||||
# get feature name from the category
|
# get feature name from the category
|
||||||
random_feature_indices = self.df_category.indices[randcategory]
|
random_feature_indices = self.df_category.indices[randcategory]
|
||||||
|
|
||||||
index = random_feature_indices[random.randint(0, len(random_feature_indices) - 1)]
|
index = random_feature_indices[random.randint(0, len(random_feature_indices) - 1)]
|
||||||
|
|
||||||
# ngramNameArray = self.vectorizer.getTransformedVectorByIndex(index)
|
|
||||||
|
|
||||||
name =self.df_en.iloc[index]["name"]
|
name =self.df_en.iloc[index]["name"]
|
||||||
|
|
||||||
category_tensor = torch.tensor([self.all_category.index(randcategory)], dtype=torch.long)
|
category_tensor = torch.tensor([self.all_category.index(randcategory)], dtype=torch.long)
|
||||||
# ngramOnceArray = np.where(ngramNameArray==1)[0]
|
|
||||||
|
|
||||||
# name_tensor=torch.zeros(len(ngramOnceArray),1, self.inputSize)
|
|
||||||
|
|
||||||
# for i in range(ngramOnceArray.size):
|
|
||||||
|
|
||||||
# name_tensor[i][0][ngramOnceArray[i]] = 1
|
|
||||||
|
|
||||||
name_tensor = self.nameToTensor(name)
|
|
||||||
|
|
||||||
|
name_tensor = self.helper.nameToTensor(name,self.vectorizer)
|
||||||
|
|
||||||
return randcategory, name, category_tensor, name_tensor
|
return randcategory, name, category_tensor, name_tensor
|
||||||
|
|
||||||
|
|
||||||
def categoryFromOutput(self,output):
|
|
||||||
|
|
||||||
_, top_i = output.topk(1)
|
|
||||||
|
|
||||||
cat_i = top_i[0].item()
|
|
||||||
|
|
||||||
return self.all_category[cat_i], cat_i
|
|
||||||
|
|
||||||
|
|
||||||
def run(self,n_iters):
|
def run(self,n_iters):
|
||||||
start = time.time()
|
start = time.time()
|
||||||
for epoch in range(1, n_iters + 1):
|
for epoch in range(1, n_iters + 1):
|
||||||
|
|
||||||
category, name, category_tensor, name_tensor = self.randomTrainingExample()
|
category, name, category_tensor, name_tensor = self.helper.randomTrainingExample()
|
||||||
|
|
||||||
output, loss = self.train(category_tensor, name_tensor)
|
output, loss = self.train(category_tensor, name_tensor)
|
||||||
self.current_loss += loss
|
self.current_loss += loss
|
||||||
# Print ``iter`` number, loss, name and guess
|
# Print ``iter`` number, loss, name and guess
|
||||||
|
|
||||||
if epoch % 10000 == 0:
|
if epoch % 10000 == 0:
|
||||||
guess, guess_i = self.categoryFromOutput(output)
|
guess, guess_i = self.helper.categoryFromOutput(output)
|
||||||
correct = '✓' if guess == category else '✗ (%s)' % category
|
correct = '✓' if guess == category else '✗ (%s)' % category
|
||||||
|
|
||||||
print('%d %d%% (%s) %.4f %s / %s %s' % (epoch,
|
print('%d %d%% (%s) %.4f %s / %s %s' % (epoch,
|
||||||
epoch / n_iters * 100,
|
epoch / n_iters * 100,
|
||||||
self.timeSince(start),
|
self.helper.timeSince(start),
|
||||||
loss,
|
loss,
|
||||||
name,
|
name,
|
||||||
guess,
|
guess,
|
||||||
|
|
@ -121,16 +91,11 @@ class Train():
|
||||||
self.all_losses.append(self.current_loss / 5000)
|
self.all_losses.append(self.current_loss / 5000)
|
||||||
self.current_loss = 0
|
self.current_loss = 0
|
||||||
|
|
||||||
self.plot()
|
self.helper.plot(self.all_losses,"loss.png")
|
||||||
|
|
||||||
torch.save(self.rnn,'ngram-rnn-classification.pt')
|
torch.save(self.rnn,'ngram-rnn-classification.pt')
|
||||||
|
|
||||||
|
|
||||||
def plot(self):
|
|
||||||
plt.figure()
|
|
||||||
plt.plot(self.all_losses)
|
|
||||||
plt.savefig('histogram.png', dpi=400)
|
|
||||||
|
|
||||||
|
|
||||||
# Just return an output given a numpy array
|
# Just return an output given a numpy array
|
||||||
def evaluate(self,tensor):
|
def evaluate(self,tensor):
|
||||||
hidden = self.rnn.initHidden()
|
hidden = self.rnn.initHidden()
|
||||||
|
|
@ -140,30 +105,12 @@ class Train():
|
||||||
|
|
||||||
return output
|
return output
|
||||||
|
|
||||||
def timeSince(self,since):
|
|
||||||
now = time.time()
|
|
||||||
s = now - since
|
|
||||||
m = math.floor(s / 60)
|
|
||||||
s -= m * 60
|
|
||||||
return '%dm %ds' % (m, s)
|
|
||||||
|
|
||||||
def nameToTensor(self,name):
|
|
||||||
# create empty tensor with
|
|
||||||
vectorized=self.vectorizer.transform(list(name.split()))
|
|
||||||
n_vectors=len(vectorized.indices)
|
|
||||||
|
|
||||||
name_tensor=torch.zeros(n_vectors,1, self.inputSize)
|
|
||||||
for i in range(n_vectors):
|
|
||||||
|
|
||||||
name_tensor[i][0][vectorized.indices[i]] = 1
|
|
||||||
|
|
||||||
return name_tensor
|
|
||||||
|
|
||||||
|
|
||||||
def predict(self,name, n_predictions=3):
|
# def predict(self,name, n_predictions=1):
|
||||||
print('\n> %s' % name)
|
print('\n> %s' % name)
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
output = self.evaluate(self.nameToTensor(name))
|
output = self.evaluate(self.helper.nameToTensor(name,self.vectorizer))
|
||||||
|
|
||||||
# Get top N categories
|
# Get top N categories
|
||||||
topv, topi = output.topk(n_predictions, 1, True)
|
topv, topi = output.topk(n_predictions, 1, True)
|
||||||
|
|
@ -175,42 +122,42 @@ class Train():
|
||||||
print('(%.2f) %s' % (value, self.all_category[category_index]))
|
print('(%.2f) %s' % (value, self.all_category[category_index]))
|
||||||
predictions.append([value, self.all_category[category_index]])
|
predictions.append([value, self.all_category[category_index]])
|
||||||
|
|
||||||
def confusionMatix(self):
|
# def confusionMatix(self):
|
||||||
# Keep track of correct guesses in a confusion matrix
|
# # Keep track of correct guesses in a confusion matrix
|
||||||
|
|
||||||
n_categories = len(self.all_category)
|
# n_categories = len(self.all_category)
|
||||||
confusion = torch.zeros(n_categories, n_categories)
|
# confusion = torch.zeros(n_categories, n_categories)
|
||||||
n_confusion = 10000
|
# n_confusion = 10000
|
||||||
|
|
||||||
# Go through a bunch of examples and record which are correctly guessed
|
# # Go through a bunch of examples and record which are correctly guessed
|
||||||
for i in range(n_confusion):
|
# for i in range(n_confusion):
|
||||||
category, name, category_tensor, name_tensor = self.randomTrainingExample()
|
# category, name, category_tensor, name_tensor = self.helper.randomTrainingExample()
|
||||||
output = self.evaluate(name_tensor)
|
# output = self.evaluate(name_tensor)
|
||||||
guess, guess_i = self.categoryFromOutput(output)
|
# guess, guess_i = self.helper.categoryFromOutput(output)
|
||||||
category_i =self.all_category.index(category)
|
# category_i =self.all_category.index(category)
|
||||||
confusion[category_i][guess_i] += 1
|
# confusion[category_i][guess_i] += 1
|
||||||
|
|
||||||
# Normalize by dividing every row by its sum
|
# # Normalize by dividing every row by its sum
|
||||||
for i in range(n_categories):
|
# for i in range(n_categories):
|
||||||
confusion[i] = confusion[i] / confusion[i].sum()
|
# confusion[i] = confusion[i] / confusion[i].sum()
|
||||||
|
|
||||||
# Set up plot
|
# # Set up plot
|
||||||
fig = plt.figure()
|
# fig = plt.figure()
|
||||||
ax = fig.add_subplot(111)
|
# ax = fig.add_subplot(111)
|
||||||
cax = ax.matshow(confusion.numpy())
|
# cax = ax.matshow(confusion.numpy())
|
||||||
fig.colorbar(cax)
|
# fig.colorbar(cax)
|
||||||
|
|
||||||
# Set up axes
|
# # Set up axes
|
||||||
ax.set_xticklabels([''] + self.all_category, rotation=45)
|
# ax.set_xticklabels([''] + self.all_category, rotation=45)
|
||||||
ax.set_yticklabels([''] + self.all_category)
|
# ax.set_yticklabels([''] + self.all_category)
|
||||||
|
|
||||||
# Force label at every tick
|
# # Force label at every tick
|
||||||
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
|
# ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
|
||||||
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
|
# ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
|
||||||
|
|
||||||
# sphinx_gallery_thumbnail_number = 2
|
# # sphinx_gallery_thumbnail_number = 2
|
||||||
plt.show()
|
# plt.show()
|
||||||
plt.savefig('confusion.png', dpi=400)
|
# plt.savefig('confusion.png', dpi=400)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
71
rm_clasificationmodel/helper.py
Normal file
71
rm_clasificationmodel/helper.py
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
import torch
|
||||||
|
import random
|
||||||
|
import time
|
||||||
|
import math
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
from VectorizeClass import Vectorize
|
||||||
|
class Helper():
|
||||||
|
def __init__(self,df_en):
|
||||||
|
self.vectorizer = Vectorize(1,1)
|
||||||
|
self.df_en=df_en
|
||||||
|
self.df_category = self.df_en.groupby('category')
|
||||||
|
self.all_category = list(self.df_category.groups.keys())
|
||||||
|
self.vectorizer.fit(doc=df_en["name"])
|
||||||
|
self.inputSize=self.vectorizer.getVocabLen()
|
||||||
|
self.n_categories=len(self.all_category)
|
||||||
|
|
||||||
|
def getIOSize(self):
|
||||||
|
return self.inputSize,self.n_categories
|
||||||
|
|
||||||
|
def timeSince(self,since):
|
||||||
|
now = time.time()
|
||||||
|
s = now - since
|
||||||
|
m = math.floor(s / 60)
|
||||||
|
s -= m * 60
|
||||||
|
return '%dm %ds' % (m, s)
|
||||||
|
|
||||||
|
def categoryFromOutput(self,output):
|
||||||
|
|
||||||
|
_, top_i = output.topk(1)
|
||||||
|
|
||||||
|
cat_i = top_i[0].item()
|
||||||
|
|
||||||
|
return self.all_category[cat_i], cat_i
|
||||||
|
|
||||||
|
def plot(self,data,name):
|
||||||
|
plt.figure()
|
||||||
|
plt.plot(data)
|
||||||
|
plt.savefig(name, dpi=400)
|
||||||
|
|
||||||
|
def nameToTensor(self,name,vectorizer):
|
||||||
|
# create empty tensor with
|
||||||
|
inputSize=vectorizer.getVocabLen()
|
||||||
|
vectorized=vectorizer.transform(list(name.split()))
|
||||||
|
n_vectors=len(vectorized.indices)
|
||||||
|
|
||||||
|
name_tensor=torch.zeros(n_vectors,1, inputSize)
|
||||||
|
for i in range(n_vectors):
|
||||||
|
|
||||||
|
name_tensor[i][0][vectorized.indices[i]] = 1
|
||||||
|
|
||||||
|
return name_tensor
|
||||||
|
|
||||||
|
def categoryTensor(self,category):
|
||||||
|
return torch.tensor([self.all_category.index(category)], dtype=torch.long)
|
||||||
|
|
||||||
|
|
||||||
|
def randomTrainingExample(self):
|
||||||
|
|
||||||
|
randcategory = random.choice(self.all_category)
|
||||||
|
# get feature name from the category
|
||||||
|
random_feature_indices = self.df_category.indices[randcategory]
|
||||||
|
|
||||||
|
index = random_feature_indices[random.randint(0, len(random_feature_indices) - 1)]
|
||||||
|
|
||||||
|
name =self.df_en.iloc[index]["name"]
|
||||||
|
|
||||||
|
category_tensor = torch.tensor([self.all_category.index(randcategory)], dtype=torch.long)
|
||||||
|
|
||||||
|
name_tensor = self.nameToTensor(name,self.vectorizer)
|
||||||
|
|
||||||
|
return randcategory, name, category_tensor, name_tensor
|
||||||
|
|
@ -13,10 +13,10 @@ def main():
|
||||||
es =ElasticSearchDb("http://172.17.212.35:9200")
|
es =ElasticSearchDb("http://172.17.212.35:9200")
|
||||||
|
|
||||||
df=DataFrame(es)
|
df=DataFrame(es)
|
||||||
dfProductTaxonomyEn=df.getProductTaxonomy(0,10000)
|
# dfProductTaxonomyEn=df.getProductTaxonomy(0,10000)
|
||||||
|
|
||||||
|
|
||||||
# df_en = df.getNormal()
|
df_en = df.getNormal()
|
||||||
|
|
||||||
# [df_en, df_de]=df.create()
|
# [df_en, df_de]=df.create()
|
||||||
|
|
||||||
|
|
@ -25,8 +25,8 @@ def main():
|
||||||
|
|
||||||
# rnn=torch.load('ngram-rnn-classification.pt')
|
# rnn=torch.load('ngram-rnn-classification.pt')
|
||||||
|
|
||||||
# train = Train(df_en)
|
train = Train(df_en)
|
||||||
# train.run(20)
|
train.run(200000)
|
||||||
# train.predict('vaico centering bush propshaft',2)
|
# train.predict('vaico centering bush propshaft',2)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
40
rm_clasificationmodel/predict.py
Normal file
40
rm_clasificationmodel/predict.py
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
from NN import *
|
||||||
|
from data import *
|
||||||
|
import sys
|
||||||
|
|
||||||
|
rnn = torch.load('char-rnn-classification.pt')
|
||||||
|
|
||||||
|
# Just return an output given a line
|
||||||
|
def evaluate(line_tensor):
|
||||||
|
hidden = rnn.initHidden()
|
||||||
|
|
||||||
|
for i in range(line_tensor.size()[0]):
|
||||||
|
output, hidden = rnn(line_tensor[i], hidden)
|
||||||
|
|
||||||
|
return output
|
||||||
|
|
||||||
|
def evaluate(self,tensor):
|
||||||
|
hidden = self.rnn.initHidden()
|
||||||
|
|
||||||
|
for i in range(tensor.size()[0]):
|
||||||
|
output, hidden = self.rnn(tensor[i], hidden)
|
||||||
|
|
||||||
|
return output
|
||||||
|
|
||||||
|
def predict(self,name, n_predictions=3):
|
||||||
|
print('\n> %s' % name)
|
||||||
|
with torch.no_grad():
|
||||||
|
output = self.evaluate(self.nameToTensor(name))
|
||||||
|
|
||||||
|
# Get top N categories
|
||||||
|
topv, topi = output.topk(n_predictions, 1, True)
|
||||||
|
predictions = []
|
||||||
|
|
||||||
|
for i in range(n_predictions):
|
||||||
|
value = topv[0][i].item()
|
||||||
|
category_index = topi[0][i].item()
|
||||||
|
print('(%.2f) %s' % (value, self.all_category[category_index]))
|
||||||
|
predictions.append([value, self.all_category[category_index]])
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
predict(sys.argv[1])
|
||||||
8
rm_clasificationmodel/server.py
Normal file
8
rm_clasificationmodel/server.py
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
from bottle import route, run
|
||||||
|
from predict import *
|
||||||
|
|
||||||
|
@route('/<input_line>')
|
||||||
|
def index(input_line):
|
||||||
|
return {'result': predict(input_line, 10)}
|
||||||
|
|
||||||
|
run(host='localhost', port=5533)
|
||||||
Loading…
Reference in a new issue