doc
This commit is contained in:
parent
79c44ac681
commit
86399459ed
7 changed files with 165 additions and 97 deletions
|
|
@ -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}
|
||||
|
|
@ -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"
|
||||
// // }
|
||||
// // }
|
||||
// // ]
|
||||
// // }
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -675,7 +675,7 @@
|
|||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.12"
|
||||
"version": "3.9.7"
|
||||
},
|
||||
"orig_nbformat": 4
|
||||
},
|
||||
|
|
|
|||
|
|
@ -193,11 +193,21 @@ class DataFrame:
|
|||
if (cats["language"]=="en"):
|
||||
list_row["category"]=cats["label"]
|
||||
|
||||
i=0
|
||||
categories =cats["path"].split('/')
|
||||
|
||||
if(list_row["name"]!=None and list_row["catL1"]!=None):
|
||||
for category in categories:
|
||||
list_row[f"catL{i+1}"] = category
|
||||
i= i+1
|
||||
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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": {
|
||||
"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'},
|
||||
'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": {}}})
|
||||
resp = self.es.search("retromotion-indexer_development_products",
|
||||
{
|
||||
"_source":
|
||||
["_id",
|
||||
"descriptions",
|
||||
"descriptionsSource",
|
||||
"nameSource",
|
||||
"shortDescriptionSource",
|
||||
"categoriesSource"
|
||||
]
|
||||
|
||||
return resp
|
||||
})
|
||||
|
||||
return resp
|
||||
|
|
|
|||
5
rm_clasificationmodel/KNN.py
Normal file
5
rm_clasificationmodel/KNN.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
class KNN():
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
|
|
@ -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__":
|
||||
|
|
|
|||
Loading…
Reference in a new issue