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

This commit is contained in:
2024-10-20 13:51:30 +08:00
parent a5c0492334
commit 052a803c25
+35 -47
View File
@@ -41,26 +41,25 @@ name = "章程鸿·"
# 这里写自己的代码实现
import numpy as np
import os
from collections import Counter
import numpy as np
import os
from collections import Counter
# 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=2):
"""
使用 KNN 算法对输入样本进行分类。
参数:
- input_vector (numpy array): 输入待分类的样本(1xN)。
- dataSet (numpy array): 训练数据集(MxN)。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,默认值为 2。
返回:
- int: 预测的分类标签。
"""
# 将欧氏距离改为马氏距离
# 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=3):
"""
使用 KNN 算法对输入样本进行分类。
参数:
- input_vector (numpy array): 输入待分类的样本(1xN)。
- dataSet (numpy array): 训练数据集(MxN)。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,默认值为 3。
返回:
- int: 预测的分类标签。
"""
# 计算马氏距离
mean_vector = np.mean(dataSet, axis=0)
cov_matrix = np.cov(dataSet.T)
inv_cov_matrix = np.linalg.inv(cov_matrix)
@@ -81,20 +80,10 @@ def classify(input_vector, dataSet, labels, k=2):
weighted_votes[label] += weight
return np.argmax(weighted_votes)
# 这里也写自己的代码实现
def load_dataset(directory):
"""
加载数据集中的图像,并将其转换为特征向量和标签。
参数:
- directory (str): 数据文件夹路径。
返回:
- np.array: 特征数据(Mx1024)。
- np.array: 标签数据(Mx1)。
"""
feature_list = []
# 这里写自己的代码实现
def load_dataset(directory):
feature_list = []
label_list = []
for file in os.listdir(directory):
file_path = os.path.join(directory, file)
@@ -110,25 +99,25 @@ def load_dataset(directory):
feature_matrix = (feature_matrix - min_value) / (max_value - min_value)
return feature_matrix, label_array
def img_to_vector(filename):
"""
将二值图像转换为向量。
Args:
- filename (str): 图像文件路径。
Returns:
- np.array: 二值图像向量。
"""
vector = np.zeros((1024,))
# 这里写自己的代码实现
def img_to_vector(filename):
"""
将二值图像转换为向量。
Args:
- filename (str): 图像文件路径。
Returns:
- np.array: 二值图像向量。
"""
vector = np.zeros((1024,))
with open(filename) as file:
for i, line in enumerate(file):
vector[i*32:i*32+32] = np.array([int(char) for char in line.strip()])
return vector
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_data, train_labels = load_dataset("trainingDigits")
test_data = (
@@ -172,4 +161,3 @@ if __name__ == "__main__":
)
print(f"预测的标签: {predicted_label}")