# 导入必要的库
from sklearn.model_selection import cross_val_score, KFold
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV, train_test_split
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import pyplot
# 创建样本数据
# X = np.array([[0, 0], [2, 2], [4, 4], [6, 6], [8, 8], [10, 10]])
# y = np.array([0, 2.3, 4.6, 6.9, 9.2, 11.5])
X = pd.read_excel('C:/Users/孙海涛/Desktop/k折/n/x.xlsx', sheet_name='Sheet1') # 读取数据
y = pd.read_excel('C:/Users/孙海涛/Desktop/k折/n/y.xlsx', sheet_name='Sheet1') # 读取数据
# 将数据集划分为训练集和测试集(留出法)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 定义需要使用的SVM模型
svr = SVR()
# 创建k折交叉验证对象
kf = KFold(n_splits=3)
# 定义超参数空间和网格搜索对象
param_grid = {'kernel': ['linear', 'rbf'], 'C': [0.1, 0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2], 'gamma': ['scale', 'auto']}
grid_search = GridSearchCV(svr, param_grid, cv=kf)
# 在训练集上使用网格搜索进行超参数寻优
grid_search.fit(X_train, y_train)
# 输出最佳超参数组合和在测试集上的性能指标
print("Best parameters:", grid_search.best_params_)
print("Test score: %.2f" % grid_search.score(X_test, y_test))
# Best parameters: {'C': 0.6, 'gamma': 'scale', 'kernel': 'rbf'}
# Test score: -0.20
#优化后的基模型
# print(grid_search.best_params_['kernel'])
model_svr = SVR(C=grid_search.best_params_['C'], kernel=grid_search.best_params_['kernel'], gamma=grid_search.best_params_['gamma'])
model_svr.fit(X_train, y_train)
predict_results = model_svr.predict(X_test)
print(len(predict_results))#10
dat = []
for i in range(1, 11):
dat.append(i)
# plt.xlim(0, 160) # 限定横轴的范围
palette = pyplot.get_cmap('Set1')
# plt.scatter(y_test, predict_results)
plt.plot(dat, y_test, color=palette(3), marker='*', label='True')
plt.plot(dat, predict_results, color=palette(1), marker='^', label='Predict')
plt.xticks(size=15)
plt.yticks(size=15)
plt.legend() # 让图例生效
# plt.show()
plt.show()
没有合适的资源?快使用搜索试试~ 我知道了~
pythonK近邻算法(k-Nearest Neighbors,KNN)解决分类问题
共3个文件
xlsx:2个
py:1个
0 下载量 65 浏览量
2024-01-09
16:38:34
上传
评论
收藏 19KB ZIP 举报
温馨提示
内含数据集+代码
资源推荐
资源详情
资源评论
收起资源包目录
k-svr.zip (3个子文件)
k折.py 2KB
x.xlsx 11KB
y.xlsx 10KB
共 3 条
- 1
资源评论
傻傻虎虎
- 粉丝: 3811
- 资源: 34
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功