generated from LufsX/Experiment-kNN
This commit is contained in:
+6
-18
@@ -45,9 +45,8 @@ import numpy as np
|
||||
import os
|
||||
from collections import Counter
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify(input_vector, dataSet, labels, k=2):
|
||||
def classify(input_vector, dataSet, labels, k=3):
|
||||
"""
|
||||
使用 KNN 算法对输入样本进行分类。
|
||||
|
||||
@@ -55,12 +54,12 @@ def classify(input_vector, dataSet, labels, k=2):
|
||||
- input_vector (numpy array): 输入待分类的样本(1xN)。
|
||||
- dataSet (numpy array): 训练数据集(MxN)。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法参数,默认值为 2。
|
||||
- k (int): kNN 算法参数,默认值为 3。
|
||||
|
||||
返回:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 将欧氏距离改为马氏距离
|
||||
# 计算马氏距离
|
||||
mean_vector = np.mean(dataSet, axis=0)
|
||||
cov_matrix = np.cov(dataSet.T)
|
||||
inv_cov_matrix = np.linalg.inv(cov_matrix)
|
||||
@@ -82,18 +81,8 @@ def classify(input_vector, dataSet, labels, k=2):
|
||||
|
||||
return np.argmax(weighted_votes)
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
# 这里写自己的代码实现
|
||||
def load_dataset(directory):
|
||||
"""
|
||||
加载数据集中的图像,并将其转换为特征向量和标签。
|
||||
|
||||
参数:
|
||||
- directory (str): 数据文件夹路径。
|
||||
|
||||
返回:
|
||||
- np.array: 特征数据(Mx1024)。
|
||||
- np.array: 标签数据(Mx1)。
|
||||
"""
|
||||
feature_list = []
|
||||
label_list = []
|
||||
for file in os.listdir(directory):
|
||||
@@ -110,6 +99,8 @@ def load_dataset(directory):
|
||||
feature_matrix = (feature_matrix - min_value) / (max_value - min_value)
|
||||
|
||||
return feature_matrix, label_array
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def img_to_vector(filename):
|
||||
"""
|
||||
将二值图像转换为向量。
|
||||
@@ -126,9 +117,7 @@ def img_to_vector(filename):
|
||||
vector[i*32:i*32+32] = np.array([int(char) for char in line.strip()])
|
||||
return vector
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
train_data, train_labels = load_dataset("trainingDigits")
|
||||
|
||||
test_data = (
|
||||
@@ -172,4 +161,3 @@ if __name__ == "__main__":
|
||||
)
|
||||
|
||||
print(f"预测的标签: {predicted_label}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user