连续变量回归的k折交叉验证python代码
时间: 2024-06-16 18:04:19 浏览: 256
连续变量回归的k折交叉验证是一种常用的模型评估方法,可以用于评估回归模型的性能。下面是一个使用Python进行连续变量回归的k折交叉验证的示例代码:
```python
import numpy as np
from sklearn.model_selection import KFold
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# 假设有一组特征X和目标变量y
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([3, 5, 7, 9])
# 定义k折交叉验证的折数
k = 5
# 初始化模型和评估指标
model = LinearRegression()
mse_scores = []
# 进行k折交叉验证
kf = KFold(n_splits=k)
for train_index, test_index in kf.split(X):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
# 训练模型
model.fit(X_train, y_train)
# 预测并计算均方误差
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
# 将均方误差添加到列表中
mse_scores.append(mse)
# 计算平均均方误差
mean_mse = np.mean(mse_scores)
# 输出结果
print("Mean Squared Error:", mean_mse)
```
阅读全文