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