generated from LufsX/Experiment-kNN
This commit is contained in:
+23
-92
@@ -1,53 +1,20 @@
|
|||||||
# function.py
|
import numpy as np
|
||||||
import numpy as np
|
import os
|
||||||
import os
|
|
||||||
from scipy.spatial.distance import mahalanobis
|
from scipy.spatial.distance import mahalanobis
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
"""
|
|
||||||
实验说明:
|
|
||||||
- 自行编写实现数据加载与 kNN 的手写数字分类算法。
|
|
||||||
- 函数输入: 待分类的样本 input_vector, 训练数据集 dataSet, 训练集对应的标签 labels。
|
|
||||||
- 函数返回: 预测的分类标签。
|
|
||||||
|
|
||||||
注意事项:
|
# 学号和姓名
|
||||||
- 在 function.py 中实现 kNN 分类算法。
|
id = "202210423111"
|
||||||
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
|
name = ""
|
||||||
- 自动评测脚本仅会加载 classify 和 load_data 函数,请勿修改函数名。
|
|
||||||
- 训练集和测试集需手动下载解压,并放入当前目录下。
|
|
||||||
|
|
||||||
测评环境:
|
|
||||||
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
|
|
||||||
- OS: Ubuntu 22.04.4 LTS
|
|
||||||
- Python: 3.10.12
|
|
||||||
- numpy: 2.1.1
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
"""
|
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
|
||||||
"""
|
|
||||||
id = "202210423111"
|
|
||||||
name = "李劲"
|
|
||||||
|
|
||||||
|
|
||||||
"""
|
|
||||||
参数说明:
|
|
||||||
- input_vector (numpy array): 输入待分类的样本。
|
|
||||||
- dataSet (numpy array): 训练数据集。
|
|
||||||
- labels (list or numpy array): 训练集对应的标签。
|
|
||||||
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
|
|
||||||
返回值:
|
|
||||||
- int: 预测的分类标签。
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
|
||||||
def classify(input_vector, dataSet, labels, k=1):
|
def classify(input_vector, dataSet, labels, k=1):
|
||||||
"""
|
"""
|
||||||
KNN 分类算法,使用马氏距离。
|
KNN 分类算法,使用马氏距离。
|
||||||
"""
|
"""
|
||||||
# 计算协方差矩阵及其逆
|
# 计算协方差矩阵及其逆
|
||||||
cov_matrix = np.cov(dataSet.T)
|
cov_matrix = np.cov(dataSet.T)
|
||||||
|
if np.linalg.det(cov_matrix) == 0: # 检查奇异矩阵
|
||||||
|
cov_matrix += np.eye(cov_matrix.shape[0]) * 1e-8 # 添加正则化
|
||||||
inv_cov_matrix = np.linalg.inv(cov_matrix)
|
inv_cov_matrix = np.linalg.inv(cov_matrix)
|
||||||
|
|
||||||
# 计算马氏距离
|
# 计算马氏距离
|
||||||
@@ -77,12 +44,8 @@ def load_dataset(directory):
|
|||||||
filepath = os.path.join(directory, filename)
|
filepath = os.path.join(directory, filename)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 假设文件名格式为 "数字_编号.txt"
|
|
||||||
label = int(filename.split('_')[0])
|
label = int(filename.split('_')[0])
|
||||||
|
|
||||||
# 加载文件中的二进制数据并转换为 1D 向量
|
|
||||||
image_vector = img_to_vector(filepath)
|
image_vector = img_to_vector(filepath)
|
||||||
|
|
||||||
features.append(image_vector)
|
features.append(image_vector)
|
||||||
labels.append(label)
|
labels.append(label)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -98,55 +61,23 @@ def img_to_vector(filename):
|
|||||||
with open(filename) as file:
|
with open(filename) as file:
|
||||||
lines = file.readlines()
|
lines = file.readlines()
|
||||||
image_vector = np.array([int(char) for line in lines for char in line.strip()])
|
image_vector = np.array([int(char) for line in lines for char in line.strip()])
|
||||||
|
return image_vector
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error reading file {filename}: {e}")
|
print(f"Error reading file {filename}: {e}")
|
||||||
image_vector = np.zeros(expected_vector_length) # 假设有一个预期的向量长度
|
return np.zeros(1024) # 假设有一个预期的向量长度,此处设为1024
|
||||||
# 或者可以抛出一个异常,根据需求决定
|
|
||||||
|
|
||||||
return image_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 = (
|
||||||
"00000000000000110000000000000000"
|
"00000000000000110000000000000000"
|
||||||
"00000000000011111000000000000000"
|
# ... (省略的测试数据)
|
||||||
"00000000000011111100000000000000"
|
)
|
||||||
"00000000001111111110000000000000"
|
predicted_label = classify(
|
||||||
"00000000001111111110000000000000"
|
np.array([int(char) for char in test_data]).reshape(1, 1024),
|
||||||
"00000000001111111100000000000000"
|
train_data,
|
||||||
"00000000011111111000000000000000"
|
train_labels,
|
||||||
"00000000111111111000000000000000"
|
)
|
||||||
"00000000111111110000000000000000"
|
|
||||||
"00000000111111110000000000000000"
|
|
||||||
"00000000111111110000000000000000"
|
|
||||||
"00000000111111110000000000000000"
|
|
||||||
"00000000111111100000000000000000"
|
|
||||||
"00000001111111100000000000000000"
|
|
||||||
"00000001111111100000000000000000"
|
|
||||||
"00000001111111100000000000000000"
|
|
||||||
"00000001111111111111000000000000"
|
|
||||||
"00000001111111111111111000000000"
|
|
||||||
"00000001111111111111111100000000"
|
|
||||||
"00000011111111111111111110000000"
|
|
||||||
"00000011111111111111111110000000"
|
|
||||||
"00000001111111111111111110000000"
|
|
||||||
"00000001111111111111111110000000"
|
|
||||||
"00000000111111111100111111100000"
|
|
||||||
"00000000111111111000111111100000"
|
|
||||||
"00000000011111111001111111100000"
|
|
||||||
"00000000011111111111111111000000"
|
|
||||||
"00000000001111111111111111000000"
|
|
||||||
"00000000000111111111111111000000"
|
|
||||||
"00000000000011111111111100000000"
|
|
||||||
"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