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

This commit is contained in:
2024-10-17 00:15:52 +08:00
parent 55ea0bfc71
commit 4d88695064
+60 -77
View File
@@ -25,8 +25,8 @@ import os
""" """
请在这里填写学号和姓名,不填写即成绩无效。 请在这里填写学号和姓名,不填写即成绩无效。
""" """
id = "202210423xxx" id = "202210423210"
name = "test_name" name = "陈宇杰"
""" """
@@ -40,92 +40,75 @@ name = "test_name"
""" """
# 这里写自己的代码实现 import numpy as np
def classify(input_vector, dataSet, labels, k=0): import os
""" from collections import Counter
KNN 分类算法。
Args: # 加载数据的函数
- input_vector (numpy array): 输入待分类的样本。 def load_data(directory):
- dataSet (numpy array): 训练数据集。 file_list = os.listdir(directory)
- labels (list or numpy array): 训练集对应的标签。 data_matrix = []
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 labels = []
Returns: for file_name in file_list:
- int: 预测的分类标签。 file_path = os.path.join(directory, file_name)
""" # 读取txt文件并将其转化为向量
vector = img_to_vector(file_path)
data_matrix.append(vector)
# 假设文件名格式为:{数字}_某些字符.txt,提取数字作为标签
label = int(file_name.split('_')[0])
labels.append(label)
return np.array(data_matrix), np.array(labels)
# 这里也写自己的代码实现 # 将32x32的二值图像转换为1x1024的向量
def load_dataset(directory): def img_to_vector(file_path):
""" vector = np.zeros((1, 1024))
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 with open(file_path, 'r') as f:
lines = f.readlines()
for i in range(32):
for j in range(32):
vector[0, 32 * i + j] = int(lines[i][j])
return vector
Args: # kNN 分类函数
- directory (str): 数据文件夹路径。 def classify(input_vector, dataSet, labels, k=3):
# 计算欧氏距离
distances = np.linalg.norm(dataSet - input_vector, axis=1)
# 获取距离最近的k个样本的标签
nearest_neighbors = np.argsort(distances)[:k]
nearest_labels = labels[nearest_neighbors]
Returns: # 确保 nearest_labels 是一维的,转换为 Python 列表
- np.array: 特征数据。 nearest_labels = nearest_labels.flatten().tolist()
- np.array: 标签数据。
"""
# 投票,返回出现次数最多的标签
most_common = Counter(nearest_labels).most_common(1)
return most_common[0][0]
# 这里还写自己的代码实现 # 实验主程序
def img_to_vector(filename): def main():
""" # 加载训练集和测试集
将二值图像转换为向量。 training_data, training_labels = load_data('trainingdigits')
该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。 test_data, test_labels = load_data('testdigits')
Args: # 测试 kNN 算法
- filename (str): 图像文件路径。 total_tests = len(test_data)
correct_predictions = 0
Returns: for i in range(total_tests):
- np.array: 二值图像向量。 test_sample = test_data[i]
""" prediction = classify(test_sample, training_data, training_labels, k=3)
actual_label = test_labels[i]
print(f"测试样本 {i+1}: 预测值 = {prediction}, 实际值 = {actual_label}")
if __name__ == "__main__": if prediction == actual_label:
# 以下代码可用于测试,可自行随意修改 correct_predictions += 1
train_data, train_labels = load_dataset("trainingDigits")
test_data = ( accuracy = correct_predictions / total_tests * 100
"00000000000000110000000000000000" print(f"\n分类精度: {accuracy:.2f}%")
"00000000000011111000000000000000"
"00000000000011111100000000000000" if __name__ == '__main__':
"00000000001111111110000000000000" main()
"00000000001111111110000000000000"
"00000000001111111100000000000000"
"00000000011111111000000000000000"
"00000000111111111000000000000000"
"00000000111111110000000000000000"
"00000000111111110000000000000000"
"00000000111111110000000000000000"
"00000000111111110000000000000000"
"00000000111111100000000000000000"
"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}")