Knn算法解决海伦约会问题代码python及其环境要求
时间: 2023-10-03 16:11:02 浏览: 31
python KNN算法的海伦约会数据
5星 · 资源好评率100%
以下是使用Python实现的KNN算法解决海伦约会问题的示例代码:
```python
import numpy as np
import operator
def create_dataset():
# 海伦约会数据集
group = np.array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
labels = ['A', 'A', 'B', 'B']
return group, labels
def classify0(inX, dataset, labels, k):
# KNN分类算法
dataset_size = dataset.shape[0]
diff_mat = np.tile(inX, (dataset_size, 1)) - dataset
sq_diff_mat = diff_mat ** 2
sq_distances = sq_diff_mat.sum(axis=1)
distances = sq_distances ** 0.5
sorted_dist_indices = distances.argsort()
class_count = {}
for i in range(k):
vote_label = labels[sorted_dist_indices[i]]
class_count[vote_label] = class_count.get(vote_label, 0) + 1
sorted_class_count = sorted(class_count.items(),
key=operator.itemgetter(1), reverse=True)
return sorted_class_count[0][0]
if __name__ == '__main__':
group, labels = create_dataset()
result = classify0([0, 0], group, labels, 3)
print(result)
```
该代码可以在Python 2.x或Python 3.x环境中运行,只需要安装NumPy库即可。可以使用以下命令安装NumPy库:
```
pip install numpy
```
阅读全文