python 實(shí)現(xiàn)關(guān)聯(lián)規(guī)則算法Apriori的示例
首先導(dǎo)入包含apriori算法的mlxtend庫,
pip install mlxtend
調(diào)用apriori進(jìn)行關(guān)聯(lián)規(guī)則分析,具體代碼如下,其中數(shù)據(jù)集選取本博客 “機(jī)器學(xué)習(xí)算法——關(guān)聯(lián)規(guī)則” 中的例子,可進(jìn)行參考,設(shè)置最小支持度(min_support)為0.4,最小置信度(min_threshold)為0.1,
最小提升度(lift)為1.0,對(duì)數(shù)據(jù)集進(jìn)行關(guān)聯(lián)規(guī)則分析,
from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori from mlxtend.frequent_patterns import association_rules import pandas as pd df_arr = [['蘋果','香蕉','鴨梨'], ['橘子','葡萄','蘋果','哈密瓜','火龍果'], ['香蕉','哈密瓜','火龍果','葡萄'], ['橘子','橡膠'], ['哈密瓜','鴨梨','葡萄'] ] #轉(zhuǎn)換為算法可接受模型(布爾值) te = TransactionEncoder() df_tf = te.fit_transform(df_arr) df = pd.DataFrame(df_tf,columns=te.columns_) #設(shè)置支持度求頻繁項(xiàng)集 frequent_itemsets = apriori(df,min_support=0.4,use_colnames= True) #求關(guān)聯(lián)規(guī)則,設(shè)置最小置信度為0.15 rules = association_rules(frequent_itemsets,metric = 'confidence',min_threshold = 0.15) #設(shè)置最小提升度 rules = rules.drop(rules[rules.lift <1.0].index) #設(shè)置標(biāo)題索引并打印結(jié)果 rules.rename(columns = {'antecedents':'from','consequents':'to','support':'sup','confidence':'conf'},inplace = True) rules = rules[['from','to','sup','conf','lift']] print(rules) #rules為Dataframe格式,可根據(jù)自身需求存入文件
輸出結(jié)果如下:
from to sup conf lift 0 (哈密瓜) (火龍果) 0.4 0.666667 1.666667 1 (火龍果) (哈密瓜) 0.4 1.000000 1.666667 2 (哈密瓜) (葡萄) 0.6 1.000000 1.666667 3 (葡萄) (哈密瓜) 0.6 1.000000 1.666667 4 (葡萄) (火龍果) 0.4 0.666667 1.666667 5 (火龍果) (葡萄) 0.4 1.000000 1.666667 6 (哈密瓜, 葡萄) (火龍果) 0.4 0.666667 1.666667 7 (哈密瓜, 火龍果) (葡萄) 0.4 1.000000 1.666667 8 (葡萄, 火龍果) (哈密瓜) 0.4 1.000000 1.666667 9 (哈密瓜) (葡萄, 火龍果) 0.4 0.666667 1.666667 10 (葡萄) (哈密瓜, 火龍果) 0.4 0.666667 1.666667 11 (火龍果) (哈密瓜, 葡萄) 0.4 1.000000 1.666667 Process finished with exit code 0
以上就是python 實(shí)現(xiàn)關(guān)聯(lián)規(guī)則算法Apriori的示例的詳細(xì)內(nèi)容,更多關(guān)于python 實(shí)現(xiàn)關(guān)聯(lián)規(guī)則算法Apriori的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Gauss-Seidel迭代算法的Python實(shí)現(xiàn)詳解
這篇文章主要介紹了Gauss-Seidel迭代算法的Python實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-06-06Python實(shí)現(xiàn)購物評(píng)論文本情感分析操作【基于中文文本挖掘庫snownlp】
這篇文章主要介紹了Python實(shí)現(xiàn)購物評(píng)論文本情感分析操作,結(jié)合實(shí)例形式分析了Python使用中文文本挖掘庫snownlp操作中文文本進(jìn)行感情分析的相關(guān)實(shí)現(xiàn)技巧與注意事項(xiàng),需要的朋友可以參考下2018-08-08python except異常處理之后不退出,解決異常繼續(xù)執(zhí)行的實(shí)現(xiàn)
這篇文章主要介紹了python except異常處理之后不退出,解決異常繼續(xù)執(zhí)行的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04