generated from LufsX/Challenge-kNN
This commit is contained in:
+26
-47
@@ -54,60 +54,39 @@ def classify0(inX, dataSet, labels, k=0):
|
|||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
# function.py
|
def classify0(inX, dataSet, labels, k=3):
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
|
||||||
from collections import Counter
|
|
||||||
|
|
||||||
# 确保填写自己的学号和姓名
|
|
||||||
# 学号: YOUR_STUDENT_ID
|
|
||||||
# 姓名: YOUR_NAME
|
|
||||||
|
|
||||||
def classify(inx, dataset, labels, k=3):
|
|
||||||
"""
|
"""
|
||||||
使用kNN算法对输入样本进行分类。
|
KNN 分类算法。
|
||||||
|
|
||||||
:param inx: 要分类的输入样本(1D数组)
|
Args:
|
||||||
:param dataset: 训练数据集(2D数组)
|
- inX (numpy array): 输入待分类的样本。
|
||||||
:param labels: 训练集对应的标签(1D数组)
|
- dataSet (numpy array): 训练数据集。
|
||||||
:param k: 最近邻居的数量
|
- labels (list or numpy array): 训练集对应的标签。
|
||||||
:return: 输入样本的预测标签
|
- k (int): KNN 算法参数,请自行设置默认值,评测时仅会使用其默认值。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
|
dataSetSize = dataSet.shape[0]
|
||||||
|
|
||||||
# 将输入转换为numpy数组以便于操作
|
# 计算协方差矩阵及其逆矩阵
|
||||||
dataset = np.array(dataset)
|
cov_matrix = np.cov(dataSet, rowvar=False)
|
||||||
labels = np.array(labels)
|
inv_cov_matrix = np.linalg.inv(cov_matrix)
|
||||||
inx = np.array(inx)
|
|
||||||
|
|
||||||
# 计算输入样本与所有样本的距离
|
# 计算马氏距离
|
||||||
distances = np.linalg.norm(dataset - inx, axis=1)
|
diffMat = inX - dataSet
|
||||||
|
left_term = np.dot(diffMat, inv_cov_matrix)
|
||||||
|
mahalanobis_distances = np.sqrt(np.sum(left_term * diffMat, axis=1))
|
||||||
|
|
||||||
# 获取最近k个邻居的索引
|
# 排序距离并选择前 k 个最近邻
|
||||||
k_indices = np.argsort(distances)[:k]
|
sortedDistIndicies = mahalanobis_distances.argsort()
|
||||||
|
classCount = {}
|
||||||
|
for i in range(k):
|
||||||
|
vote_label = labels[sortedDistIndicies[i]]
|
||||||
|
classCount[vote_label] = classCount.get(vote_label, 0) + 1
|
||||||
|
|
||||||
# 获取这k个邻居的标签
|
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
|
||||||
k_nearest_labels = labels[k_indices]
|
return sortedClassCount[0][0]
|
||||||
|
|
||||||
# 使用多数投票确定预测标签
|
|
||||||
most_common = Counter(k_nearest_labels).most_common(1)
|
|
||||||
return most_common[0][0]
|
|
||||||
|
|
||||||
# 测试代码示例(可选择性运行)
|
|
||||||
if __name__ == "__main__":
|
|
||||||
# 加载训练数据集
|
|
||||||
train_data = pd.read_csv('datingTrainset2.tsv', sep='\t')
|
|
||||||
train_labels = train_data['label'].values # 替换'label'为你的实际标签列名
|
|
||||||
train_features = train_data.drop('label', axis=1).values # 删除标签列
|
|
||||||
|
|
||||||
# 加载测试数据集
|
|
||||||
test_data = pd.read_csv('datingTestset2.tsv', sep='\t')
|
|
||||||
test_labels = test_data['label'].values # 替换'label'为你的实际标签列名
|
|
||||||
test_features = test_data.drop('label', axis=1).values # 删除标签列
|
|
||||||
|
|
||||||
# 示例:对一个样本进行分类
|
|
||||||
sample = test_features[0] # 使用测试集中第一个样本
|
|
||||||
predicted_label = classify(sample, train_features, train_labels, k=3)
|
|
||||||
print(f"Predicted label: {predicted_label}")
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user