42 lines
1.4 KiB
Python
42 lines
1.4 KiB
Python
import numpy as np
|
|
from sklearn.svm import SVR
|
|
from sklearn.model_selection import train_test_split
|
|
from sklearn.metrics import mean_squared_error, r2_score
|
|
import matplotlib.pyplot as plt
|
|
|
|
# 生成一些示例数据
|
|
# 这里我们创建一个简单的非线性关系作为示例
|
|
np.random.seed(0)
|
|
X = np.sort(5 * np.random.rand(40, 1), axis=0)
|
|
y = np.sin(X).ravel()
|
|
|
|
# 为了使问题更具挑战性,我们向目标变量添加一些噪声
|
|
# y[::5]每隔5个元素取一个值, 总共40个元素,即最后取8个值 , np.random.rand(8) 随机生成一个值在[0,1)之间的形状为[8, 1]的数组,所以形状正好相加.
|
|
y[::5] += 3 * (0.5 - np.random.rand(8))
|
|
|
|
# 将数据集拆分为训练集和测试集
|
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
|
|
|
# 创建SVM回归模型
|
|
svr_rbf = SVR(kernel='rbf', C=100, gamma=0.1, epsilon=0.1)
|
|
|
|
# 训练模型
|
|
svr_rbf.fit(X_train, y_train)
|
|
|
|
# 对测试集进行预测
|
|
y_pred = svr_rbf.predict(X_test)
|
|
|
|
# 评估模型性能
|
|
mse = mean_squared_error(y_test, y_pred)
|
|
r2 = r2_score(y_test, y_pred)
|
|
print(f"Mean Squared Error: {mse:.2f}")
|
|
print(f"R^2 Score: {r2:.2f}")
|
|
|
|
# 可视化结果
|
|
plt.scatter(X, y, color='darkorange', label='data')
|
|
plt.plot(X_test, y_pred, color='navy', lw=2, label='SVR model')
|
|
plt.xlabel('data')
|
|
plt.ylabel('target')
|
|
plt.title('Support Vector Regression (SVR)')
|
|
plt.legend()
|
|
plt.savefig('./output/svm_r.png') |