diff --git a/doc/chapters/chapter3.tex b/doc/chapters/chapter3.tex index f3625cd..0f4f6d5 100644 --- a/doc/chapters/chapter3.tex +++ b/doc/chapters/chapter3.tex @@ -23,21 +23,21 @@ In table \ref{table:TN}, displays the difference in text before and after normal Using Pandas - vectorized string method, a text can be lower cased across the document. These methos exclude the missing / NA values automatically \parencite{mckinney-proc-scipy-2010}. -\begin{lstlisting}[language=Python] +\begin{lstlisting}[language=Python, caption={Pandas vectorized string method }] df_de["name"]= df_de["name"].str.lower() \end{lstlisting} \section{Html parsing} Probability of getting html tags in a document increases if the source of document is from web scraping or also if the document from database source has inline html tags. In such case, fetching normal texts from a html text is required. One of the method would be to use regular expressions to get text in between angel brackets \textless \textgreater text \textless \textgreater. However, this method would require to have the tags to be well formed. -\begin{lstlisting}[language=Python] +\begin{lstlisting}[language=Python, caption={Regular expression to get text from html}] text = re.sub('<[^>]*>', '', text) \end{lstlisting} The better option would be to use Beautiful Soup \footnote{https://www.crummy.com/software/BeautifulSoup/bs4/doc/} a Pyhon library for pulling data out of HTLM and XML. -\begin{lstlisting}[language=Python] +\begin{lstlisting}[language=Python, caption={Beautiful soap API to get text from html}] # Remove html tags soup = BeautifulSoup(doc, 'html.parser') text =soup.get_text() @@ -46,7 +46,7 @@ The better option would be to use Beautiful Soup \footnote{https://www.crummy.co \section{Cleanning text} A product detail text may contain non-word characters represented in regular expression as \textbackslash W. It may also contain space seperated decimals describing the dimentional values of the product such as weight, height. Regular expressions could be used for removing the non-character words and spaces between the decimal values. -\begin{lstlisting}[language=Python] +\begin{lstlisting}[language=Python,,caption={Clean text with Regular expression}] text = (re.sub('[-\W]+', ' ', text)) text = (re.sub('(?<=\d) (?=\d)', '', text)) \end{lstlisting} @@ -54,7 +54,7 @@ A product detail text may contain non-word characters represented in regular exp \section{Normal form D - Unicode database} A product name in Deutsch language may contain umlaute characters such as \"A. Pythons unicodedata \footnote{https://docs.python.org/3/library/unicodedata.html} module provides access to the Unicode Character Database (UCD) which defines the character properties for all Unicode characters. To change \"A to A, the Normal form D (NFD) should be applied which translated each character into its decomposed form. Further the text can be refined with the general category assigned to the character as string. Nonspacing mark characters \footnote{https://www.compart.com/en/unicode/category/Mn} are represented as "Mn". These characters could be removed by referring the the character category. -\begin{lstlisting}[language=Python] +\begin{lstlisting}[language=Python ,caption={NFD normalization}] ''.join( c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn') diff --git a/doc/chapters/chapter4.tex b/doc/chapters/chapter4.tex index 1dbe190..8a2a04d 100644 --- a/doc/chapters/chapter4.tex +++ b/doc/chapters/chapter4.tex @@ -10,7 +10,7 @@ Machine learning algorithm to predict values in a categorical variable based on \begin{table}[h] \centering - \caption{Feature imputation} + \caption{Identify categorical features} \label{table:feature_imputation} \begin{tabular}{ lll } \toprule @@ -38,7 +38,7 @@ In an iterated round-robin fashion, at every step a missing feature column \tex Replacing the most frequent categorical value in a column is known as mode imputation. Pandas.DataFrame.mode \parencite{mckinney-proc-scipy-2010} function returns most often value. Code snippet will fill the missing values for each column using its own most frequent value. -\begin{lstlisting}[language=Python] +\begin{lstlisting}[language=Python, caption={Pandas DataFrames mode function}] df = df.fillna(df.mode().iloc[0]) \end{lstlisting} @@ -46,9 +46,9 @@ Mode imputation on categorical data are prone to fill incorrect data if the miss -\section{\textit{k}-Nearest Neighbors imputation} +\section{\acf{KNN} imputation} -k-Nearest Neighbor is a supervised learning algorithm is used to search dataset with the most similar elements to a given query element, with similarity defined by a distance function. This imputation method is suitable for categorical data. +\acl{KNN} is a supervised learning algorithm is used to search dataset with the most similar elements to a given query element, with similarity defined by a distance function. This imputation method is suitable for categorical data. The most common distance functions are:- @@ -60,11 +60,9 @@ The most common distance functions are:- sklearn.neighbors.KNeighborsClassifier \parencite{scikit-learn} does an instance-based learning, it does not construct a model, but stores instance of training data. Classification is computed from majority vote of nearest neighbors of each point. -The \textit{k}-neighbors classification implements learning based on \textit{k} nearest neighbors of each query point, where \textit{K} is integer value specified by user. +The \textit{k}-neighbors classification implements learning based on \textit{k} nearest neighbors of each query point, where \textit{k} is integer value specified by user. The optimal \textit{k} value can be evaluated by iterating the classifier with different \textit{n\textunderscore neighbors} parameter and finding the minimum value of error rate. As per \parencite{scikit-learn}, larger \textit{k} suppresses the effects of noise, but makes the classification boundaries less distinct. -The optimal \textit{k} value can be evaluated by iterating the classifier with different \textit{n\textunderscore neighbors} parameter and finding the minimum value of error rate. - -\begin{lstlisting}[language=Python] +\begin{lstlisting}[language=Python, caption={Find optimal \textit{k} value in \acl{KNN} }] error_rate = [] for i in range(1,40): knn = KNeighborsClassifier(n_neighbors=i) @@ -75,11 +73,12 @@ The optimal \textit{k} value can be evaluated by iterating the classifier with d print("Minimum error:-",min(error_rate),"at K =",error_rate.index(min(error_rate))) \end{lstlisting} -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 8 columns. Target column is 'catL3' which is the category at level three. +\subsection{\acs{KNN} model implementation} + +In table \ref{table:KNN_implementation} there are 7 columns. Target column is \textbf{Category-Level-3} which is the category at level three. +As per the sample category hierarchy, the @@ -87,24 +86,25 @@ In table \ref{table:KNN_implementation} there are 8 columns. Target column is 'c \centering \caption{Data frame head} \label{table:KNN_implementation} - \begin{tabular}{llll} - \toprule id & name & shortDesc & Desc \\ - \midrule + \begin{tabular}{ll} + \toprule + \textbf{Name}& \textit{product name} \\ + \textbf{Description}& \textit{product description} \\ + \textbf{Short-Description}& \textit{product short description} \\ + \textbf{Category-Level-1}& Spare-Part \\ + \textbf{Category-Level-2}& Cooling System \\ + \textbf{Category-Level-3}& Thermostat \\ + \textbf{Category-Level-4}& NaN \textit{product has no level 4 category} \\ + \bottomrule + \end{tabular} - 1&DENSO DTM82363 & NaN & NaN \\ - \bottomrule -\end{tabular} - -\begin{tabular}{llll} - \toprule catL1 & catL2 & catL3 & catL4\\ - \midrule - - SparePart & Cooling System & Thermostat & NaN \\ - \bottomrule -\end{tabular} \end{table} - +\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} value equal to the optimal value. +\end{itemize} \begin{lstlisting}[language=Python] X = df.drop(['catL3'], axis = 1) @@ -122,11 +122,7 @@ In table \ref{table:KNN_implementation} there are 8 columns. Target column is 'c 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} diff --git a/doc/index.tex b/doc/index.tex index e5c997b..2dd8289 100644 --- a/doc/index.tex +++ b/doc/index.tex @@ -78,6 +78,7 @@ chapters/chapter5 \tableofcontents \listoffigures \listoftables +\lstlistoflistings \include{preliminary/acronyms} %----------------- chapters -------------------- diff --git a/doc/preliminary/acronyms.tex b/doc/preliminary/acronyms.tex index 0095e9a..01ee54f 100644 --- a/doc/preliminary/acronyms.tex +++ b/doc/preliminary/acronyms.tex @@ -26,6 +26,7 @@ \acro{Tf-Idf}[Tf-Idf]{Term frequency-Inverse document frequency} \acro{Tf}[Tf-Idf]{Term frequency} \acro{Idf}[Idf]{Inverse document frequency} +\acro{KNN}[KNN]{\textit{k} -Nearest Neighbors} \end{acronym} diff --git a/rm_clasificationmodel/DataFrameClass.py b/rm_clasificationmodel/DataFrameClass.py index 292f63d..7d72e3f 100644 --- a/rm_clasificationmodel/DataFrameClass.py +++ b/rm_clasificationmodel/DataFrameClass.py @@ -32,16 +32,17 @@ class DataFrame: def normalize(self,doc): # Remove html tags - soup = BeautifulSoup(doc, 'html.parser') - text =soup.get_text() - text = (re.sub('[-\W]+', ' ', text)) - text = (re.sub('(?<=\d) (?=\d)', '', text)) - text = (re.sub("([a-z]\d+)|(\d+)", '', text)) - - - return ''.join( - c for c in unicodedata.normalize('NFD', text) - if unicodedata.category(c) != 'Mn') + if doc: + soup = BeautifulSoup(doc, 'html.parser') + text =soup.get_text() + text = (re.sub('[-\W]+', ' ', text)) + text = (re.sub('(?<=\d) (?=\d)', '', text)) + text = (re.sub("([a-z]\d+)|(\d+)", '', text)) + + + return ''.join( + c for c in unicodedata.normalize('NFD', text) + if unicodedata.category(c) != 'Mn') # text= text.replace('-', '') @@ -177,6 +178,7 @@ class DataFrame: def setDfProductTaxonomy(self,lang='en'): + resp=self.es.searchDevelopmentProducts() df = pd.DataFrame(columns=["id",'name','shortDesc','Desc','category','catL1','catL2','catL3','catL4','catL5']) @@ -184,29 +186,34 @@ class DataFrame: list_row = dict (id=None,name=None,shortDesc=None,Desc=None,catL1=None,catL2=None,catL3=None,catL4=None,catL5=None) list_row["id"]=hit['_id'] - for name in hit['_source']['nameSource']: - if (name["language"]==lang): - list_row["name"]=name["value"] + if 'nameSource' in hit['_source']: + for name in hit['_source']['nameSource']: + if (name["language"]==lang): + list_row["name"]=name["value"] - for sd in hit['_source']['shortDescriptionSource']: - if (name["language"]==lang): - list_row["shortDesc"]=sd["value"] + if 'shortDescriptionSource' in hit['_source']: + for sd in hit['_source']['shortDescriptionSource']: + if (sd["language"]==lang): + list_row["shortDesc"]=sd["value"] - for ds in hit['_source']['descriptionsSource']: - if (name["language"]==lang): - list_row["Desc"]=ds["value"] + + if 'descriptionsSource' in hit['_source']: + for ds in hit['_source']['descriptionsSource']: + if (ds["language"]==lang): + list_row["Desc"]=ds["value"] - for cats in hit['_source']['categoriesSource']: - if (cats["language"]=="en"): - list_row["category"]=cats["label"] + if 'categoriesSource' in hit['_source']: + for cats in hit['_source']['categoriesSource']: + if (cats["language"]=="en"): + list_row["category"]=cats["label"] - i=0 - categories =cats["path"].split('/') + i=0 + categories =cats["path"].split('/') - for category in categories: - list_row[f"catL{i+1}"] = category - i= i+1 + for category in categories: + list_row[f"catL{i+1}"] = category + i= i+1 @@ -215,8 +222,54 @@ class DataFrame: df=pd.concat([df, new_row.to_frame().T], ignore_index=True) return df + + def createProductFeature(self): + resp =self.es.searchProductFeatures(0,10000) + df = pd.DataFrame(columns=['name','shortDesc','Desc','category','catL1','catL2','catL3','catL4','catL5']) + for hit in resp['hits']['hits']: + list_row = dict (name=None,shortDesc=None,Desc=None,catL1=None,catL2=None,catL3=None,catL4=None,catL5=None) + + # list_row["id"]=hit['_source']['id'] + + list_row["name"]=hit['_source']['name'] + list_row["shortDesc"]=hit['_source']['shortDesc'] + list_row["Desc"]=hit['_source']['Desc'] + list_row["category"]=hit['_source']['category'] + for i in range(1,5): + list_row[f"catL{i}"] = hit['_source'][f"catL{i}"] + + + if(list_row["name"]!=None): + new_row = pd.Series(list_row) + df=pd.concat([df, new_row.to_frame().T], ignore_index=True) + + + + df = self.cleanData(df) + df=df.drop_duplicates() + self.es.createIndexerProductFeatureNormal() + + doc = df.to_dict(orient='records') + self.es.ingestProductFeaturesNormal(doc) + + + def cleanData(self,df): + + + + df["name"] = df["name"].str.lower().apply(lambda n:self.normalize(n)) + df["shortDesc"] = df["shortDesc"].str.lower().apply(lambda c:self.normalize(c)) + df["Desc"] = df["Desc"].str.lower().apply(lambda c:self.normalize(c)) + df["Desc"] = df["Desc"].str.lower().apply(lambda c:self.normalize(c)) + df["category"] = df["category"].str.lower().apply(lambda c:self.normalize(c)) + for i in range(1,5): + df[f"catL{i}"] = df[f"catL{i}"].str.lower().apply(lambda c:self.normalize(c)) + return df + + + diff --git a/rm_clasificationmodel/ElasticSearchClass.py b/rm_clasificationmodel/ElasticSearchClass.py index db8d970..5c26a56 100644 --- a/rm_clasificationmodel/ElasticSearchClass.py +++ b/rm_clasificationmodel/ElasticSearchClass.py @@ -24,6 +24,7 @@ class ElasticSearchDb: self.es.indices.create(index=_index, body=request_body) def createIndexerPrediction(self, docDict): + request_body = { "settings": { "number_of_shards": 5, @@ -48,20 +49,103 @@ class ElasticSearchDb: for val in docDict: self.ingest('english-false-prediction', val, 'category_prediction') + - def searchDevelopmentProducts(self): - resp = self.es.search(index="retromotion-indexer_development_products", + + def createIndexerProductFeature(self): + + docType="product_feature" + request_body = { + "settings": { + "number_of_shards": 5, + "number_of_replicas": 1 + }, + 'mappings': { + docType: { + + 'properties': { + 'id': {'type': 'text'}, + 'name': {'type': 'text'}, + 'shortDesc':{'type': 'text'}, + 'Desc':{'type': 'text'}, + 'category': {'type': 'text'}, + 'catL1': {'type': 'text'}, + 'catL2': {'type': 'text'}, + 'catL3': {'type': 'text'}, + 'catL4': {'type': 'text'}, + 'catL5': {'type': 'text'}, + } + } + } + } + + self.create('english-product-feature',request_body) + + def ingestProductFeatures(self,docDict): + for val in docDict: + + self.ingest('english-product-feature', val, 'product_feature') + + + + def searchProductFeatures(self, _from,_size): + resp = self.es.search(index="english-product-feature", body={ - "_source": - ["_id", - "descriptions", - "descriptionsSource", - "nameSource", - "shortDescriptionSource", - "categoriesSource" - ], - "size":65000 - + 'from':_from, + 'size' :_size, }) return resp + + + def searchDevelopmentProducts(self): + resp = self.es.search(index="retromotion-indexer_development_products", + body={ + "_source": + ["_id", + "descriptions", + "descriptionsSource", + "nameSource", + "shortDescriptionSource", + "categoriesSource" + ], + "size":65000 + + }) + + return resp + + + def createIndexerProductFeatureNormal(self): + + docType="product_feature_normal" + request_body = { + "settings": { + "number_of_shards": 5, + "number_of_replicas": 1 + }, + 'mappings': { + docType: { + + 'properties': { + + 'name': {'type': 'text'}, + 'shortDesc':{'type': 'text'}, + 'Desc':{'type': 'text'}, + 'category': {'type': 'text'}, + 'catL1': {'type': 'text'}, + 'catL2': {'type': 'text'}, + 'catL3': {'type': 'text'}, + 'catL4': {'type': 'text'}, + 'catL5': {'type': 'text'}, + } + } + } + } + + self.create('english-product-feature-normal',request_body) + + def ingestProductFeaturesNormal(self,docDict): + for val in docDict: + + self.ingest('english-product-feature-normal', val, 'product_feature_normal') diff --git a/rm_clasificationmodel/KNN.py b/rm_clasificationmodel/KNN.py index 105bbca..add2f44 100644 --- a/rm_clasificationmodel/KNN.py +++ b/rm_clasificationmodel/KNN.py @@ -4,6 +4,4 @@ from sklearn.neighbors import KNeighborsClassifier class KNN(): def __init__(self) -> None: - pass - - \ No newline at end of file + pass \ No newline at end of file diff --git a/rm_clasificationmodel/main.py b/rm_clasificationmodel/main.py index 054ef6c..39c096a 100644 --- a/rm_clasificationmodel/main.py +++ b/rm_clasificationmodel/main.py @@ -13,10 +13,17 @@ import pandas as pd def main(): es =ElasticSearchDb("http://localhost:9200") + + # resp =es.searchProductFeatures(0,10000) + # es.createIndexerProductFeature() helper = Helper() df=DataFrame(es) - df_prod= df.setDfProductTaxonomy() + df.createProductFeature() + # df_prod= df.setDfProductTaxonomy() + # doc = df_prod.to_dict(orient='records') + + # es.ingestProductFeatures(doc) # dfProductTaxonomyEn=df.getProductTaxonomy(10000,0) # df_en = df.getNormal() # # train = Train(df_en)