建了一個(gè)網(wǎng)站,用決策樹挑選西瓜!
↓↓↓點(diǎn)擊關(guān)注,回復(fù)資料,10個(gè)G的驚喜

在機(jī)器學(xué)習(xí)領(lǐng)域,有一個(gè)很有名氣的西瓜--周志華老師的《機(jī)器學(xué)習(xí)》,很多同學(xué)選擇這本書入門,都曾有被西瓜支配的恐懼。我寫文章的時(shí)候也特別喜歡用西瓜數(shù)據(jù)集,以它為例手算+可視化講解過XGBoost,自認(rèn)非常通俗易懂。
最近我介紹了決策樹的可視化,還有可以快速實(shí)現(xiàn)機(jī)器學(xué)習(xí)web應(yīng)用的神器——streamlit。今天我們就把它們結(jié)合起來,用機(jī)器學(xué)習(xí)幫華強(qiáng)挑西瓜!僅供娛樂,希望大家可以學(xué)到一些新姿勢(shì)。
項(xiàng)目已發(fā)布,歡迎大家試玩
https://share.streamlit.io/tjxj/watermelon-prediction/main/app.py
老規(guī)矩,先看效果圖(GIF刷新有點(diǎn)慢,請(qǐng)耐心等待)


使用方法
第一步,左側(cè)先選擇西瓜外觀

第二步,選擇決策樹的模型參數(shù)

第三步,看結(jié)果


實(shí)現(xiàn)方式
注:篇幅原因,僅貼出核心代碼
data.py
主要是原始數(shù)據(jù)的處理,inputData方法實(shí)現(xiàn)輸入外觀變量值的標(biāo)簽編碼。
def?inputData():
????st.sidebar.subheader("請(qǐng)選擇西瓜外觀:sunglasses:")
????color?=?st.sidebar.selectbox("色澤",?("青綠",?"烏黑",?"淺白"))
????root?=?st.sidebar.selectbox("根蒂",?("蜷縮",?"稍蜷",?"硬挺"))
????knocks?=?st.sidebar.selectbox("敲擊",?("濁響",?"沉悶",?"清脆"))
????texture?=?st.sidebar.selectbox("紋理",?("清晰",?"稍糊",?"模糊"))
????navel?=?st.sidebar.selectbox("臍部",?("凹陷",?"稍凹",?"平坦"))
????touch?=?st.sidebar.selectbox("觸感",?("硬滑",?"軟粘"))
????input?=?[[color,?root,?knocks,?texture,?navel,?touch]]
????features?=?["color",?"root",?"knocks",?"texture",?"navel",?"touch"]
????np.array(input).reshape(1,?6)
????df_input?=?pd.DataFrame(input,?columns=features,?index=None)
????for?feature?in?features[0:6]:
????????le?=?joblib.load("./models/"?+?feature?+?"_LabelEncoder.model")
????????df_input[feature]?=?le.transform(df_input[feature])
????return?df_input
訓(xùn)練模型
這一塊很簡(jiǎn)單,就不多解釋了。注:數(shù)據(jù)量太小就不整交叉驗(yàn)證了
def?dt_param_selector():
????st.sidebar.subheader("請(qǐng)選擇模型參數(shù):sunglasses:")
????criterion?=?st.sidebar.selectbox("criterion",?["gini",?"entropy"])
????max_depth?=?st.sidebar.number_input("max_depth",?1,?50,?5,?1)
????min_samples_split?=?st.sidebar.number_input(
????????"min_samples_split",?1,?20,?2,?1)
????max_features?=?st.sidebar.selectbox(
????????"max_features",?[None,?"auto",?"sqrt",?"log2"])
????params?=?{
????????"criterion":?criterion,
????????"max_depth":?max_depth,
????????"min_samples_split":?min_samples_split,
????????"max_features":?max_features,
????}
????model?=?DecisionTreeClassifier(**params)
????df?=?dataPreprocessing()
????X,?y?=?df[df.columns[:-1]],?df["label"]
????model.fit(X,?y)
????return?modeldef?predictor():
????df_input?=?inputData()
????model?=?dt_param_selector()
????y_pred?=?model.predict(df_input)
????if?y_pred?==?1:
????????goodwatermelon?=?Image.open("./pics/good.png")
????????st.image(goodwatermelon,width=705,use_column_width=?True)
????????st.markdown("??????這瓜甚甜,買一個(gè)?????? ",?unsafe_allow_html=True)
????else:
????????file_?=?open("./pics/bad2.gif",?"rb")
????????contents?=?file_.read()
????????data_url?=?base64.b64encode(contents).decode("utf-8")
????????file_.close()
????????st.markdown(
????????????f'',
????????????unsafe_allow_html=True,
????????)
????????st.markdown('??????這瓜不甜,買不得?????? ',?unsafe_allow_html=True)
????return?y_pred,model
決策樹可視化
決策樹可視化和插入網(wǎng)頁(yè)我用decisionTreeViz和svg_write實(shí)現(xiàn),可惜目前僅本地模式正常,發(fā)布后報(bào)錯(cuò),尚未解決。
def?decisionTreeViz():
????df,le?=?getDataSet()
????X,?y?=?df[df.columns[:-1]],?df["label"]
????clf?=?joblib.load('..\watermelonClassifier.pkl')
????viz?=?dtreeviz(clf,?
????????????????X,?
????????????????y,
????????????????orientation="LR",
????????????????target_name='label',
????????????????feature_names=df.columns[:-1],
????????????????class_names=["good","bad"]
????????????????)??
????????????????
????return?viz
def?svg_write(svg,?center=True):
????"""
????Disable?center?to?left-margin?align?like?other?objects.
????"""
????#?Encode?as?base?64
????b64?=?base64.b64encode(svg.encode("utf-8")).decode("utf-8")
????#?Add?some?CSS?on?top
????css_justify?=?"center"?if?center?else?"left"
????css?=?f''
????html?=?f'{css}'
????#?Write?the?HTML
????st.write(html,?unsafe_allow_html=True)
streamlit
過程就不說了,就把調(diào)用的streamlit API列一下吧
st.title
st.write
st.code
st.table
st.markdown
st.sidebar
st.expander
st.code
st.image
st.pyplot
以上API具體用途大家可以查一查https://docs.streamlit.io/library/api-reference
TODO
增加更多模型 dtreeviz決策樹可視化bug
決策樹可視化依賴graphviz,在localhost:8501下預(yù)覽可以顯示,發(fā)布到streamlit.io就不行了。GIF 不適配手機(jī)屏幕 移動(dòng)端預(yù)測(cè)壞瓜頁(yè)面刷新bug
以上問題,如有興趣,歡迎貢獻(xiàn)代碼。
推薦閱讀
決策樹可視化,被驚艷到了! 開發(fā)機(jī)器學(xué)習(xí)APP,太簡(jiǎn)單了 周志華教授:關(guān)于深度學(xué)習(xí)的一點(diǎn)思考 200 道經(jīng)典機(jī)器學(xué)習(xí)面試題總結(jié) 卷積神經(jīng)網(wǎng)絡(luò)(CNN)數(shù)學(xué)原理解析
如有收獲,歡迎三連??
