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

This commit is contained in:
77
2024-10-16 18:58:24 +08:00
parent 1df32a4709
commit 4dc272a10a
+39
View File
@@ -54,6 +54,21 @@ def classify(input_vector, dataSet, labels, k=0):
Returns:
- int: 预测的分类标签。
"""
# 计算输入向量与数据集中每个样本的欧氏距离
distances = np.sqrt(((dataSet - input_vector) ** 2).sum(axis=1))
# 获取距离最近的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]
# 这里也写自己的代码实现
@@ -68,6 +83,20 @@ def load_dataset(directory):
- np.array: 特征数据。
- np.array: 标签数据。
"""
fileList = os.listdir(directory)
m = len(fileList)
dataSet = np.zeros((m, 1024)) # 假设每个图像是32x32的
labels = []
i = 0
for file in fileList:
path = os.path.join(directory, file)
vector = img_to_vector(path)
dataSet[i, :] = vector
# 假设文件名的格式是"label_number.txt"
label = int(file.split('_')[0])
labels.append(label)
i = i + 1
return dataSet, np.array(labels)
# 这里还写自己的代码实现
@@ -82,6 +111,16 @@ def img_to_vector(filename):
Returns:
- np.array: 二值图像向量。
"""
returnVect = np.zeros((1, 1024)) # 假设图像是32x32的
with open(filename, 'r') as fr:
lines = fr.readlines()
w = 0
for i in range(32): # 假设图像是32行
for j in range(32): # 每行32个像素
if lines[i][j] == '1':
returnVect[0, w] = 1
w += 1
return returnVect.flatten() # 返回一维数组
if __name__ == "__main__":