Compare commits

5 Commits
Author SHA1 Message Date
Wyy d61231b836 更新 function.py 2024-10-17 00:08:20 +08:00
Wyy 1355057050 更新 requirements.txt 2024-10-17 00:07:51 +08:00
Wyy bf2ff4ab8a 更新 function.py 2024-10-17 00:06:30 +08:00
Wyy 9f9dbb9bcd 更新 requirements.txt 2024-10-17 00:06:09 +08:00
Wyy 47b5945e38 更新 function.py 2024-10-17 00:05:18 +08:00
2 changed files with 53 additions and 57 deletions
+49 -54
View File
@@ -1,7 +1,7 @@
# function.py
import numpy as np
import os
from scipy.spatial import distance
"""
实验说明:
- 自行编写实现数据加载与 kNN 的手写数字分类算法。
@@ -25,8 +25,8 @@ import os
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423224"
name = "吴杨洋"
"""
@@ -40,8 +40,9 @@ name = "test_name"
"""
# 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=0):
def classify(input_vector, dataSet, labels, k=3):
"""
KNN 分类算法。
@@ -49,17 +50,33 @@ 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: 预测的分类标签。
"""
# 计算输入向量与数据集中每个向量的欧氏距离
distances = [distance.euclidean(input_vector, row) for row in dataSet]
# 获取距离最近的k个样本的索引
k_indices = np.argsort(distances)[:k]
# 获取这些样本对应的标签
k_nearest_labels = [labels[index] for index in k_indices]
# 统计每个类别的出现次数
class_count = {}
for vote in k_nearest_labels:
class_count[vote] = class_count.get(vote, 0) + 1
# 预测的类别是出现次数最多的类别
predicted_class = max(class_count, key=class_count.get)
return predicted_class
# 这里也写自己的代码实现
def load_dataset(directory):
"""
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
从文件夹中加载数据。
Args:
- directory (str): 数据文件夹路径。
@@ -68,13 +85,21 @@ def load_dataset(directory):
- np.array: 特征数据。
- np.array: 标签数据。
"""
training_file_list = os.listdir(directory)
training_matrix = []
training_labels = []
for file in training_file_list:
class_num = int(file.split('_')[0])
vector = img_to_vector(os.path.join(directory, file))
training_matrix.append(vector)
training_labels.append(class_num)
return np.array(training_matrix), np.array(training_labels)
# 这里还写自己的代码实现
def img_to_vector(filename):
"""
将二值图像转换为向量。
该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。
Args:
- filename (str): 图像文件路径。
@@ -82,50 +107,20 @@ def img_to_vector(filename):
Returns:
- np.array: 二值图像向量。
"""
return_vec = np.zeros((1024,))
with open(filename) as fr:
lines = fr.readlines()
for i in range(32):
line_str = str(lines[i])
for j in range(32):
if line_str[j] == '1':
return_vec[32*i + j] = 1
else:
return_vec[32*i + j] = 0
return return_vec
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_data, train_labels = load_dataset("trainingDigits")
test_data = (
"00000000000000110000000000000000"
"00000000000011111000000000000000"
"00000000000011111100000000000000"
"00000000001111111110000000000000"
"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}")
this_digit = img_to_vector('testDigits/0_13.txt')
test_result = classify(this_digit, train_data, train_labels)
print(test_result)
+1
View File
@@ -1,2 +1,3 @@
numpy==2.1.1
requests==2.32.3
scipy==1.13.1