python输出拟合图像的经验误差和测试误差的代码
时间: 2024-05-04 11:15:27 浏览: 31
以下是一个简单的 Python 代码示例,用于输出拟合图像的经验误差和测试误差:
```python
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import numpy as np
# 生成一些随机数据
X = np.random.rand(100, 1)
y = 2 + 3 * X + np.random.randn(100, 1)
# 拆分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练模型
reg = LinearRegression()
reg.fit(X_train, y_train)
# 计算经验误差
y_train_pred = reg.predict(X_train)
train_error = mean_squared_error(y_train, y_train_pred)
# 计算测试误差
y_test_pred = reg.predict(X_test)
test_error = mean_squared_error(y_test, y_test_pred)
# 输出误差值
print("经验误差:", train_error)
print("测试误差:", test_error)
```
希望这可以帮助你。如果你有任何其他问题,请随时问我。
阅读全文