generated from LufsX/Challenge-SVM
This commit is contained in:
+21
-15
@@ -7,7 +7,7 @@ from sklearn.preprocessing import StandardScaler
|
||||
id = "202210423201"
|
||||
name = "陈瑞琪祥"
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
# 数据加载函数
|
||||
def load_data(filepath):
|
||||
@@ -31,20 +31,26 @@ def load_data(filepath):
|
||||
|
||||
return np.array(data), np.array(labels)
|
||||
|
||||
# 线性SVM训练函数
|
||||
def train_svm(X, y):
|
||||
"""
|
||||
支持向量机训练函数。
|
||||
"""
|
||||
scaler = StandardScaler()
|
||||
X_scaled = scaler.fit_transform(X)
|
||||
n_samples, n_features = X.shape
|
||||
weights = np.zeros(n_features)
|
||||
bias = 0
|
||||
learning_rate = 0.01
|
||||
iterations = 1000
|
||||
|
||||
model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42)
|
||||
model.fit(X_scaled, y)
|
||||
return model, scaler
|
||||
for _ in range(iterations):
|
||||
for idx, x_i in enumerate(X):
|
||||
condition = y[idx] * (np.dot(x_i, weights) - bias) >= 1
|
||||
if not condition:
|
||||
weights -= learning_rate * (2 * weights - np.dot(x_i, y[idx]))
|
||||
bias -= learning_rate * y[idx]
|
||||
|
||||
def predict_svm(model, scaler, X):
|
||||
X_scaled = scaler.transform(X)
|
||||
return model.predict(X_scaled)
|
||||
return weights, bias
|
||||
|
||||
# 预测函数
|
||||
def predict_svm(X, weights, bias):
|
||||
return np.sign(np.dot(X, weights) - bias)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 加载数据
|
||||
@@ -54,10 +60,10 @@ if __name__ == "__main__":
|
||||
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
||||
|
||||
# 训练SVM模型
|
||||
svm_model, scaler = train_svm(X_train, y_train)
|
||||
weights, bias = train_svm(X_train, y_train)
|
||||
|
||||
# 预测测试集
|
||||
y_pred = predict_svm(svm_model, scaler, X_test)
|
||||
y_pred = predict_svm(X_test, weights, bias)
|
||||
|
||||
# 评估模型
|
||||
accuracy = accuracy_score(y_test, y_pred)
|
||||
@@ -65,5 +71,5 @@ if __name__ == "__main__":
|
||||
|
||||
# 测试单个数据
|
||||
test_sample = X_test[11] # 选择第12个样本(从0开始计数)
|
||||
y_pred_single = predict_svm(svm_model, scaler, test_sample.reshape(1, -1))
|
||||
y_pred_single = predict_svm(test_sample.reshape(1, -1), weights, bias)
|
||||
print(f"\n单个样本预测结果: {y_pred_single[0]}, 实际结果: {y_test[11]}")
|
||||
Reference in New Issue
Block a user