[机器学习]鸢尾花分类
简介
通过datasets导入鸢尾花数据集,用KNN算法分类
代码实现
一、sklearn实现KNN
from sklearn import neighbors
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import random
iris = datasets.load_iris()
用sklearn打乱数据集,切分训练集和测试集,导入模型并训练,打印模型评价
#用sklearn打乱数据切分数据集
x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size = 0.2)
#构建模型
model = neighbors.KNeighborsClassifier(n_neighbors = 5) # n_eighbors即周围取K个值,值默认为5
model.fit(x_train,y_train)
predictions = model.predict(x_test)
print(classification_report(y_test,predictions))
二、KNN简单例子
同样地,先导入iris数据集。
import numpy as np
from sklearn import neighbors
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import random
iris = datasets.load_iris()
打乱数据集
data_size = iris.data.shape[0]
index = [i for i in range(data_size)]
random.shuffle(index)
iris.data = iris.data[index]
iris.target = iris.target[index]
切分数据集
test_size = 40 #data_size = 150
x_train = iris.data[test_size:]
x_test = iris.data[:test_size]
y_train = iris.target[test_size:]
y_test = iris.target[:test_size]
构建模型
model = neighbors.KNeighborsClassifier(n_neighbors = 3,weights = 'uniform') #weighets = 'uniform'表示所有点权重一样
model.fit(x_train,y_train)
predictions = model.predict(x_test)
print(classification_report(y_test,predications)