generated from LufsX/Challenge-SVM
This commit is contained in:
+9
-7
@@ -1,13 +1,11 @@
|
|||||||
import numpy as np
|
|
||||||
from sklearn.svm import SVC
|
|
||||||
from sklearn.model_selection import train_test_split
|
|
||||||
from sklearn.metrics import classification_report, accuracy_score
|
|
||||||
from sklearn.preprocessing import StandardScaler
|
|
||||||
|
|
||||||
id = "202210423201"
|
id = "202210423201"
|
||||||
name = "陈瑞琪祥"
|
name = "陈瑞琪祥"
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
from sklearn.model_selection import train_test_split
|
||||||
|
from sklearn.metrics import accuracy_score
|
||||||
|
|
||||||
# 数据加载函数
|
# 数据加载函数
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
@@ -52,6 +50,11 @@ def train_svm(X, y):
|
|||||||
def predict_svm(X, weights, bias):
|
def predict_svm(X, weights, bias):
|
||||||
return np.sign(np.dot(X, weights) - bias)
|
return np.sign(np.dot(X, weights) - bias)
|
||||||
|
|
||||||
|
# 评估函数
|
||||||
|
def evaluate_svm(test_data, weights, bias):
|
||||||
|
predictions = [predict_svm(test_data[i].reshape(1, -1), weights, bias) for i in range(len(test_data))]
|
||||||
|
return predictions
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载数据
|
# 加载数据
|
||||||
X, y = load_data("./data/horse-colic.data")
|
X, y = load_data("./data/horse-colic.data")
|
||||||
@@ -63,7 +66,7 @@ if __name__ == "__main__":
|
|||||||
weights, bias = train_svm(X_train, y_train)
|
weights, bias = train_svm(X_train, y_train)
|
||||||
|
|
||||||
# 预测测试集
|
# 预测测试集
|
||||||
y_pred = predict_svm(X_test, weights, bias)
|
y_pred = evaluate_svm(X_test, weights, bias)
|
||||||
|
|
||||||
# 评估模型
|
# 评估模型
|
||||||
accuracy = accuracy_score(y_test, y_pred)
|
accuracy = accuracy_score(y_test, y_pred)
|
||||||
@@ -73,4 +76,3 @@ if __name__ == "__main__":
|
|||||||
test_sample = X_test[11] # 选择第12个样本(从0开始计数)
|
test_sample = X_test[11] # 选择第12个样本(从0开始计数)
|
||||||
y_pred_single = predict_svm(test_sample.reshape(1, -1), weights, bias)
|
y_pred_single = predict_svm(test_sample.reshape(1, -1), weights, bias)
|
||||||
print(f"\n单个样本预测结果: {y_pred_single[0]}, 实际结果: {y_test[11]}")
|
print(f"\n单个样本预测结果: {y_pred_single[0]}, 实际结果: {y_test[11]}")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user