chore: adjust upstream
Gitea Actions Test / Exp-Actions (push) Successful in 17s

This commit is contained in:
2024-09-28 01:23:22 +08:00
parent 894256e3f1
commit 40056a6379
+21 -26
View File
@@ -38,7 +38,7 @@ name = "向兴宇"
# 这里写自己的代码实现
def classify0(inX, dataSet, labels):
def classify0(inX, dataSet, labels, k=9):
"""
KNN 分类算法。
@@ -63,7 +63,7 @@ def classify0(inX, dataSet, labels):
sortedDistIndices = np.argsort(distances)
# 统计前 k 个样本的标签
classCount = np.bincount(labels[sortedDistIndices[:8]])
classCount = np.bincount(labels[sortedDistIndices[:k]])
# 返回出现次数最多的标签
return np.argmax(classCount)
@@ -73,16 +73,10 @@ def load_data(file_path):
"""
加载 TSV 格式数据文件。
"""
features = []
labels = []
with open(file_path, "r") as file:
for line in file:
values = line.strip().split("\t")
features.append([float(x) for x in values[:-1]])
labels.append(int(values[-1]))
return np.array(features), np.array(labels)
data = np.loadtxt(file_path, delimiter="\t")
features = data[:, :-1]
labels = data[:, -1].astype(int)
return features, labels
if __name__ == "__main__":
@@ -95,18 +89,19 @@ if __name__ == "__main__":
train_data, train_labels = load_data(train_file)
test_data, test_labels = load_data(test_file)
correct = 0
total = len(test_data)
for j in range(20):
correct = 0
total = len(test_data)
for i in range(total):
# 获取测试数据中的每个样本
result = classify0(test_data[i], train_data, train_labels)
if result == test_labels[i]:
correct += 1
else:
print(
f"第 {i+1} 次测试错误,数据 {test_data[i]} 被分类到 {result} 实际是 {test_labels[i]}"
)
accuracy = correct / total
print(f"测试集正确个数 {correct},总个数 {total},正确率 {accuracy}")
for i in range(total):
# 获取测试数据中的每个样本
result = classify0(test_data[i], train_data, train_labels, k=j + 1)
if result == test_labels[i]:
correct += 1
# else:
# print(
# f"第 {i+1} 次测试错误,数据 {test_data[i]} 被分类到 {result} 实际是 {test_labels[i]}"
# )
if correct >= 96:
print(f"KNN 分类算法,k={j+1}")
print(f"{correct}% 正确率")