作业二.自定义数据集使用scikit-learn中的包实现线性回归方法对其进行拟合

from sklearn.linear_model import LinearRegression

from sklearn.model_selection import train_test_split

from sklearn.metrics import mean_squared_error

import numpy as np

import matplotlib.pyplot as plt

np.random.seed(0)

加载自定义数据集

X = 2 * np.random.rand(100, 1)

y = 4 + 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)

创建线性回归模型对象并拟合训练数据

model = LinearRegression()

model.fit(X_train, y_train)

使用训练好的模型对测试集进行预测

y_pred = model.predict(X_test)

计算预测误差

mse = mean_squared_error(y_test, y_pred)

print("均方误差:", mse)

plt.scatter(X_test, y_test, color='blue')

plt.plot(X_test, y_pred, color='red')

plt.show()

相关推荐
LFly_ice20 小时前
Next-4-路由导航
开发语言·前端·javascript
卡尔特斯20 小时前
pyenv 安装的 python 版本缺少 tkinter 报错 import _tkinter # If this fails your Python xxx
python
liulanba20 小时前
YOLOv6 端到端详解
机器学习
38242782720 小时前
python :__call__方法
开发语言·python
是Yu欸20 小时前
从Ascend C算子开发视角看CANN的“软硬协同”
c语言·开发语言·云原生·昇腾·ascend·cann·开放社区
黎雁·泠崖20 小时前
C 语言字符串进阶:strcpy/strcat/strcmp 精讲
c语言·开发语言
八月ouc20 小时前
Python实战小游戏(三): 简易文件管理器
python·shutil·文件管理器·os.walk·pathlib
赴前尘21 小时前
golang获取一个系统中没有被占用的端口
开发语言·后端·golang
嘴贱欠吻!21 小时前
JavaSE基础知识
java·开发语言