)基于欧式距离,建立一个 k 近邻分类器;利用下列语句建立训练数据集 X_train1、X_labels1 和测试数据集 Y_test1 作为测试数据集 1,验证建立的 k 近邻分类器性能: X_train1=np.array([[1.1,2.1],[1.2,0.1],[0.1,1.4],[0.3,3.5], [1.1,1.0],[0.5,1.5]]) ; X_labels1 = np.array(['A','A','B','B','A','B']) ; Y_test1 = np.array([[1.0,2.1],[0.4,2.0]]) ;
时间: 2023-07-16 17:13:34 浏览: 88
目标检测数据集:基于骨头X光的癌症检测(VOC标注,包含训练集和验证集)
5星 · 资源好评率100%
以下是基于欧式距离的 k 近邻分类器的 Python 代码:
```python
import numpy as np
def euclidean_distance(a, b):
return np.sqrt(np.sum(np.square(a - b)))
def k_nearest_neighbors(X_train, X_labels, Y_test, k):
predictions = []
for sample in Y_test:
distances = []
for i, train_sample in enumerate(X_train):
distance = euclidean_distance(train_sample, sample)
distances.append((distance, X_labels[i]))
distances.sort(key=lambda x: x[0])
neighbors = [x[1] for x in distances[:k]]
predictions.append(max(set(neighbors), key=neighbors.count))
return predictions
X_train1 = np.array([[1.1,2.1],[1.2,0.1],[0.1,1.4],[0.3,3.5],[1.1,1.0],[0.5,1.5]])
X_labels1 = np.array(['A', 'A', 'B', 'B', 'A', 'B'])
Y_test1 = np.array([[1.0,2.1],[0.4,2.0]])
predictions = k_nearest_neighbors(X_train1, X_labels1, Y_test1, k=3)
print(predictions)
```
输出结果为:
```
['A', 'B']
```
说明第一个测试样本 `[1.0, 2.1]` 被分类为 `'A'`,第二个测试样本 `[0.4, 2.0]` 被分类为 `'B'`。
阅读全文