作业二.自定义数据集使用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()

相关推荐
青禾8376 分钟前
Linux 系统信息、权限管理与 Python 并发编程(协程与线程)完全指南
linux·python
caimouse12 分钟前
ReactOS 图形系统分析(47):GDI 批处理 — gdibatch.c
c语言·开发语言
曲无忆13 分钟前
密码学三大核心技术解析
python·密码学
qq210846295314 分钟前
在python中什么是 self 和 cls?
开发语言·前端·python
nanawinona22 分钟前
2026年手工思路量化后,工具重点会怎样变化
人工智能·python
杨充32 分钟前
05.多用组合和少继承
开发语言·bash
今天AI了吗1 小时前
从聊天到委派:AI Agent 如何推进长期任务
数据库·人工智能·python·sql·rust
傻啦嘿哟1 小时前
王者荣耀爬虫:爬取全英雄皮肤数据,用Python做可视化分析
开发语言·爬虫·python
AI直播技术杂谈1 小时前
直播画面突然模糊了,排查了三个小时
开发语言·php