# 机器学习-鸢尾花(Iris Flower)分类

1. 导入数据
2. 概述数据
3. 数据可视化
4. 评估算法
5. 实施预测

### 1、导入数据

``````"""导入类库和方法"""
from pandas.plotting import scatter_matrix
from matplotlib import pyplot
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
``````

separ-length separ-width petal-length petal-width class

``````"""导入数据"""
filename = 'iris.data.csv'
names = ['separ-length', 'separ-width', 'petal-length', 'petal-width', 'class']
``````

### 2、概述数据

``````"""提要输出"""
# 显示数据的维度：
print("行：%s ， 列：%s" % dataset.shape)
# 查看数据前10行：
# 数据的统计信息：
print(dataset.describe())
#数据的分布情况：
print(dataset.groupby("class").size())
``````

### 3、数据可视化

``````"""单变量图表"""
#箱线图
dataset.plot(kind="box", subplots=True, layout=(2, 2), sharex=False, sharey=False)
#直方图
dataset.hist()
"""显示图片"""
pyplot.show()
``````

``````"""多变量图表"""
#散点矩阵图
scatter_matrix(dataset)
"""显示图片"""
pyplot.show()
``````

### 4、评估算法

##### 分离出评估的数据集。

``````"""分离数据 分离评估数据集"""
array = dataset.values
X = array[:, 0:4]
Y = array[:, 4]
validation_size = 0.2
seed = 7
X_train, X_validation, Y_train, Y_validation =
train_test_split(X, Y, train_size=validation_size, random_state=seed)
``````

##### 创建模型

• 线性回归（Linear Regression，LR）
• 线性判别分析 (linear Discriminant Analysis，LDA)
• K最近邻 (k-Nearest Neighbor，KNN)
• 分类与回归树 （Classification And Regression Tree）
• 朴素贝叶斯(Naïve Bayes，NB)
• 支持向量机（Support Vector Machine, SVM）

``````"""算法审查"""
models = {}
models["LR"] = LogisticRegression(max_iter=1000)
models["LDA"] = LinearDiscriminantAnalysis()
models["KNN"] = KNeighborsClassifier()
models["CART"] = DecisionTreeClassifier()
models["NB"] = GaussianNB()
models["SVM"] = SVC()
"""评估算法"""
results = []
for key in models:
kfold = KFold(n_splits=10, random_state=seed, shuffle=True)
cv_results = cross_val_score(models[key], X_train, Y_train, cv=kfold, scoring="accuracy")
results.append(cv_results)
print("%s:%f(%f)" %(key, cv_results.mean(), cv_results.std()))
``````
##### 选择最优模型

LR:0.866667(0.163299)
LDA:0.933333(0.133333)
KNN:0.900000(0.213437)
CART:0.933333(0.133333)
NB:0.900000(0.152753)
SVM:0.900000(0.152753)

``````"""箱线图比较算法"""
fig = pyplot.figure()
fig.suptitle("Algorithm Comparison")
pyplot.boxplot(results)
ax.set_xticklabels(models.keys())
pyplot.show()
``````

### 5、实施预测

``````"""使用评估数据集评估算法模型"""
svm = LinearDiscriminantAnalysis()
svm.fit(X=X_train,y=Y_train)
predictions = svm.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation,predictions))
print(classification_report(Y_validation,predictions))
``````

THE END