From 86399459ed0222650e71039fe640aa97d6ea47a2 Mon Sep 17 00:00:00 2001 From: "shoney.arickathil" Date: Sun, 16 Jul 2023 00:27:23 +0200 Subject: [PATCH] doc --- doc/chapters/chapter4.tex | 72 +++++++++++++++--- fetchDatafromDb/getProductDescriptionCat.es | 38 +++++----- fetchDatafromDb/getProductDetails.ipynb | 2 +- rm_clasificationmodel/DataFrameClass.py | 12 ++- rm_clasificationmodel/ElasticSearchClass.py | 84 +++++++++++---------- rm_clasificationmodel/KNN.py | 5 ++ rm_clasificationmodel/main.py | 49 ++++++------ 7 files changed, 165 insertions(+), 97 deletions(-) create mode 100644 rm_clasificationmodel/KNN.py diff --git a/doc/chapters/chapter4.tex b/doc/chapters/chapter4.tex index 8abcb8b..3baaf3f 100644 --- a/doc/chapters/chapter4.tex +++ b/doc/chapters/chapter4.tex @@ -44,18 +44,7 @@ Replacing the most frequent categorical value in a column is known as mode imput Mode imputation on categorical data are prone to fill incorrect data if the missing data is not the most frequent one. -\section{Mean/median imputation} -Pandas.DataFrame.median \parencite{mckinney-proc-scipy-2010} returns the median value. These can be applied to the features represented in numerical value. In reference to table \ref{table:feature_imputation}, \textit{price} could be a column on which median value can be filled. However, using median to fill missing value could underestimate or overestimate the value. - -\begin{enumerate} - \item Median - The mid point value - \item Mean - The average value -\end{enumerate} - -\begin{lstlisting}[language=Python] - df = df.fillna(df.median().iloc[0]) -\end{lstlisting} \section{\textit{k}-Nearest Neighbors imputation} @@ -88,3 +77,64 @@ The optimal \textit{k} value can be evaluated by iterating the classifier with d As per \parencite{scikit-learn}, larger \textit{k} suppresses the effects of noise, but makes the classification boundaries less distinct. +\subsection{KNN model implementation} + +In table \ref{table:KNN_implementation} there are nine columns. Target column is 'catL3' which is the category at level three. + +\begin{table}[h] + \centering + \caption{Data frame head} + \label{table:KNN_implementation} + \begin{tabular}{ lll } + \toprule + + \textbf{No}& \textbf{Feature} & \textbf{Categorical}\\ + \midrule + 1&Product name & No\\ + 3&Description & No\\ + 4&Short description & No\\ + 5&Supplier & Yes\\ + 6&Manufacturer & Yes\\ + 7&Price & No \\ + 8&Dimension & Yes\\ + \bottomrule + \end{tabular} +\end{table} + + + + +\begin{lstlisting}[language=Python] + X = df.drop(['catL3'], axis = 1) + y = df['catL3'] + from sklearn import preprocessing + X = preprocessing.StandardScaler().fit(X).transform(X.astype(float)) + from sklearn.model_selection import train_test_split + X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4) + from sklearn.neighbors import KNeighborsClassifier + from sklearn import metrics + #Train Model and Predict + k = 3 + neigh = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train) + Pred_y = neigh.predict(X_test) + print("Accuracy of model at K=3 is",metrics.accuracy_score(y_test, Pred_y)) +\end{lstlisting} + +\begin{itemize} + \item Collect independent data features into the X data frame and target field into a y data frame. + \item Split data into training and testing. + \item Import the classifier model from sklearn library and fit the model with \textit{k} equal to the optimal value. +\end{itemize} + +\section{Mean/median imputation} + +Pandas.DataFrame.median \parencite{mckinney-proc-scipy-2010} returns the median value. These can be applied to the features represented in numerical value. In reference to table \ref{table:feature_imputation}, \textit{price} could be a column on which median value can be filled. However, using median to fill missing value could underestimate or overestimate the value. + +\begin{enumerate} + \item Median - The mid point value + \item Mean - The average value +\end{enumerate} + +\begin{lstlisting}[language=Python] + df = df.fillna(df.median().iloc[0]) +\end{lstlisting} \ No newline at end of file diff --git a/fetchDatafromDb/getProductDescriptionCat.es b/fetchDatafromDb/getProductDescriptionCat.es index cd79123..2695fc6 100644 --- a/fetchDatafromDb/getProductDescriptionCat.es +++ b/fetchDatafromDb/getProductDescriptionCat.es @@ -1,24 +1,24 @@ Get retromotion-indexer_development_products/_search { - "_source":["_id","descriptions","descriptionsSource","nameSource","shortDescriptionSource","categoriesSource"], - "query": { - "match_all":{} - // "bool": { - // // "filter": { - // // "term": { - // // "order.paymentReceived": "true" - // // // "status": "canceled" - // // } - // // }, - // "must": [ - // { - // "term": { - // "products.sku": "0000-3289946" - // } - // } - // ] - // } - } + "_source":["_id","descriptions","descriptionsSource","nameSource","shortDescriptionSource","categoriesSource"] + // "query": { + // "match_all":{} + // // "bool": { + // // // "filter": { + // // // "term": { + // // // "order.paymentReceived": "true" + // // // // "status": "canceled" + // // // } + // // // }, + // // "must": [ + // // { + // // "term": { + // // "products.sku": "0000-3289946" + // // } + // // } + // // ] + // // } + // } } diff --git a/fetchDatafromDb/getProductDetails.ipynb b/fetchDatafromDb/getProductDetails.ipynb index 39f7958..a537102 100644 --- a/fetchDatafromDb/getProductDetails.ipynb +++ b/fetchDatafromDb/getProductDetails.ipynb @@ -675,7 +675,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.12" + "version": "3.9.7" }, "orig_nbformat": 4 }, diff --git a/rm_clasificationmodel/DataFrameClass.py b/rm_clasificationmodel/DataFrameClass.py index 44b4fae..16dbb8a 100644 --- a/rm_clasificationmodel/DataFrameClass.py +++ b/rm_clasificationmodel/DataFrameClass.py @@ -192,12 +192,22 @@ class DataFrame: for cats in hit['_source']['categoriesSource']: if (cats["language"]=="en"): list_row["category"]=cats["label"] + + i=0 + categories =cats["path"].split('/') + + for category in categories: + list_row[f"catL{i+1}"] = category + i= i+1 + - if(list_row["name"]!=None and list_row["catL1"]!=None): + if(list_row["name"]!=None): new_row = pd.Series(list_row) df=pd.concat([df, new_row.to_frame().T], ignore_index=True) + return df + diff --git a/rm_clasificationmodel/ElasticSearchClass.py b/rm_clasificationmodel/ElasticSearchClass.py index 30d1a05..0a87575 100644 --- a/rm_clasificationmodel/ElasticSearchClass.py +++ b/rm_clasificationmodel/ElasticSearchClass.py @@ -1,64 +1,66 @@ from elasticsearch import Elasticsearch + + class ElasticSearchDb: - def __init__(self,url): - self.url=url + def __init__(self, url): + self.url = url self.es = Elasticsearch(url) - def search(self,_index,doc): + def search(self, _index, doc): resp = self.es.search(index=_index, - body=doc) + body=doc) return resp - - def ingest(self,_index,doc,type): + + def ingest(self, _index, doc, type): self.es.index( index=_index, body=doc, doc_type=type - ) - - def create(self,_index,request_body): + ) + + def create(self, _index, request_body): self.es.indices.create(index=_index, body=request_body) - - def createIndexerPrediction(self,docDict): + + def createIndexerPrediction(self, docDict): request_body = { - "settings": { - "number_of_shards": 5, - "number_of_replicas": 1 - }, - 'mappings': { - "category_prediction": { - - 'properties': { - 'id': {'type': 'text'}, - 'name': {'type': 'text'}, - 'category': {'type': 'text'}, - 'predicted': {'type': 'text'}, - 'value': {'type': 'float'}, + "settings": { + "number_of_shards": 5, + "number_of_replicas": 1 + }, + 'mappings': { + "category_prediction": { + + 'properties': { + 'id': {'type': 'text'}, + 'name': {'type': 'text'}, + 'category': {'type': 'text'}, + 'predicted': {'type': 'text'}, + 'value': {'type': 'float'}, + } } } } - } # self.create('english-false-prediction',request_body) - for val in docDict: - - self.ingest('english-false-prediction',val,'category_prediction') + + self.ingest('english-false-prediction', val, 'category_prediction') def searchDevelopmentProducts(self): - resp=self.es.search("retromotion-indexer_development_products", - {"_source": - ["_id", - "descriptions", - "descriptionsSource", - "nameSource", - "shortDescriptionSource", - "categoriesSource" - ], - 'size' : 65000, - "query": {"match_all": {}}}) - - return resp + resp = self.es.search("retromotion-indexer_development_products", + { + "_source": + ["_id", + "descriptions", + "descriptionsSource", + "nameSource", + "shortDescriptionSource", + "categoriesSource" + ] + + }) + + return resp diff --git a/rm_clasificationmodel/KNN.py b/rm_clasificationmodel/KNN.py new file mode 100644 index 0000000..569f341 --- /dev/null +++ b/rm_clasificationmodel/KNN.py @@ -0,0 +1,5 @@ +class KNN(): + def __init__(self) -> None: + pass + + \ No newline at end of file diff --git a/rm_clasificationmodel/main.py b/rm_clasificationmodel/main.py index 3f3efd0..054ef6c 100644 --- a/rm_clasificationmodel/main.py +++ b/rm_clasificationmodel/main.py @@ -12,39 +12,40 @@ import pandas as pd def main(): - es =ElasticSearchDb("http://172.17.212.35:9200") + es =ElasticSearchDb("http://localhost:9200") helper = Helper() df=DataFrame(es) - dfProductTaxonomyEn=df.getProductTaxonomy(10000,0) - df_en = df.getNormal() - # train = Train(df_en) - # train.run(300000,30000,3000) - predict = Predict() + df_prod= df.setDfProductTaxonomy() + # dfProductTaxonomyEn=df.getProductTaxonomy(10000,0) + # df_en = df.getNormal() + # # train = Train(df_en) + # # train.run(300000,30000,3000) + # predict = Predict() - # predict.confusionMatix(df_en) - df_prediction=pd.DataFrame(columns=["id",'name','category','predicted','value']) - list_row_en = dict (id=None,name=None,category=None,predicted=None,value=None) - list =[] - for index, row in dfProductTaxonomyEn.iterrows(): - predicted =predict.start(row["name"].lower()) - actualCategory=helper.normalize(row["category"]) + # # predict.confusionMatix(df_en) + # df_prediction=pd.DataFrame(columns=["id",'name','category','predicted','value']) + # list_row_en = dict (id=None,name=None,category=None,predicted=None,value=None) + # list =[] + # for index, row in dfProductTaxonomyEn.iterrows(): + # predicted =predict.start(row["name"].lower()) + # actualCategory=helper.normalize(row["category"]) - if(predicted[0][1]!=actualCategory.lower()): - list_row = dict (id=None,name=None,category=None,predicted=None,value=None) - list_row["id"] =row["id"] - list_row["name"] =row["name"] - list_row["category"] =row["category"] - list_row["predicted"] =predicted[0][1] - list_row["value"] =predicted[0][0] + # if(predicted[0][1]!=actualCategory.lower()): + # list_row = dict (id=None,name=None,category=None,predicted=None,value=None) + # list_row["id"] =row["id"] + # list_row["name"] =row["name"] + # list_row["category"] =row["category"] + # list_row["predicted"] =predicted[0][1] + # list_row["value"] =predicted[0][0] - list.append(list_row) + # list.append(list_row) - # new_row = pd.Series(list_row) - # df_prediction=pd.concat([df_prediction, new_row.to_frame().T], ignore_index=True) - es.createIndexerPrediction(list) + # # new_row = pd.Series(list_row) + # # df_prediction=pd.concat([df_prediction, new_row.to_frame().T], ignore_index=True) + # es.createIndexerPrediction(list) if __name__=="__main__":