鳶尾花數(shù)據(jù)集介紹
一:讀取數(shù)據(jù)
from sklearn.datasets import load_iris
# 導(dǎo)入數(shù)據(jù)集Iris
iris = load_iris() #導(dǎo)入數(shù)據(jù)
iris_feature= iris.data #特征數(shù)據(jù)
iris_target = iris.target #分類數(shù)據(jù)
# print(iris.data) # 輸出數(shù)據(jù)
print(type(iris))
print(type(iris_feature))
print(type(iris_target)) # numpy 數(shù)據(jù)類型
<class 'sklearn.utils.Bunch'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
# numpy數(shù)據(jù)查看--索引
print(iris_feature[2])
print(iris_feature[2,1])
[4.7 3.2 1.3 0.2]
3.2
二:鳶尾花類別
target介紹
# print(iris.data) # 輸出數(shù)據(jù)
print(iris.target) #輸出真實(shí)標(biāo)簽
print(len(iris.target)) #樣本個(gè)數(shù)
print(iris.data.shape)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2]
150
(150, 4)
三:數(shù)據(jù)可視化
1:繪制直方圖
import pandas as pd
# 將特征的numpy數(shù)據(jù)轉(zhuǎn)換為pandas數(shù)據(jù)
names=['length_sepal','width_speal','petal_length','petal_width ']
d_iris_feature = pd.DataFrame(iris_feature, columns=names)
d_iris_target=pd.DataFrame(iris_target,columns=['label_'])
print(d_iris_feature.head())
print(d_iris_target.head())
# 描述性分析
print(d_iris_feature.describe())
# hist(),輸出各個(gè)特征對(duì)比的直方圖
d_iris_feature.hist()
length_sepal width_speal petal_length petal_width
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
label_
0 0
1 0
2 0
3 0
4 0
length_sepal width_speal petal_length petal_width
count 150.000000 150.000000 150.000000 150.000000
mean 5.843333 3.057333 3.758000 1.199333
std 0.828066 0.435866 1.765298 0.762238
min 4.300000 2.000000 1.000000 0.100000
25% 5.100000 2.800000 1.600000 0.300000
50% 5.800000 3.000000 4.350000 1.300000
75% 6.400000 3.300000 5.100000 1.800000
max 7.900000 4.400000 6.900000 2.500000
array([[<AxesSubplot:title={'center':'length_sepal'}>,
<AxesSubplot:title={'center':'width_speal'}>],
[<AxesSubplot:title={'center':'petal_length'}>,
<AxesSubplot:title={'center':'petal_width '}>]], dtype=object)
2.png)]
四:訓(xùn)練和分類
1:劃分訓(xùn)練集和測試集
構(gòu)建訓(xùn)練集和測試集,分別保存在X_train,y_train,X_test,y_test
from sklearn.model_selection import train_test_split
from sklearn.model_selection import train_test_split
for i in range(1000):
X_train, X_test, y_train, y_test = train_test_split(d_iris_feature,d_iris_target, test_size=0.3)
# 不要設(shè)置隨機(jī)種子random_state保證每次劃分的隨機(jī)性
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
(105, 4)
(45, 4)
(105, 1)
(45, 1)
# 構(gòu)造訓(xùn)練集和測試集
# <pre name="code" class="python"><span style="font-size:14px;">
from sklearn.model_selection import train_test_split
# 交叉驗(yàn)證
X_train,X_test,y_train,y_test=train_test_split(d_iris_feature,d_iris_target,random_state=1)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
# 默認(rèn)為75%為訓(xùn)練,25%為測試
(112, 4)
(38, 4)
(112, 1)
(38, 1)
print(X_train)
length_sepal width_speal petal_length petal_width
54 6.5 2.8 4.6 1.5
108 6.7 2.5 5.8 1.8
112 6.8 3.0 5.5 2.1
17 5.1 3.5 1.4 0.3
119 6.0 2.2 5.0 1.5
.. ... ... ... ...
133 6.3 2.8 5.1 1.5
137 6.4 3.1 5.5 1.8
72 6.3 2.5 4.9 1.5
140 6.7 3.1 5.6 2.4
37 4.9 3.6 1.4 0.1
[112 rows x 4 columns]
print(y_train)
label_
54 1
108 2
112 2
17 0
119 2
.. ...
133 2
137 2
72 1
140 2
37 0
[112 rows x 1 columns]
2:訓(xùn)練和分類
from sklearn.tree import DecisionTreeClassifier
DecisionTreeClassifier()
DecisionTreeClassifier(criterion=‘entropy’, min_samples_leaf=3)函數(shù)為創(chuàng)建一個(gè)決策樹模型,其函數(shù)的參數(shù)含義如下所示
class_weight : 指定樣本各類別的的權(quán)重,主要是為了防止訓(xùn)練集某些類別的樣本過多導(dǎo)致訓(xùn)練的決策樹過于偏向這些類別。這里可以自己指定各個(gè)樣本的權(quán)重,如果使用“balanced”,則算法會(huì)自己計(jì)算權(quán)重,樣本量少的類別所對(duì)應(yīng)的樣本權(quán)重會(huì)高。
criterion : gini或者entropy,前者是基尼系數(shù),后者是信息熵;
max_depth : int or None, optional (default=None) 設(shè)置決策隨機(jī)森林中的決策樹的最大深度,深度越大,越容易過擬合,推薦樹的深度為:5-20之間;
max_features: None(所有),log2,sqrt,N 特征小于50的時(shí)候一般使用所有的;
max_leaf_nodes : 通過限制最大葉子節(jié)點(diǎn)數(shù),可以防止過擬合,默認(rèn)是"None”,即不限制最大的葉子節(jié)點(diǎn)數(shù)。
min_impurity_split: 這個(gè)值限制了決策樹的增長,如果某節(jié)點(diǎn)的不純度(基尼系數(shù),信息增益,均方差,絕對(duì)差)小于這個(gè)閾值則該節(jié)點(diǎn)不再生成子節(jié)點(diǎn)。即為葉子節(jié)點(diǎn) 。
min_samples_leaf : 這個(gè)值限制了葉子節(jié)點(diǎn)最少的樣本數(shù),如果某葉子節(jié)點(diǎn)數(shù)目小于樣本數(shù),則會(huì)和兄弟節(jié)點(diǎn)一起被剪枝。
min_samples_split : 設(shè)置結(jié)點(diǎn)的最小樣本數(shù)量,當(dāng)樣本數(shù)量可能小于此值時(shí),結(jié)點(diǎn)將不會(huì)在劃分。
min_weight_fraction_leaf: 這個(gè)值限制了葉子節(jié)點(diǎn)所有樣本權(quán)重和的最小值,如果小于這個(gè)值,則會(huì)和兄弟節(jié)點(diǎn)一起被剪枝默認(rèn)是0,就是不考慮權(quán)重問題。
presort :
splitter : best or random 前者是在所有特征中找最好的切分點(diǎn) 后者是在部分特征中,默認(rèn)的”best”適合樣本量不大的時(shí)候,而如果樣本數(shù)據(jù)量非常大,此時(shí)決策樹構(gòu)建推薦”random” 。
from sklearn.tree import DecisionTreeClassifier
#clf:決策樹對(duì)象
clf=DecisionTreeClassifier(criterion='entropy', min_samples_leaf=3) #
# 調(diào)用對(duì)象訓(xùn)練數(shù)據(jù)
clf.fit(X_train,y_train)
print(clf)
#預(yù)測
predicted=clf.predict(X_test)
print(predicted)
DecisionTreeClassifier(criterion='entropy', min_samples_leaf=3)
[0 1 1 0 2 1 2 0 0 2 1 0 2 1 1 0 1 1 0 0 1 1 2 0 2 1 0 0 1 2 1 2 1 2 2 0 1
0]
3:算法精度
# from sklearn.metrics import roc_curve
# fpr,tpr,threshold=roc_curve(y_test,predicted)
# 多分類不用RoC曲線評(píng)估
使用ROC曲線評(píng)估分類模型是非常通用的手段,但是,使用它的時(shí)候要注意兩點(diǎn):
1、分類的類型。
必須為數(shù)值型。
2、只針對(duì)二分類問題。
ROC曲線是根據(jù)一系列不同的二分類方式(分界值或決定閾),以真陽性率(靈敏度)為縱坐標(biāo),假陽性率(1-特異度)為橫坐標(biāo)繪制的曲線。傳統(tǒng)的診斷試驗(yàn)評(píng)價(jià)方法有一個(gè)共同的特點(diǎn),必須將試驗(yàn)結(jié)果分為兩類,再進(jìn)行統(tǒng)計(jì)分析。
3.1 accuracy_score
sklearn.metrics.accuracy_score(y_true, y_pred, normalize=True, sample_weight=None)
normalize:默認(rèn)值為True,返回正確分類的比例;如果為False,返回正確分類的樣本數(shù)
3.2 f1_score()
文章來源:http://www.zghlxwxcb.cn/news/detail-735038.html
from sklearn import metrics
# 計(jì)算模型評(píng)估指標(biāo)
acc = metrics.accuracy_score(y_test, predicted)
print('acc: '+str(acc))
f1 = metrics.f1_score(y_test, predicted,average='micro')
print('f1: '+str(f1))
# class_names = np.unique(y_train)
# y_binarize = label_binarize(y_test, classes=class_names)
# y_fit=label_binarize(y_pred, classes = class_names)
# fpr, tpr, _= metrics.roc_curve(y_binarize.ravel(),y_fit.ravel())
# auc = metrics.auc(fpr, tpr)
# print('auc: '+str(auc))
acc: 0.9736842105263158
f1: 0.9736842105263158
4:
predicted.reshape(len(predicted))
array([0, 1, 1, 0, 2, 1, 2, 0, 0, 2, 1, 0, 2, 1, 1, 0, 1, 1, 0, 0, 1, 1,
2, 0, 2, 1, 0, 0, 1, 2, 1, 2, 1, 2, 2, 0, 1, 0])
import numpy as np
type(X_test)
# scatter()的輸入為array
X_test_=np.array(X_test)
# X_test為datafram數(shù)據(jù),需要轉(zhuǎn)換為numpy 的數(shù)組array形式
# 獲取花卉的兩列數(shù)據(jù)集
# 繪圖
import matplotlib.pyplot as plt
plt.scatter(X_test_[:,0],X_test_[:,1], c=predicted.reshape(len(predicted)), marker='x')
plt.show()
# X_test_[:,0],X_test_[:,1]用前兩個(gè)特征畫圖,沒有降維
文章來源地址http://www.zghlxwxcb.cn/news/detail-735038.html
到了這里,關(guān)于使用決策樹對(duì)鳶尾花進(jìn)行分類python的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!