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

This commit is contained in:
bzf
2024-10-17 16:47:09 +08:00
parent 1deeaa7cda
commit 2e25a652c5
+79 -76
View File
@@ -1,6 +1,8 @@
陈垣豪:
# function.py
import numpy as np
import os
from collections import Counter
"""
实验说明:
@@ -39,87 +41,88 @@ name = "李潼"
- int: 预测的分类标签。
"""
# 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=3):
"""
KNN 分类算法。
    distances = np.linalg.norm(dataSet - input_vector, axis=1)
    nearest_indices = np.argsort(distances)[:k]
    nearest_labels = [labels[i] for i in nearest_indices]
    most_common_label = Counter(nearest_labels).most_common(1)[0][0]
    return most_common_label
Args:
- input_vector (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,默认值为3。
Returns:
- int: 预测的分类标签。
"""
dataSet_size = dataSet.shape[0]
diff_mat = np.tile(input_vector, (dataSet_size, 1)) - dataSet
sq_diff_mat = diff_mat ** 2
sq_distances = sq_diff_mat.sum(axis=1)
distances = sq_distances ** 0.5
sorted_dist_indices = np.argsort(distances)
class_count = {}
for i in range(k):
vote_label = labels[sorted_dist_indices[i]]
class_count[vote_label] = class_count.get(vote_label, 0) + 1
sorted_class_count = sorted(class_count.items(), key=lambda x: x[1], reverse=True)
return sorted_class_count[0][0]
# 这里也写自己的代码实现
def load_dataset(directory):
"""
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
    file_list = os.listdir(directory)
    num_files = len(file_list)
    dataSet = np.zeros((num_files, 1024))
    labels = []
Args:
- directory (str): 数据文件夹路径。
    for i, filename in enumerate(file_list):
        label = int(filename.split('_')[0])
        labels.append(label)
        dataSet[i, :] = img_to_vector(os.path.join(directory, filename))
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
training_files = os.listdir(directory)
features = []
labels = []
for file in training_files:
label = int(file.split('_')[0])
with open(os.path.join(directory, file), 'r') as f:
content = f.read().strip()
feature = [int(char) for char in content]
features.append(feature)
labels.append(label)
return np.array(features), np.array(labels)
    return dataSet, np.array(labels)
# 这里还写自己的代码实现
def img_to_vector(filename):
    return_vector = np.zeros((1, 1024))
    with open(filename) as f:
        for i in range(32):
            line_str = f.readline()
            for j in range(32):
                return_vector[0, i * 32 + j] = int(line_str[j])
    return return_vector
if __name__ == "__main__":
train_data, train_labels = load_dataset("trainingDigits")
test_data = (
"00000000000000110000000000000000"
"00000000000011111000000000000000"
"00000000000011111100000000000000"
"00000000001111111110000000000000"
"00000000001111111110000000000000"
"00000000001111111100000000000000"
"00000000011111111000000000000000"
"00000000111111111000000000000000"
"00000000111111110000000000000000"
"00000000111111110000000000000000"
"00000000111111110000000000000000"
"00000000111111110000000000000000"
"00000000111111110000000000000000"
"00000001111111110000000000000000"
"00000001111111110000000000000000"
"00000001111111110000000000000000"
"00000001111111111111111111111111"
"11111111111111111111111111111111"
"11111111111111111111111111111111"
"11111111111111111111111111111111"
"11111111111111111111111111111111"
"11111111111111111111111111111111"
"11111111111111111111111111111111"
"11111111111111111111111111111111"
"1111111111111111111"
)
predicted_label = classify(
np.array([int(char) for char in test_data]).reshape(-1, 64),
train_data,
train_labels,
)
print(f"预测的标签: {predicted_label}")
    # 以下代码可用于测试,可自行随意修改
    train_data, train_labels = load_dataset("trainingDigits")
    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}")