更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 20s

This commit is contained in:
2024-10-16 22:13:44 +08:00
parent 3c9309ae9d
commit 667941dcfa
+45 -45
View File
@@ -25,8 +25,8 @@ import os
""" """
请在这里填写学号和姓名,不填写即成绩无效。 请在这里填写学号和姓名,不填写即成绩无效。
""" """
id = "202210423xxx" id = "202210423102"
name = "test_name" name = "周佳成"
""" """
@@ -41,7 +41,7 @@ name = "test_name"
# 这里写自己的代码实现 # 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=0): def classify(input_vector, dataSet, labels, k=3):
""" """
KNN 分类算法。 KNN 分类算法。
@@ -54,6 +54,14 @@ def classify(input_vector, dataSet, labels, k=0):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
if k > len(labels):
raise ValueError("k 不能大于训练集样本数")
distances = np.linalg.norm(dataSet - input_vector, axis=1)
sorted_indices = distances.argsort()
nearest_labels = np.array(labels)[sorted_indices[:k]]
predicted_label = np.bincount(nearest_labels).argmax()
return predicted_label
# 这里也写自己的代码实现 # 这里也写自己的代码实现
@@ -68,6 +76,17 @@ def load_dataset(directory):
- np.array: 特征数据。 - np.array: 特征数据。
- np.array: 标签数据。 - np.array: 标签数据。
""" """
data = []
labels = []
for filename in os.listdir(directory):
if filename.endswith(".txt"):
# 提取文件名中的标签信息
label = int(filename.split('_')[0])
labels.append(label)
# 将图像文件转换为向量
vector = img_to_vector(os.path.join(directory, filename))
data.append(vector)
return np.array(data), np.array(labels)
# 这里还写自己的代码实现 # 这里还写自己的代码实现
@@ -82,50 +101,31 @@ def img_to_vector(filename):
Returns: Returns:
- np.array: 二值图像向量。 - np.array: 二值图像向量。
""" """
with open(filename, 'r') as f:
lines = f.readlines()
# 将32x32的字符矩阵转换为长度为1024的一维数组
vector = np.array([int(char) for line in lines for char in line.strip()])
return vector
if __name__ == "__main__": if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改 # 加载训练集和测试集
train_data, train_labels = load_dataset("trainingDigits") train_data, train_labels = load_dataset("D:/二值手写数字数据集/trainingDigits")
test_data, test_labels = load_dataset("D:/二值手写数字数据集/testDigits")
test_data = ( # 记录预测的正确数量
"00000000000000110000000000000000" correct_count = 0
"00000000000011111000000000000000"
"00000000000011111100000000000000" # 遍历测试集,逐个样本进行分类
"00000000001111111110000000000000" for i in range(len(test_data)):
"00000000001111111110000000000000" predicted_label = classify(test_data[i], train_data, train_labels)
"00000000001111111100000000000000" print(f"测试样本 {i+1} 的真实标签: {test_labels[i]},预测标签: {predicted_label}")
"00000000011111111000000000000000"
"00000000111111111000000000000000" if predicted_label == test_labels[i]:
"00000000111111110000000000000000" correct_count += 1
"00000000111111110000000000000000"
"00000000111111110000000000000000" # 打印准确率
"00000000111111110000000000000000" accuracy = correct_count / len(test_data) * 100
"00000000111111100000000000000000" print(f"测试集的准确率: {accuracy:.2f}%")
"00000001111111100000000000000000"
"00000001111111100000000000000000"
"00000001111111100000000000000000"
"00000001111111111111000000000000"
"00000001111111111111111000000000"
"00000001111111111111111100000000"
"00000011111111111111111110000000"
"00000011111111111111111110000000"
"00000001111111111111111110000000"
"00000001111111111111111110000000"
"00000000111111111100111111100000"
"00000000111111111000111111100000"
"00000000011111111001111111100000"
"00000000011111111111111111000000"
"00000000001111111111111111000000"
"00000000000111111111111111000000"
"00000000000011111111111100000000"
"00000000000001111111110000000000"
"00000000000000000111100000000000"
)
predicted_label = classify(
np.array([int(char) for char in test_data]).reshape(1, 1024),
train_data,
train_labels,
) )
print(f"预测的标签: {predicted_label}")