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

This commit is contained in:
2024-10-17 10:51:28 +08:00
parent 011504d1d5
commit 7cfdfb682c
+43 -4
View File
@@ -25,8 +25,8 @@ import os
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423119"
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 分类算法。
@@ -54,9 +54,26 @@ def classify(input_vector, dataSet, labels, k=0):
Returns:
- int: 预测的分类标签。
"""
"""
使用欧式距离的 kNN 分类算法。
"""
# 计算欧式距离
distances = np.linalg.norm(dataSet - input_vector, axis=1)
# 获取距离最近的 k 个样本的索引
k_indices = np.argsort(distances)[:k]
# 获取最近邻样本的标签
k_nearest_labels = [labels[i] for i in k_indices]
# 找出出现次数最多的标签
most_common = max(set(k_nearest_labels), key=k_nearest_labels.count)
return most_common
# 这里也写自己的代码实现
def load_dataset(directory):
"""
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
@@ -68,6 +85,24 @@ def load_dataset(directory):
- np.array: 特征数据。
- np.array: 标签数据。
"""
features = []
labels = []
# 遍历文件夹中的所有文件
for filename in os.listdir(directory):
if filename.endswith(".txt"): # 假设文件是 .txt 格式
filepath = os.path.join(directory, filename)
# 假设文件名格式为 "数字_编号.txt"
label = int(filename.split('_')[0])
# 加载文件中的二进制数据并转换为 1D 向量
image_vector = img_to_vector(filepath)
features.append(image_vector)
labels.append(label)
return np.array(features), np.array(labels)
# 这里还写自己的代码实现
@@ -82,7 +117,11 @@ def img_to_vector(filename):
Returns:
- np.array: 二值图像向量。
"""
with open(filename) as file:
lines = file.readlines()
image_vector = np.array([int(char) for line in lines for char in line.strip()])
return image_vector
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改