vectorizer

This commit is contained in:
shoney 2023-07-01 23:04:59 +00:00
parent ea91e03756
commit 133a26f822
6 changed files with 87 additions and 41 deletions

View file

@ -72,7 +72,7 @@
\end{tikzpicture}
\vspace{1cm}
\begin{multicols}{3}
\begin{multicols*}{3}
\fontsize{30}{40}
@ -102,6 +102,28 @@
\end{multicols}
\columnbreak
\section{Network Architecture - Recurrent Neural Network}
% \begin{Figure}
% \centering
% \includegraphics[width=0.50\linewidth]{nn_arch}
% \captionsetup{font=footnotesize}
% \captionof{figure}{Confusion Matrix}
% \label{fig:nn}
% \end{Figure}
\begin{enumerate}
\item Input layer - These nodes pass on information to hidden nodes. The collection of product names after normalization and creating a vocabulary of it using n-gram vectorization provides provides \textit{n} number of unique words. Here, \textit{n} is the number of input layer size.
\item Hidden layers - Transfers information from input node to the output node.
\item Output layer - This layer performs computation and transfers information to the network to out of the function. In our experiment the total number of categories the model should predict is the size of the output layer.
\item Softmax function - Takes input of \textit{K} real numbers, and normalizes it into a probability distribution consisting of \textit{K} probabilities.
\item Combine function : Add the input layer and hidden layer tensors and pass on to the softmax function.
\end{enumerate}
\section{Evaluation and Results}
\begin{enumerate}
\item Preprocessing of the product and category data frame is performed, which involves step:-
@ -129,7 +151,7 @@
\end{center}
\columnbreak
\subsection{Confusion Matrix}
Confusion matrix displays how well the network performed on different categories. It is a matrix of actual categories (rows) which category the network guesses (columns). In figure \ref{fig:cm}, the yellow cells aligned diagonally shows the correct guesses by the network.
\begin{Figure}
@ -140,32 +162,12 @@
\label{fig:cm}
\end{Figure}
\end{multicols}
\end{multicols*}
% \printbibliography
\fontsize{30}{40}
\selectfont
\section{Network Architecture - Recurrent Neural Netwrok}
\begin{multicols}{3}
\begin{Figure}
\centering
\includegraphics[width=0.5\linewidth]{nn_arch}
\captionsetup{font=footnotesize}
\captionof{figure}{Confusion Matrix}
\label{fig:nn}
\end{Figure}
\columnbreak
\begin{enumerate}
\item Input layer - These nodes pass on information to hidden nodes. The collection of product names after normalization and creating a vocabulary of it using n-gram vectorization provides provides \textit{n} number of unique words. Here, \textit{n} is the number of input layer size.
\item Hidden layers - Transfers information from input node to the output node.
\item Output layer - This layer performs computation and transfers information to the network to out of the function. In our experiment the total number of categories the model should predict is the size of the output layer.
\item Softmax function - Takes input of \textit{K} real numbers, and normalizes it into a probability distribution consisting of \textit{K} probabilities.
\item Combine function : Add the input layer and hidden layer tensors and pass on to the softmax function.
\end{enumerate}
\end{multicols}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

View file

@ -6,6 +6,8 @@ import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from VectorizeClass import Vectorize
import time
import math
from NN import RNN
@ -14,8 +16,8 @@ class Train():
self.df_en=df_en
self.vectorizer = Vectorize(1,1)
self.vectorizer.fit(doc=df_en["name"])
self.vectorizer.transform(df_en["name"])
self.inputSize=self.vectorizer.getTransformedVectorSize()
self.inputSize=self.vectorizer.getVocabLen()
self.n_hidden = 256*4
self.df_category = self.df_en.groupby('category')
@ -30,8 +32,7 @@ class Train():
self.current_loss = 0
self.all_losses = []
def train(self,category_tensor, name_tensor):
@ -66,19 +67,20 @@ class Train():
index = random_feature_indices[random.randint(0, len(random_feature_indices) - 1)]
ngramNameArray = self.vectorizer.getTransformedVectorByIndex(index)
# ngramNameArray = self.vectorizer.getTransformedVectorByIndex(index)
name =self.df_en.iloc[index]["name"]
category_tensor = torch.tensor([self.all_category.index(randcategory)], dtype=torch.long)
ngramOnceArray = np.where(ngramNameArray==1)[0]
# ngramOnceArray = np.where(ngramNameArray==1)[0]
name_tensor=torch.zeros(len(ngramOnceArray),1, self.inputSize)
# name_tensor=torch.zeros(len(ngramOnceArray),1, self.inputSize)
for i in range(ngramOnceArray.size):
name_tensor[i][0][ngramOnceArray[i]] = 1
# for i in range(ngramOnceArray.size):
# name_tensor[i][0][ngramOnceArray[i]] = 1
name_tensor = self.nameToTensor(name)
return randcategory, name, category_tensor, name_tensor
@ -94,19 +96,22 @@ class Train():
def run(self,n_iters):
start = time.time()
for epoch in range(1, n_iters + 1):
category, name, category_tensor, name_tensor = self.randomTrainingExample()
output, loss = self.train(category_tensor, name_tensor)
self.current_loss += loss
# Print ``iter`` number, loss, name and guess
if epoch % 10000 == 0:
guess, guess_i = self.categoryFromOutput(output)
correct = '✓' if guess == category else '✗ (%s)' % category
print('%d %d%% %.4f %s / %s %s' % (epoch,
print('%d %d%% (%s) %.4f %s / %s %s' % (epoch,
epoch / n_iters * 100,
self.timeSince(start),
loss,
name,
guess,
@ -135,6 +140,41 @@ class Train():
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):
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]])
def confusionMatix(self):
# Keep track of correct guesses in a confusion matrix

View file

@ -7,9 +7,13 @@ class Vectorize():
def fit(self,doc):
self.vectorizer.fit(doc)
def getVocabLen(self):
return len(self.vectorizer.vocabulary_)
def transform (self,doc):
self.transformedVector = self.vectorizer.transform(doc)
self.transformedVector=self.vectorizer.transform(doc)
return self.transformedVector
def getVocabulary(self):
return self.vectorizer.vocabulary_

View file

@ -40,10 +40,10 @@ def main():
# rnn=torch.load('ngram-rnn-classification.pt')
train = Train(df_en,False,True)
train.run(2000)
train.confusionMatix()
train = Train(df_en)
train.run(200000)
train.predict('vaico centering bush propshaft',2)