sy1
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 24s

This commit is contained in:
2024-10-12 22:57:26 +08:00
parent c34258ec92
commit 68058515dd
+55 -51
View File
@@ -25,8 +25,8 @@ import os
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423109"
name = "孔祥芷"
"""
@@ -41,7 +41,7 @@ name = "test_name"
# 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=0):
def classify(input_vector, dataSet, labels, k=3):
"""
KNN 分类算法。
@@ -49,17 +49,31 @@ 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: 预测的分类标签。
"""
# 计算输入向量与数据集中每个向量之间的欧式距离
diffMat = np.tile(input_vector, (dataSet.shape[0], 1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances**0.5
# 获取k个最近邻的索引
sortedDistIndices = distances.argsort()
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistIndices[i]]
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
# 以出现次数最多的类别作为预测类别
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
return sortedClassCount[0][0]
# 这里也写自己的代码实现
def load_dataset(directory):
"""
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
从文件夹中加载数据。
Args:
- directory (str): 数据文件夹路径。
@@ -68,13 +82,22 @@ def load_dataset(directory):
- np.array: 特征数据。
- np.array: 标签数据。
"""
fileList = os.listdir(directory) # 使用 os.listdir
numFiles = len(fileList)
trainingMat = np.zeros((numFiles, 1024))
hwLabels = []
for i in range(numFiles):
fileNameStr = fileList[i]
fileStr = fileNameStr.split(',')[0]
classNumStr = int(fileStr.split('_')[0])
hwLabels.append(classNumStr)
returnVect = img_to_vector(os.path.join(directory, fileNameStr)) # 使用 os.path.join
trainingMat[i, :] = returnVect
return trainingMat, np.array(hwLabels)
# 这里还写自己的代码实现
def img_to_vector(filename):
"""
将二值图像转换为向量。
该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。
Args:
- filename (str): 图像文件路径。
@@ -82,50 +105,31 @@ def img_to_vector(filename):
Returns:
- np.array: 二值图像向量。
"""
returnVect = np.zeros((1, 1024))
with open(filename, 'r') as fr:
for i in range(32):
lineStr = fr.readline()
for j in range(32):
returnVect[0, 32 * i + j] = int(lineStr[j])
return returnVect.flatten()
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_data, train_labels = load_dataset("trainingDigits")
# 加载训练集和测试集数据
train_data, train_labels = load_dataset("C:\\Users\\kxz\\Desktop\\kxz\\ds\\ML\\sy1\\trainingDigits")
test_data, test_labels = load_dataset("C:\\Users\\kxz\\Desktop\\kxz\\ds\\ML\\sy1\\testDigits")
# Test the classifier
errorCount = 0.0
mTest = len(test_data)
for i in range(mTest):
vectorUnderTest = test_data[i, :]
classifierResult = classify(vectorUnderTest, train_data, train_labels, 3)
print(f"KNN classified as: {classifierResult}, Actual: {test_labels[i]}")
if (classifierResult != test_labels[i]):
errorCount += 1.0
print(f"\nError Count: {errorCount}")
print(f"\nAccuracy: {(1 - errorCount / float(mTest)) * 100}%")
test_data = (
"00000000000000110000000000000000"
"00000000000011111000000000000000"
"00000000000011111100000000000000"
"00000000001111111110000000000000"
"00000000001111111110000000000000"
"00000000001111111100000000000000"
"00000000011111111000000000000000"
"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}")