knn鸢尾花分类python代码
时间: 2023-06-08 07:06:31 浏览: 106
以下是KNN鸢尾花分类的Python代码:
```
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建k-NN分类器
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(X_train, y_train)
# 预测测试集数据
y_pred = knn.predict(X_test)
# 显示准确率
print("Accuracy:", knn.score(X_test, y_test))
```
相关问题
knn鸢尾花分类python
KNN(k-Nearest Neighbors)算法是一种简单的机器学习算法,它能够根据已知数据集中每个样本的特征,对未知数据进行分类。鸢尾花数据集是机器学习中常用的数据集之一,包含了150个样本,每个样本有4个特征:萼片长度、萼片宽度、花瓣长度和花瓣宽度,以及它所属的类别(Setosa,Versicolour或Virginica)。
下面是一个用Python实现的KNN鸢尾花分类的示例代码:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# 加载数据集
iris = load_iris()
# 划分训练集和测试集,比例为7:3
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
# 创建KNN分类器,设置k值为3
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(X_train, y_train)
# 预测测试集
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
输出结果为:
```
Accuracy: 0.9777777777777777
```
这表示我们的KNN分类器在测试集上的准确率为97.8%。
knn分类鸢尾花纯python代码
下面是纯 Python 实现的 KNN 分类鸢尾花代码:
```python
import csv
import random
import math
# 读取数据集
def loadDataset(filename, split, trainingSet=[] , testSet=[]):
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset)-1):
for y in range(4):
dataset[x][y] = float(dataset[x][y])
if random.random() < split:
trainingSet.append(dataset[x])
else:
testSet.append(dataset[x])
# 计算距离
def euclideanDistance(instance1, instance2, length):
distance = 0
for x in range(length):
distance += pow((instance1[x] - instance2[x]), 2)
return math.sqrt(distance)
# 获取最近的邻居
def getNeighbors(trainingSet, testInstance, k):
distances = []
length = len(testInstance)-1
for x in range(len(trainingSet)):
dist = euclideanDistance(testInstance, trainingSet[x], length)
distances.append((trainingSet[x], dist))
distances.sort(key=lambda x: x[1])
neighbors = []
for x in range(k):
neighbors.append(distances[x][0])
return neighbors
# 获取最多的投票
def getResponse(neighbors):
classVotes = {}
for x in range(len(neighbors)):
response = neighbors[x][-1]
if response in classVotes:
classVotes[response] += 1
else:
classVotes[response] = 1
sortedVotes = sorted(classVotes.items(), key=lambda x: x[1], reverse=True)
return sortedVotes[0][0]
# 计算准确率
def getAccuracy(testSet, predictions):
correct = 0
for x in range(len(testSet)):
if testSet[x][-1] == predictions[x]:
correct += 1
return (correct/float(len(testSet))) * 100.0
# 测试 KNN 算法
def main():
# prepare data
trainingSet=[]
testSet=[]
split = 0.67
loadDataset('iris.data', split, trainingSet, testSet)
print('Train set: ' + repr(len(trainingSet)))
print('Test set: ' + repr(len(testSet)))
# generate predictions
predictions=[]
k = 3
for x in range(len(testSet)):
neighbors = getNeighbors(trainingSet, testSet[x], k)
result = getResponse(neighbors)
predictions.append(result)
print('> predicted=' + repr(result) + ', actual=' + repr(testSet[x][-1]))
accuracy = getAccuracy(testSet, predictions)
print('Accuracy: ' + repr(accuracy) + '%')
main()
```
这段代码中,我们使用了欧氏距离来计算样本之间的距离,并使用投票法来确定测试样本所属的类别。
阅读全文