#!/usr/bin/env python # coding: utf-8 # ## Import Libs # In[54]: import pandas as pd import sklearn import numpy as np import matplotlib.pyplot as plt import random from pythainlp import word_tokenize, Tokenizer import re from sklearn.naive_bayes import MultinomialNB df_product_title = pd.read_csv('product_title_100.csv') df = df_product_title[df_product_title.subcategory!='อื่นๆ'].copy() target = df.iloc[:, 2] title = df.iloc[:, 4] rand = random.randint(0,len(df)) print('Target example:',target[rand:rand+1].values[0]) print('Title example:',title[rand:rand+1].values[0]) print('Token example:',word_tokenize(title[rand:rand+1].values[0],engine='longest')) def token_processing(token): res = re.sub(r'[^a-zก-๙1-9]', '', token.lower()) if res != '' : return res # In[234]: title_split = [] num=1 for i in list(title): word_split = word_tokenize(i,engine='longest') title_split_temp =[] for j in word_split: res = token_processing(j) if res != None : title_split_temp.append(res) title_split.append(title_split_temp) if num%1000==0 : print(num,'/',len(title)) num+=1 # In[235]: #title_split all_title_split = [] for i in title_split: for j in i : res = token_processing(j) if res != None : all_title_split.append(res) all_char= set(all_title_split) print(len(all_char)) char_map = dict(zip(all_char, range(len(all_char)))) # In[236]: def count_str(string): global all_char, char_map result = np.zeros(len(all_char)) np_str = np.array(list(string)) str_char, str_char_count = np.unique(np_str, return_counts=True) for char, count in zip(str_char, str_char_count): try: result[char_map[char]] = count except: pass return result # In[239]: # run on data set temp = np.vectorize(count_str, otypes=[object])(title_split) print('done1') # In[240]: test_2=[] num=0 for sl in temp: test =[] for e in sl: test.append(e) test_2.append(test) x_f1 = np.array(test_2) # In[242]: model = MultinomialNB(fit_prior=False, alpha = 0.1) model.fit(x_f1, target) y_pred = model.predict(x_f1) print("Model Acc. on train data %f%%" % ((target == y_pred).sum() / x_f1.shape[0] * 100)) # In[259]: def predict_prob_df(word): token = word_tokenize(word,engine='longest') clean_token = [] for i in token: res = token_processing(i) if res != None : clean_token.append(res) prob_each_class = (model.predict_proba(count_str(clean_token).reshape(1,-1))).tolist()[0] each_class_name = model.classes_.tolist() pr = pd.DataFrame(prob_each_class,each_class_name).reset_index().rename(columns={'index':'predict',0:'prob'}).sort_values('prob',ascending=False).reset_index() return pr # In[259] test 2 import gradio as gr pd.set_option('display.float_format', lambda x: '%5f' % x) demo = gr.Blocks() def subcat_predict(word): global pr, text_ text_ = word pr = predict_prob_df(word) return dict(zip(pr.loc[:2,'predict'],pr.loc[:2,'prob'])) log = [] log_correct= [] num = 0 num_2 = 0 def correct_number1(number): global num num+=1 log.append([text_,'1-right',pr.loc[0,'predict'],pr.loc[0,'prob']]) return 'thank for teaching the model' def correct_number2(number): global num log.append([text_,'1-wrong',pr.loc[0,'predict'],pr.loc[0,'prob']]) log.append([text_,'2-right',pr.loc[1,'predict'],pr.loc[1,'prob']]) return 'thank for teaching the model' def correct_number3(number): global num log.append([text_,'1-wrong',pr.loc[0,'predict'],pr.loc[0,'prob']]) log.append([text_,'2-wrong',pr.loc[1,'predict'],pr.loc[1,'prob']]) log.append([text_,'3-right',pr.loc[2,'predict'],pr.loc[2,'prob']]) return 'thank for teaching the model' def feedback(correction_input,text_input): global num , num_2 log.append([text_,'1-wrong',pr.loc[0,'predict'],pr.loc[0,'prob']]) log.append([text_,'2-wrong',pr.loc[1,'predict'],pr.loc[1,'prob']]) log.append([text_,'3-wrong',pr.loc[2,'predict'],pr.loc[2,'prob']]) log_correct.append([text_,'feedback',pr.loc[0,'predict'],pr.loc[0,'prob'],correction_input]) return 'thank for teaching the model' with demo: with gr.Row(): with gr.Column(): gr.Markdown("มาให้โมเดลทำนาย subcat จากชื่อ Product กันจ้า") with gr.Row(): text_input = gr.Textbox(label='พิมพ์ชื่อ product แล้วกด Predict! ได้เลยจ้า') predict_button = gr.Button("Predict!") predict_button.click(subcat_predict, inputs=text_input, outputs = gr.outputs.Label()) gr.Markdown("ถ้าโมเดลทำนายออกมาถูกแล้วช่วยกดปุ่มให้หน่อยครับว่าถูกที่อันดับไหน (1,2,3)") with gr.Row(): button_1 = gr.Button("1st is correct") button_2 = gr.Button("2nd is correct") button_3 = gr.Button("3rd is correct") thanks_box = gr.Textbox(label='') button_1.click(correct_number1, inputs=text_input,outputs=thanks_box) button_2.click(correct_number2, inputs=text_input,outputs=thanks_box) button_3.click(correct_number3, inputs=text_input,outputs=thanks_box) with gr.Column(): gr.Markdown("ถ้าโมเดลทำนายผิดหมด รบกวนใส่ subcat ที่ถูกให้หน่อยครัช") with gr.Row(): correction_input = gr.Dropdown(df.target.unique().tolist()) button_feedback = gr.Button("Send Feedback") button_feedback.click(feedback, inputs=[correction_input,text_input], outputs=gr.outputs.Textbox(label='')) demo.launch(share=True)