generated from LufsX/Experiment-kNN
This commit is contained in:
+21
-22
@@ -54,17 +54,13 @@ def classify(input_vector, dataSet, labels, k=3):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
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)
|
||||
sorted_indices = distances.argsort()
|
||||
nearest_labels = np.array(labels)[sorted_indices[:k]]
|
||||
predicted_label = np.bincount(nearest_labels).argmax()
|
||||
if k > len(labels):
|
||||
raise ValueError("k 不能大于训练集样本数")
|
||||
|
||||
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()
|
||||
return predicted_label
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
@@ -79,14 +75,16 @@ def load_dataset(directory):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data = []
|
||||
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)
|
||||
data = []
|
||||
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)
|
||||
|
||||
# 这里还写自己的代码实现
|
||||
@@ -101,9 +99,10 @@ def img_to_vector(filename):
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
"""
|
||||
with open(filename, 'r') as f:
|
||||
lines = f.readlines()
|
||||
vector = np.array([int(char) for line in lines for char in line.strip()])
|
||||
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
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user