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

This commit is contained in:
zhe
2024-10-17 14:51:45 +08:00
parent 78be1b6eb5
commit a8186e64c8
+21 -38
View File
@@ -44,17 +44,8 @@ name = "李劲"
def classify(input_vector, dataSet, labels, k=3):
"""
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)
# 获取距离最近的 k 个样本的索引
@@ -64,21 +55,14 @@ def classify(input_vector, dataSet, labels, k=3):
k_nearest_labels = [labels[i] for i in k_indices]
# 找出出现次数最多的标签
most_common = max(set(k_nearest_labels), key=k_nearest_labels.count)
from collections import Counter
most_common = Counter(k_nearest_labels).most_common(1)[0][0]
return most_common
# 这里也写自己的代码实现
def load_dataset(directory):
"""
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- directory (str): 数据文件夹路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
从文件夹中加载数据。
"""
features = []
labels = []
@@ -88,33 +72,32 @@ def load_dataset(directory):
if filename.endswith(".txt"): # 假设文件是 .txt 格式
filepath = os.path.join(directory, filename)
# 假设文件名格式为 "数字_编号.txt"
label = int(filename.split('_')[0])
try:
# 假设文件名格式为 "数字_编号.txt"
label = int(filename.split('_')[0])
# 加载文件中的二进制数据并转换为 1D 向量
image_vector = img_to_vector(filepath)
# 加载文件中的二进制数据并转换为 1D 向量
image_vector = img_to_vector(filepath)
features.append(image_vector)
labels.append(label)
features.append(image_vector)
labels.append(label)
except Exception as e:
print(f"Error processing file {filepath}: {e}")
return np.array(features), np.array(labels)
# 这里还写自己的代码实现
def img_to_vector(filename):
"""
将二值图像转换为向量。
该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。
Args:
- filename (str): 图像文件路径。
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()])
try:
with open(filename) as file:
lines = file.readlines()
image_vector = np.array([int(char) for line in lines for char in line.strip()])
except Exception as e:
print(f"Error reading file {filename}: {e}")
image_vector = np.zeros(expected_vector_length) # 假设有一个预期的向量长度
# 或者可以抛出一个异常,根据需求决定
return image_vector