generated from LufsX/Challenge-kNN
This commit is contained in:
+38
-14
@@ -40,6 +40,7 @@ name = "孔祥芷"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
|
||||
def classify0(inX, dataSet, labels, k=3):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
@@ -48,50 +49,73 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): KNN 算法参数,请自行设置默认值,评测时仅会使用其默认值。
|
||||
- k (int): KNN 算法参数。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 计算待分类样本与训练集中每个样本之间的距离
|
||||
dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1))
|
||||
# 根据距离对训练样本进行排序
|
||||
sorted_index = np.argsort(dists)
|
||||
# 选择距离最近的k个样本
|
||||
class_count = {}
|
||||
for i in range(k):
|
||||
vote_label = labels[sorted_index[i]]
|
||||
if vote_label not in class_count.keys():
|
||||
class_count[vote_label] = 1
|
||||
else:
|
||||
class_count[vote_label] += 1
|
||||
class_count[vote_label] = class_count.get(vote_label, 0) + 1
|
||||
# 投票得到最多的标签作为预测结果
|
||||
sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True)
|
||||
return sorted_class_count[0][0]
|
||||
|
||||
|
||||
if sorted_class_count:
|
||||
return sorted_class_count[0][0]
|
||||
else:
|
||||
return -1
|
||||
|
||||
def load_data(file_path):
|
||||
|
||||
#加载 TSV 格式数据文件。
|
||||
|
||||
"""
|
||||
加载 TSV 格式数据文件。
|
||||
|
||||
Args:
|
||||
- file_path (str): 文件路径。
|
||||
|
||||
Returns:
|
||||
- features (numpy array): 特征数据。
|
||||
- labels (numpy array): 标签数据。
|
||||
"""
|
||||
data = np.loadtxt(file_path, delimiter="\t")
|
||||
features = data[:, :-1]
|
||||
labels = data[:, -1].astype(int)
|
||||
return features, labels
|
||||
|
||||
|
||||
|
||||
def standardize(features):
|
||||
mean = np.mean(features, axis=0)
|
||||
std = np.std(features, axis=0)
|
||||
standardized = (features - mean) / std
|
||||
return standardized
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
train_file_path = "datingTrainSet2.tsv"
|
||||
train_features, train_labels = load_data(train_file_path)
|
||||
|
||||
test_file_path = "datingTestSet2.tsv"
|
||||
test_features, test_labels = load_data(test_file_path)
|
||||
|
||||
# 特征标准化
|
||||
train_features = standardize(train_features)
|
||||
test_features = standardize(test_features)
|
||||
|
||||
correct_count = 0
|
||||
for i in range(len(test_features)):
|
||||
test_feature = test_features[i].reshape(1, -1)
|
||||
predict_label = classify0(test_feature, train_features, train_labels, k=3)
|
||||
if predict_label == -1:
|
||||
continue
|
||||
correct_count += (predict_label == test_labels[i])
|
||||
|
||||
accuracy = correct_count / len(test_features)
|
||||
print(f"Accuracy: {accuracy:.2f}")
|
||||
|
||||
|
||||
|
||||
|
||||
accuracy = correct_count / len(test_features)
|
||||
print(f"Accuracy: {accuracy:.2f}")
|
||||
Reference in New Issue
Block a user