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

This commit is contained in:
2024-10-16 00:28:45 +08:00
parent f46edbc84f
commit d22de46091
+4 -5
View File
@@ -56,12 +56,8 @@ def classify(input_vector, dataSet, labels, k=3):
"""
if k > len(labels):
raise ValueError("k 不能大于训练集样本数")
min_vals = dataSet.min(axis=0)
max_vals = dataSet.max(axis=0)
norm_dataSet = (dataSet - min_vals) / (max_vals - min_vals)
norm_input_vector = (input_vector - min_vals) / (max_vals - min_vals)
distances = np.linalg.norm(norm_dataSet - norm_input_vector, axis=1)
distances = np.linalg.norm(dataSet - input_vector, axis=1)
sorted_indices = distances.argsort()
nearest_labels = np.array(labels)[sorted_indices[:k]]
predicted_label = np.bincount(nearest_labels).argmax()
@@ -83,8 +79,10 @@ def load_dataset(directory):
labels = []
for filename in os.listdir(directory):
if filename.endswith(".txt"):
# 提取文件名中的标签信息
label = int(filename.split('_')[0])
labels.append(label)
# 将图像文件转换为向量
vector = img_to_vector(os.path.join(directory, filename))
data.append(vector)
return np.array(data), np.array(labels)
@@ -103,6 +101,7 @@ def img_to_vector(filename):
"""
with open(filename, 'r') as f:
lines = f.readlines()
# 将32x32的字符矩阵转换为长度为1024的一维数组
vector = np.array([int(char) for line in lines for char in line.strip()])
return vector