机器学习与数据挖掘机器学习

Naive_Bayes分类器,Cart、Adaboost的skl

2019-05-22  本文已影响25人  小Bill
屏幕快照 2019-05-22 上午11.17.02.png
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 21 19:55:47 2019

@author: xx
"""
from functools import reduce
import pandas as pd
import pprint

class Classifier():
    data = None
    class_attr = None
    priori = {}
    cp = {}
    hypothesis = None


    def __init__(self,filename=None, class_attr=None ):
        self.data = pd.read_csv(filename, header =(0)) #列索引
        self.class_attr = class_attr                    

    '''
        概率(类)     =           它出现在列中的次数
                             __________________________________________
                                  所有类属性的计数
    '''
    def calculate_priori(self):
        class_values = list(set(self.data[self.class_attr])) #{'no', 'yes'},['no', 'yes']
        class_data =  list(self.data[self.class_attr]) #['no', 'no', 'yes', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'no']
        for i in class_values:                        #yes , no
            self.priori[i]  = class_data.count(i)/len(class_data)# class_data.count(i) 5,9
        print ("Priori Values: ", self.priori)      #Priori Values:  {'no': 0.35714285714285715, 'yes': 0.6428571428571429}

    '''
         
        P(结果|证据)=            P(证据的可能性)x结果的先验概率
                            ___________________________________________
                                    P(证据)
    '''
    def get_cp(self, attr, attr_type, class_value):
        data_attr = list(self.data[attr])#所有数据,每一躺分别是一个索引下的14个数据。
        class_data = list(self.data[self.class_attr])#yes,no数据,['no', 'no', 'yes', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'no']
        total =0
        for i in range(0, len(data_attr)):# i = 0 :14,
            if class_data[i] == class_value and data_attr[i] == attr_type: #class_value:yes,no,attr_type:输入的type
                total+=1
        #print(data_attr.count(attr_type))
        #print(total)
        return total/data_attr.count(attr_type) #此处公式为P(B|A) = P(A|B)/P(A),下面reduce处再乘以P(B)

    '''
        在这里,我们计算证据的可能性和先验的多个所有个体概率
         (结果|多重证据)= P(证据1 |结果)×P(证据2 |结果)x ... x P(证据N |结果)×P(结果)
         按比例缩放(多重证据)
    '''
    def calculate_conditional_probabilities(self, hypothesis):
        for i in self.priori:   #yes,no
            self.cp[i] = {}
            for j in hypothesis: #二重循环,第一重:最终需要比较i层循环,合适不合适的概率,第二重:4个列索引数据
                self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})#字典索引hypothesis[j]:假设情况,j:Outlook,Temp,Humidity,Windy
        print ("\n计算条件概率: \n")
        pprint.pprint(self.cp)

    def classify(self):
        print ("结果: ")
        for i in self.cp:
            print(self.cp[i].values())
            print(self.priori[i])
            print (i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i])

if __name__ == "__main__":
    c = Classifier(filename="new_dataset.csv", class_attr="Play" )
    c.calculate_priori()
    c.hypothesis = {"Outlook":'Sunny', "Temp":"Hot", "Humidity":'High' , "Windy":'t'}
    c.calculate_conditional_probabilities(c.hypothesis)
    c.classify()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 20:11:50 2019

@author: xx
"""

# 导入库
import numpy as np  # 导入numpy库
import pandas as pd
from sklearn import tree    #导入sklearn的决策树模型(包括分类和回归两种)
import pydotplus    #画句子的依存结构树
import graphviz


#画决策树pdf图   (DataFrame)
def tree_showpdf(data,labels):
    a = data.iloc[:,:-1]    #特征矩阵
    b = data.iloc[:,-1]     #目标变量
    clf = tree.DecisionTreeClassifier() #分类决策树criterion='gini'
    clf.fit(a,b)    #训练

    dot_data = tree.export_graphviz(clf, out_file=None,
                         filled=True, rounded=True, feature_names=labels,
                         special_characters=True) 
        
    graph = pydotplus.graph_from_dot_data(dot_data)
    graph.write_pdf("tree.pdf")  #保存树图tree.pdf
    return clf
    
 
def change(data):
    names = data.columns[:-1] #前四列索引,DataFrame
    for i in names:
        col = pd.Categorical(data[i])
        data[i] = col.codes
    print(data)
        
def predict(data,clf):
    result = clf.predict([[2,0,0,0]])#手动输入待预测值
    print("预测值:",result)

    
if __name__=="__main__":
    data = pd.read_csv("new_dataset2.csv") #读取文件
    labelsp = list(data.columns.values)
    labels = labelsp[0:4]#读列索引
    change(data)        #转换非大小离散型为数值型
    clf = tree_showpdf(data,labels)  #画树图
    predict(data,clf) #预测

    

'''
dataSet = np.array(pd.read_csv("/Users/makangbo/Desktop/new_dataset2.csv")).tolist()#读所有数据
raw_data = pd.read_csv("/Users/makangbo/Desktop/new_dataset2.csv")
data = np.array(df.loc[:,:])
labelsp = list(df.columns.values)
labels = labelsp[0:4]#读列索引
'''

result.png

决策树,可以根据feature直接看出来属于哪一类。


.png
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import AdaBoostClassifier
import numpy as np  # 导入numpy库
import pandas as pd
from sklearn import tree    #导入sklearn的决策树模型(包括分类和回归两种)

#画决策树pdf图   (DataFrame)
def Adaboost(data):
    a = data.iloc[:,:-1]    #特征矩阵
    b = data.iloc[:,-1]     #目标变量
    #设定弱分类器CART
    weakClassifier=tree.DecisionTreeClassifier(max_depth=1)
    #设定Adaboost强分类器
    clf = AdaBoostClassifier(base_estimator=weakClassifier,algorithm='SAMME',n_estimators=1,learning_rate=0.9)
    clf.fit(a,b)
    print("评分:",clf.score(a,b))
    return clf
 
def change(data):
    names = data.columns[:-1] #前四列索引,DataFrame
    for i in names:
        col = pd.Categorical(data[i])
        data[i] = col.codes
    print(data)
        
def Predict(data,clf):
    result = clf.predict([[0,1,1]])#手动输入待预测值
    print("预测值:",result)

    
if __name__=="__main__":
    data = pd.read_csv("new_dataset3.csv") #读取文件
    labelsp = list(data.columns.values)
    labels = labelsp[0:4]#读列索引
    change(data)        #转换非大小离散型为数值型
    clf = Adaboost(data)  #Adaboost
    Predict(data,clf) #预测
result1.png
上一篇 下一篇

猜你喜欢

热点阅读