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

This commit is contained in:
2024-10-24 16:51:00 +08:00
parent 18af8b0e47
commit 94094dba2c
+21 -7
View File
@@ -43,14 +43,30 @@ name = "陈垣豪"
# 这里写自己的代码实现 # 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=3): 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_indices = np.argsort(distances)[:k]
nearest_labels = [labels[i] for i in nearest_indices] 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): def load_dataset(directory):
file_list = os.listdir(directory) file_list = os.listdir(directory)
num_files = len(file_list) num_files = len(file_list)
@@ -64,8 +80,6 @@ def load_dataset(directory):
return dataSet, np.array(labels) return dataSet, np.array(labels)
# 这里还写自己的代码实现
def img_to_vector(filename): def img_to_vector(filename):
return_vector = np.zeros((1, 1024)) return_vector = np.zeros((1, 1024))
with open(filename) as f: with open(filename) as f:
@@ -76,7 +90,6 @@ def img_to_vector(filename):
return return_vector return return_vector
if __name__ == "__main__": if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_data, train_labels = load_dataset("trainingDigits") train_data, train_labels = load_dataset("trainingDigits")
test_data = ( test_data = (
@@ -113,6 +126,7 @@ if __name__ == "__main__":
"00000000000001111111110000000000" "00000000000001111111110000000000"
"00000000000000000111100000000000" "00000000000000000111100000000000"
) )
predicted_label = classify( predicted_label = classify(
np.array([int(char) for char in test_data]).reshape(1, 1024), np.array([int(char) for char in test_data]).reshape(1, 1024),
train_data, train_data,