上传文件至 /
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 23s

This commit is contained in:
2024-10-16 21:43:17 +08:00
parent dd477eb7f1
commit 110dca8f54
+30 -96
View File
@@ -1,129 +1,63 @@
# function.py
import numpy as np
import os
from collections import Counter
from collections import defaultdict
import operator
id = "202210423104"
name = "张钦诚"
"""
参数说明:
- input_vector (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
返回值:
- int: 预测的分类标签。
"""
def classify(input_vector, dataSet, labels, k=5):
"""
KNN 分类算法。
Args:
- input_vector (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
Returns:
- int: 预测的分类标签。
"""
# 计算欧式距离
# 使用广播和向量化计算距离,避免循环
distances = np.linalg.norm(dataSet - input_vector, axis=1)
sortedDistIndices = distances.argsort()
k_labels = [labels[i] for i in sortedDistIndices[:k]]
count = Counter(k_labels)
return count.most_common(1)[0][0]
# 获取k个最近邻的索引
sortedDistIndices = distances.argsort()[:k]
# 获取k个最近邻的标签
k_labels = [labels[i] for i in sortedDistIndices]
# 获取k个最近邻的距离
k_distances = distances[sortedDistIndices]
# 加权多数表决:权重为1/(距离 + 1e-5) 避免除以零
weight_dict = defaultdict(float)
for label, dist in zip(k_labels, k_distances):
weight = 1 / (dist + 1e-5)
weight_dict[label] += weight
# 排序权重并选择权重最大的类别
sorted_weight = sorted(weight_dict.items(), key=operator.itemgetter(1), reverse=True)
return sorted_weight[0][0]
def load_dataset(directory):
"""
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- directory (str): 数据文件夹路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
labels = []
files = os.listdir(directory)
m = len(files)
dataset = np.zeros((m, 1024))
dataset = np.zeros((m, 1024), dtype=np.int8)
for i, file in enumerate(files):
filename = os.path.join(directory, file)
dataset[i, :] = img_to_vector(filename)
label = int(file.split('_')[0])
labels.append(label)
return dataset, labels
def img_to_vector(filename):
"""
将二值图像转换为向量。
该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。
Args:
- filename (str): 图像文件路径。
Returns:
- np.array: 二值图像向量。
"""
returnVect = np.zeros((1, 1024))
with open(filename) as fr:
returnVect = np.zeros((1024,), dtype=np.int8)
with open(filename, 'r') as fr:
for i in range(32):
lineStr = fr.readline()
lineStr = fr.readline().strip()
for j in range(32):
returnVect[0, 32*i + j] = int(lineStr[j])
returnVect[32 * i + j] = int(lineStr[j])
return returnVect
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}")