class KNearestNeighbor(object): def __init__(self): pass def train(self, X, y): self.X_train = X self.y_train = y def predict(self, X, k=1): num_test = X.shape[0] num_train = self.X_train.shape[0] dists = np.zeros((num_test, num_train)) d1 = -2 * np.dot(X, self.X_train.T) d2 = np.sum(np.square(X), axis=1, keepdims=True) d3 = np.sum(np.square(self.X_train), axis=1) dist = np.sqrt(d1 + d2 + d3) y_pred = np.zeros(num_test) for i in range(num_test): dist_k_min = np.argsort(dist[i])[:k] y_kclose = self.y_train[dist_k_min] y_pred[i] = np.argmax(np.bincount(y_kclose.tolist())) return y_pred注释每一行代码
时间: 2023-11-28 18:04:24 浏览: 104
KNN(K Near Neighbor)最近邻算法
5星 · 资源好评率100%
这是一个K最近邻分类器的Python实现,以下是每一行代码的注释:
```
class KNearestNeighbor(object):
def __init__(self):
pass
# 训练函数,输入训练数据X和对应的标签y
def train(self, X, y):
self.X_train = X
self.y_train = y
# 预测函数,输入测试数据X和参数k表示选择的最近邻数,默认为1
def predict(self, X, k=1):
num_test = X.shape[0] # 测试数据集的大小
num_train = self.X_train.shape[0] # 训练数据集的大小
dists = np.zeros((num_test, num_train)) # 创建一个距离矩阵,大小为(num_test, num_train)
# 计算测试数据集和训练数据集之间的距离
d1 = -2 * np.dot(X, self.X_train.T) # 先计算两个矩阵的乘积,再将结果乘以-2
d2 = np.sum(np.square(X), axis=1, keepdims=True) # 计算测试数据集中每个数据的平方和
d3 = np.sum(np.square(self.X_train), axis=1) # 计算训练数据集中每个数据的平方和
dist = np.sqrt(d1 + d2 + d3) # 计算欧几里得距离
y_pred = np.zeros(num_test) # 创建一个长度为num_test的数组,用于存储预测结果
# 针对每个测试数据,选出距离最近的k个训练数据,并进行分类
for i in range(num_test):
dist_k_min = np.argsort(dist[i])[:k] # 选出距离最近的k个训练数据
y_kclose = self.y_train[dist_k_min] # 获取这k个训练数据的标签
y_pred[i] = np.argmax(np.bincount(y_kclose.tolist())) # 对这k个训练数据的标签进行投票,选出最多的标签作为预测结果
return y_pred
```
阅读全文