generated from LufsX/Challenge-kNN
This commit is contained in:
+35
-11
@@ -40,6 +40,7 @@ name = "孔祥芷"
|
|||||||
|
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
|
|
||||||
def classify0(inX, dataSet, labels, k=3):
|
def classify0(inX, dataSet, labels, k=3):
|
||||||
"""
|
"""
|
||||||
KNN 分类算法。
|
KNN 分类算法。
|
||||||
@@ -48,50 +49,73 @@ def classify0(inX, dataSet, labels, k=3):
|
|||||||
- inX (numpy array): 输入待分类的样本。
|
- inX (numpy array): 输入待分类的样本。
|
||||||
- dataSet (numpy array): 训练数据集。
|
- dataSet (numpy array): 训练数据集。
|
||||||
- labels (list or numpy array): 训练集对应的标签。
|
- labels (list or numpy array): 训练集对应的标签。
|
||||||
- k (int): KNN 算法参数,请自行设置默认值,评测时仅会使用其默认值。
|
- k (int): KNN 算法参数。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
|
# 计算待分类样本与训练集中每个样本之间的距离
|
||||||
dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1))
|
dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1))
|
||||||
|
# 根据距离对训练样本进行排序
|
||||||
sorted_index = np.argsort(dists)
|
sorted_index = np.argsort(dists)
|
||||||
|
# 选择距离最近的k个样本
|
||||||
class_count = {}
|
class_count = {}
|
||||||
for i in range(k):
|
for i in range(k):
|
||||||
vote_label = labels[sorted_index[i]]
|
vote_label = labels[sorted_index[i]]
|
||||||
if vote_label not in class_count.keys():
|
class_count[vote_label] = class_count.get(vote_label, 0) + 1
|
||||||
class_count[vote_label] = 1
|
# 投票得到最多的标签作为预测结果
|
||||||
else:
|
|
||||||
class_count[vote_label] += 1
|
|
||||||
sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True)
|
sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True)
|
||||||
|
if sorted_class_count:
|
||||||
return sorted_class_count[0][0]
|
return sorted_class_count[0][0]
|
||||||
|
else:
|
||||||
|
return -1
|
||||||
|
|
||||||
def load_data(file_path):
|
def load_data(file_path):
|
||||||
|
"""
|
||||||
|
加载 TSV 格式数据文件。
|
||||||
|
|
||||||
#加载 TSV 格式数据文件。
|
Args:
|
||||||
|
- file_path (str): 文件路径。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- features (numpy array): 特征数据。
|
||||||
|
- labels (numpy array): 标签数据。
|
||||||
|
"""
|
||||||
data = np.loadtxt(file_path, delimiter="\t")
|
data = np.loadtxt(file_path, delimiter="\t")
|
||||||
features = data[:, :-1]
|
features = data[:, :-1]
|
||||||
labels = data[:, -1].astype(int)
|
labels = data[:, -1].astype(int)
|
||||||
return features, labels
|
return features, labels
|
||||||
|
|
||||||
|
def standardize(features):
|
||||||
|
mean = np.mean(features, axis=0)
|
||||||
|
std = np.std(features, axis=0)
|
||||||
|
standardized = (features - mean) / std
|
||||||
|
return standardized
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 以下代码可用于测试,可自行随意修改
|
|
||||||
train_file_path = "datingTrainSet2.tsv"
|
train_file_path = "datingTrainSet2.tsv"
|
||||||
train_features, train_labels = load_data(train_file_path)
|
train_features, train_labels = load_data(train_file_path)
|
||||||
|
|
||||||
test_file_path = "datingTestSet2.tsv"
|
test_file_path = "datingTestSet2.tsv"
|
||||||
test_features, test_labels = load_data(test_file_path)
|
test_features, test_labels = load_data(test_file_path)
|
||||||
|
|
||||||
|
# 特征标准化
|
||||||
|
train_features = standardize(train_features)
|
||||||
|
test_features = standardize(test_features)
|
||||||
|
|
||||||
correct_count = 0
|
correct_count = 0
|
||||||
for i in range(len(test_features)):
|
for i in range(len(test_features)):
|
||||||
test_feature = test_features[i].reshape(1, -1)
|
test_feature = test_features[i].reshape(1, -1)
|
||||||
predict_label = classify0(test_feature, train_features, train_labels, k=3)
|
predict_label = classify0(test_feature, train_features, train_labels, k=3)
|
||||||
|
if predict_label == -1:
|
||||||
|
continue
|
||||||
correct_count += (predict_label == test_labels[i])
|
correct_count += (predict_label == test_labels[i])
|
||||||
|
|
||||||
accuracy = correct_count / len(test_features)
|
accuracy = correct_count / len(test_features)
|
||||||
print(f"Accuracy: {accuracy:.2f}")
|
print(f"Accuracy: {accuracy:.2f}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
accuracy = correct_count / len(test_features)
|
||||||
|
print(f"Accuracy: {accuracy:.2f}")
|
||||||
Reference in New Issue
Block a user