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

This commit is contained in:
77
2024-10-16 19:29:44 +08:00
parent 4dc272a10a
commit 20583fa983
+17 -20
View File
@@ -1,4 +1,3 @@
# function.py
import numpy as np
import os
@@ -41,7 +40,7 @@ name = "陈瑞琪祥"
# 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=0):
def classify(input_vector, dataSet, labels, k=3):
"""
KNN 分类算法。
@@ -49,7 +48,7 @@ def classify(input_vector, dataSet, labels, k=0):
- input_vector (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
- k (int): kNN 算法参数,默认值为3。
Returns:
- int: 预测的分类标签。
@@ -70,8 +69,6 @@ def classify(input_vector, dataSet, labels, k=0):
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
return sortedClassCount[0][0]
# 这里也写自己的代码实现
def load_dataset(directory):
"""
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
@@ -98,8 +95,6 @@ def load_dataset(directory):
i = i + 1
return dataSet, np.array(labels)
# 这里还写自己的代码实现
def img_to_vector(filename):
"""
将二值图像转换为向量。
@@ -122,11 +117,12 @@ def img_to_vector(filename):
w += 1
return returnVect.flatten() # 返回一维数组
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_data, train_labels = load_dataset("trainingDigits")
# 使用绝对路径加载数据集
directory = r"C:\Users\HP\Desktop\trainingDigits"
train_data, train_labels = load_dataset(directory)
# 确保 test_data 字符串长度为1024
test_data = (
"00000000000000110000000000000000"
"00000000000011111000000000000000"
@@ -147,24 +143,25 @@ if __name__ == "__main__":
"00000001111111111111000000000000"
"00000001111111111111111000000000"
"00000001111111111111111100000000"
"00000011111111111111111110000000"
"00000011111111111111111110000000"
"00000011111111111111111100000000"
"00000011111111111111111100000000"
"00000001111111111111111110000000"
"00000001111111111111111110000000"
"00000000111111111100111111100000"
"00000000111111111000111111100000"
"00000000011111111001111111100000"
"00000000011111111100111111110000"
"00000000011111111111111111000000"
"00000000001111111111111111000000"
"00000000000111111111111111000000"
"00000000000011111111111100000000"
"00000000000001111111110000000000"
"00000000000000111111111000000000"
"00000000000000000111100000000000"
)
predicted_label = classify(
np.array([int(char) for char in test_data]).reshape(1, 1024),
train_data,
train_labels,
)
).replace("\n", "") # 移除换行符
# 将 test_data 转换为 NumPy 数组,并确保其长度为1024
test_vector = np.array([int(char) for char in test_data])[:1024].reshape(1, 1024)
# 确保数组大小为1024后再进行分类
predicted_label = classify(test_vector, train_data, train_labels)
print(f"预测的标签: {predicted_label}")