generated from LufsX/Challenge-kNN
This commit is contained in:
+11
-19
@@ -42,21 +42,10 @@ name = "章程鸿"
|
||||
# 这里写自己的代码实现
|
||||
import numpy as np
|
||||
from collections import Counter
|
||||
from sklearn.preprocessing import MinMaxScaler
|
||||
|
||||
def classify0(inX, dataSet, labels, k=3):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): KNN 算法参数,默认为3。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
|
||||
"""
|
||||
# 计算距离
|
||||
diffMat = inX - dataSet
|
||||
@@ -80,19 +69,23 @@ def load_data(file_path):
|
||||
labels = data[:, -1].astype(int)
|
||||
return features, labels
|
||||
|
||||
def preprocess_data(features):
|
||||
def normalize_features(features):
|
||||
"""
|
||||
特征预处理,包括归一化。
|
||||
"""
|
||||
scaler = MinMaxScaler()
|
||||
normalized_features = scaler.fit_transform(features)
|
||||
return normalized_features
|
||||
min_vals = features.min(axis=0)
|
||||
max_vals = features.max(axis=0)
|
||||
ranges = max_vals - min_vals
|
||||
m = features.shape[0]
|
||||
norm_features = features - np.tile(min_vals, (m, 1))
|
||||
norm_features = norm_features / np.tile(ranges, (m, 1))
|
||||
return norm_features
|
||||
|
||||
if __name__ == "__main__":
|
||||
train_file = "datingTrainSet2.tsv"
|
||||
|
||||
train_data, train_labels = load_data(train_file)
|
||||
train_data_normalized = preprocess_data(train_data)
|
||||
train_data_normalized = normalize_features(train_data)
|
||||
|
||||
# 选择几个有代表性的测试数据点
|
||||
test_points = [
|
||||
@@ -105,7 +98,6 @@ if __name__ == "__main__":
|
||||
]
|
||||
|
||||
for point in test_points:
|
||||
normalized_point = preprocess_data(np.array([point]))[0]
|
||||
normalized_point = normalize_features(np.array([point]))[0]
|
||||
predicted_label = classify0(normalized_point, train_data_normalized, train_labels)
|
||||
print(f"测试数据 {point} 预测标签: {predicted_label}")
|
||||
|
||||
print(f"测试数据 {point} 预测标签: {predicted_label}")
|
||||
Reference in New Issue
Block a user