generated from LufsX/Challenge-kNN
This commit is contained in:
+18
-20
@@ -46,8 +46,19 @@ name = "陈瑞琪祥"
|
||||
|
||||
|
||||
|
||||
def classify0(inX, dataSet, labels, k):
|
||||
result = classify0(test_data[i], train_data, train_labels, k=3) # 假设 k=3 是你选择的值
|
||||
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 = np.tile(inX, (dataSet.shape[0], 1)) - dataSet
|
||||
sqDiffMat = diffMat**2
|
||||
sqDistances = sqDiffMat.sum(axis=1)
|
||||
@@ -61,26 +72,15 @@ def classify0(inX, dataSet, labels, k):
|
||||
return sortedClassCount[0][0]
|
||||
|
||||
def load_data(file_path):
|
||||
"""
|
||||
加载 TSV 格式数据文件,并进行标准化处理。
|
||||
"""
|
||||
data = np.loadtxt(file_path, delimiter="\t")
|
||||
features = data[:, :-1]
|
||||
labels = data[:, -1].astype(int)
|
||||
features = (features - np.mean(features, axis=0)) / np.std(features, axis=0)
|
||||
return features, labels
|
||||
|
||||
def find_best_k(train_data, train_labels):
|
||||
best_accuracy = 0
|
||||
best_k = 1
|
||||
for k in range(1, 26, 2): # 尝试奇数的 k 值,从 1 到 25
|
||||
correct_count = 0
|
||||
for i in range(train_data.shape[0]):
|
||||
if classify0(train_data[i], train_data, train_labels, k) == train_labels[i]:
|
||||
correct_count += 1
|
||||
accuracy = correct_count / train_data.shape[0]
|
||||
if accuracy > best_accuracy:
|
||||
best_accuracy = accuracy
|
||||
best_k = k
|
||||
return best_k
|
||||
|
||||
def preprocess_data(features):
|
||||
# 简单的异常值处理
|
||||
Q1 = np.percentile(features, 25, axis=0)
|
||||
@@ -99,11 +99,9 @@ if __name__ == "__main__":
|
||||
train_data = preprocess_data(train_data)
|
||||
test_data = preprocess_data(test_data)
|
||||
|
||||
best_k = find_best_k(train_data, train_labels)
|
||||
|
||||
correct_count = 0
|
||||
for i in range(test_data.shape[0]):
|
||||
if classify0(test_data[i], train_data, train_labels, best_k) == test_labels[i]:
|
||||
if classify0(test_data[i], train_data, train_labels, k=3) == test_labels[i]:
|
||||
correct_count += 1
|
||||
|
||||
print(f"Accuracy with best k = {best_k}: {correct_count / test_data.shape[0] * 100:.2f}%")
|
||||
print(f"Accuracy: {correct_count / test_data.shape[0] * 100:.2f}%")
|
||||
Reference in New Issue
Block a user