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

This commit is contained in:
2024-09-26 16:40:21 +08:00
parent db4866b30e
commit e81f146552
+33 -11
View File
@@ -23,8 +23,8 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423226"
name = "潘宇豪"
"""
@@ -38,23 +38,46 @@ name = "test_name"
# 这里写自己的代码实现
def classify0(inX, dataSet, labels):
def classify0(inX, dataSet, labels, k=3):
"""
KNN 分类算法。
Args:
参数:
- inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): 使用的邻居数量。
Returns:
返回值:
- int: 预测的分类标签。
"""
# 计算输入样本与训练数据集中每个样本的欧氏距离
diffMat = np.tile(inX, (dataSet.shape[0], 1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = np.sqrt(sqDistances)
# 对距离进行排序并找到最近的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 item: item[1], reverse=True)
return sortedClassCount[0][0]
def load_data(file_path):
"""
加载 TSV 格式数据文件。
加载TSV格式的数据文件。
参数:
- file_path (str): 数据文件的路径。
返回值:
- tuple: 包含特征数组和标签数组的元组。
"""
features = []
labels = []
@@ -68,11 +91,10 @@ def load_data(file_path):
return np.array(features), np.array(labels)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_file = "datingTrainSet2.tsv"
train_data, train_labels = load_data(train_file)
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))
# 使用一个测试样本进行测试
test_result = classify0([65915, 3.868359, 0.128078], train_data, train_labels, k=3)
print("预测结果:", test_result)