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

This commit is contained in:
2024-10-17 09:17:59 +08:00
parent c53efbfdcc
commit b8c5bba806
+52 -27
View File
@@ -1,33 +1,16 @@
id = "202210423210"
name = "陈宇杰"
import numpy as np
import os
from collections import Counter
from sklearn.preprocessing import MinMaxScaler
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423210"
name = "陈宇杰"
"""
函数名称: load_dataset
功能: 加载训练数据集和测试数据集。
参数:
- directory (str): 包含手写数字图像的文件夹路径。
返回值:
- dataSet (numpy array): 训练数据集或测试数据集,shape 为 (m, 1024)。
- labels (numpy array): 训练集或测试集对应的标签,shape 为 (m,)。
"""
import numpy as np
import os
from collections import Counter
# 加载数据的函数
def load_dataset(directory):
file_list = os.listdir(directory)
data_matrix = []
labels = []
for file_name in file_list:
file_path = os.path.join(directory, file_name)
# 读取txt文件并将其转化为向量
@@ -36,10 +19,17 @@ def load_dataset(directory):
# 假设文件名格式为:{数字}_某些字符.txt,提取数字作为标签
label = int(file_name.split('_')[0])
labels.append(label)
return np.array(data_matrix), np.array(labels)
# 将32x32的二值图像转换为1x1024的向量
"""
函数名称: img_to_vector
功能: 将32x32的二值图像转换为1x1024的向量。
参数:
- file_path (str): 图像文件的路径。
返回值:
- vector (numpy array): 转换后的1x1024的向量。
"""
def img_to_vector(file_path):
vector = np.zeros((1, 1024))
with open(file_path, 'r') as f:
@@ -49,7 +39,17 @@ def img_to_vector(file_path):
vector[0, 32 * i + j] = int(lines[i][j])
return vector
# kNN 分类函数
"""
函数名称: classify
功能: 使用kNN算法对输入样本进行分类。
参数:
- input_vector (numpy array): 输入待分类的样本,shape 为 (1024,)。
- dataSet (numpy array): 训练数据集,shape 为 (m, 1024)。
- labels (list or numpy array): 训练集对应的标签,shape 为 (m,)。
- k (int): kNN 算法的参数,默认值为3。
返回值:
- int: 预测的分类标签。
"""
def classify(input_vector, dataSet, labels, k=3):
# 计算欧氏距离
distances = np.linalg.norm(dataSet - input_vector, axis=1)
@@ -64,11 +64,36 @@ def classify(input_vector, dataSet, labels, k=3):
most_common = Counter(nearest_labels).most_common(1)
return most_common[0][0]
# 实验主程序
"""
函数名称: normalize_data
功能: 对数据进行归一化处理,将特征缩放到相同范围,通常是 [0, 1]。
参数:
- dataSet (numpy array): 需要归一化的训练数据集或测试数据集。
返回值:
- normalized_dataSet (numpy array): 归一化后的数据集。
"""
def normalize_data(dataSet):
# 将数据集 reshape 成二维数组
num_samples = dataSet.shape[0]
dataSet_reshaped = dataSet.reshape(num_samples, -1)
# 对数据进行归一化处理
scaler = MinMaxScaler()
return scaler.fit_transform(dataSet_reshaped)
"""
实验主程序:
- 加载训练集和测试集。
- 测试 kNN 算法的分类效果,并计算分类精度。
"""
def main():
# 加载训练集和测试集
training_data, training_labels = load_dataset('trainingdigits')
test_data, test_labels = load_dataset('testdigits')
training_data, training_labels = load_dataset('trainingDigits')
test_data, test_labels = load_dataset('testDigits')
# 归一化数据
training_data = normalize_data(training_data)
test_data = normalize_data(test_data)
# 测试 kNN 算法
total_tests = len(test_data)