generated from LufsX/Experiment-kNN
This commit is contained in:
+22
-8
@@ -43,14 +43,30 @@ name = "陈垣豪"
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify(input_vector, dataSet, labels, k=3):
|
||||
distances = np.sum((dataSet - input_vector) ** 2, axis=1)
|
||||
# 计算协方差矩阵的逆
|
||||
cov_matrix = np.cov(dataSet.T)
|
||||
cov_inv = np.linalg.inv(cov_matrix)
|
||||
|
||||
#计算马氏距离
|
||||
distances_squared = np.array([
|
||||
(input_vector - point).dot(cov_inv).dot((input_vector - point).T)
|
||||
for point in dataSet
|
||||
])
|
||||
|
||||
# 获取最近k个样本的索引
|
||||
nearest_indices = np.argsort(distances)[:k]
|
||||
nearest_labels = [labels[i] for i in nearest_indices]
|
||||
most_common_label = Counter(nearest_labels).most_common(1)[0][0]
|
||||
return most_common_label
|
||||
|
||||
# 根据距离加权投票
|
||||
weights = 1 / (distances[nearest_indices] + 1e-10) # 避免除零
|
||||
weight_counts = Counter()
|
||||
|
||||
for label, weight in zip(nearest_labels, weights):
|
||||
weight_counts[label] += weight
|
||||
|
||||
# 返回加权投票结果
|
||||
return weight_counts.most_common(1)[0][0]
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_dataset(directory):
|
||||
file_list = os.listdir(directory)
|
||||
num_files = len(file_list)
|
||||
@@ -64,8 +80,6 @@ def load_dataset(directory):
|
||||
|
||||
return dataSet, np.array(labels)
|
||||
|
||||
|
||||
# 这里还写自己的代码实现
|
||||
def img_to_vector(filename):
|
||||
return_vector = np.zeros((1, 1024))
|
||||
with open(filename) as f:
|
||||
@@ -76,7 +90,6 @@ def img_to_vector(filename):
|
||||
return return_vector
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
train_data, train_labels = load_dataset("trainingDigits")
|
||||
|
||||
test_data = (
|
||||
@@ -113,10 +126,11 @@ if __name__ == "__main__":
|
||||
"00000000000001111111110000000000"
|
||||
"00000000000000000111100000000000"
|
||||
)
|
||||
|
||||
predicted_label = classify(
|
||||
np.array([int(char) for char in test_data]).reshape(1, 1024),
|
||||
train_data,
|
||||
train_labels,
|
||||
)
|
||||
|
||||
print(f"预测的标签: {predicted_label}")
|
||||
print(f"预测的标签: {predicted_label}")
|
||||
Reference in New Issue
Block a user