使用knn算法进行水果分类给出代码和数据集
时间: 2023-07-05 12:04:41 浏览: 178
以下是使用KNN算法进行水果分类的Python代码,数据集可以自行收集或者使用公开数据集。
```python
import csv
import random
import math
import operator
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=operator.itemgetter(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=operator.itemgetter(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
def main():
trainingSet=[]
testSet=[]
split = 0.67
loadDataset('<your dataset file>', split, trainingSet, testSet)
print('Train set: ' + repr(len(trainingSet)))
print('Test set: ' + repr(len(testSet)))
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()
```
数据集应该包含以下内容:
| 颜色 | 直径 | 重量 | 类型 |
| --- | --- | --- | --- |
| 绿 | 3 | 176 | 苹果 |
| 黄 | 3 | 170 | 苹果 |
| 红 | 1 | 70 | 葡萄 |
| 红 | 1.5 | 92 | 葡萄 |
| 黄 | 3.5 | 180 | 苹果 |
| 绿 | 3.2 | 150 | 苹果 |
| ... | ... | ... | ... |
请将数据保存为CSV格式。在代码中指定数据集文件的路径,例如`loadDataset('fruits.csv', split, trainingSet, testSet)`。
阅读全文