generated from LufsX/Experiment-kNN
This commit is contained in:
+43
-14
@@ -25,8 +25,8 @@ import os
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423xxx"
|
||||
name = "test_name"
|
||||
id = "202210423112"
|
||||
name = "严锡好"
|
||||
|
||||
|
||||
"""
|
||||
@@ -39,9 +39,8 @@ name = "test_name"
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify(input_vector, dataSet, labels, k=0):
|
||||
def classify(input_vector, dataSet, labels, k=3):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
@@ -49,14 +48,25 @@ def classify(input_vector, dataSet, labels, k=0):
|
||||
- input_vector (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
|
||||
- k (int): kNN 算法参数,默认值为3。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 计算输入向量与数据集中每个向量之间的距离
|
||||
distances = [np.linalg.norm(row-input_vector) for row in dataSet]
|
||||
# 获取距离最小的k个样本的索引
|
||||
sortedDistIndices = np.argsort(distances)
|
||||
# 获取这些样本对应的标签
|
||||
classCount = {}
|
||||
for i in range(k):
|
||||
voteLabel = labels[sortedDistIndices[i]]
|
||||
# 统计每个类别的出现次数
|
||||
classCount[voteLabel] = classCount.get(voteLabel, 0) + 1
|
||||
# 返回出现次数最多的类别
|
||||
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
|
||||
return sortedClassCount[0][0]
|
||||
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_dataset(directory):
|
||||
"""
|
||||
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
@@ -68,13 +78,25 @@ def load_dataset(directory):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
fileList = os.listdir(directory)
|
||||
numberOfFiles = len(fileList)
|
||||
m = numberOfFiles
|
||||
n = 1024 # 假设每个图像是32x32的
|
||||
dataSet = np.zeros((m, n)) # 存储特征数据
|
||||
labels = [] # 存储标签
|
||||
for i in range(m):
|
||||
filename = fileList[i]
|
||||
filePath = os.path.join(directory, filename)
|
||||
vector = img_to_vector(filePath)
|
||||
dataSet[i, :] = vector
|
||||
# 假设文件名的格式是"label01.txt",其中label是标签
|
||||
label = int(filename.split('.')[0][1])
|
||||
labels.append(label)
|
||||
return dataSet, np.array(labels)
|
||||
|
||||
|
||||
# 这里还写自己的代码实现
|
||||
def img_to_vector(filename):
|
||||
"""
|
||||
将二值图像转换为向量。
|
||||
该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。
|
||||
|
||||
Args:
|
||||
- filename (str): 图像文件路径。
|
||||
@@ -82,12 +104,19 @@ def img_to_vector(filename):
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
"""
|
||||
|
||||
returnVect = np.zeros((1, 1024)) # 假设图像是32x32的
|
||||
with open(filename, 'r') as file:
|
||||
lines = file.readlines()
|
||||
index = 0
|
||||
for line in lines:
|
||||
for i in range(len(line)-1):
|
||||
if line[i] == '1':
|
||||
returnVect[0, index] = 1
|
||||
index += 1
|
||||
return returnVect
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
train_data, train_labels = load_dataset("trainingDigits")
|
||||
|
||||
test_data = (
|
||||
"00000000000000110000000000000000"
|
||||
"00000000000011111000000000000000"
|
||||
@@ -128,4 +157,4 @@ if __name__ == "__main__":
|
||||
train_labels,
|
||||
)
|
||||
|
||||
print(f"预测的标签: {predicted_label}")
|
||||
print(f"预测的标签: {predicted_label}")
|
||||
Reference in New Issue
Block a user