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

相关推荐
乐园游梦记4 分钟前
下载 Docker 镜像(CVAT)资源
人工智能·python·深度学习·yolo·机器学习·cvat
热爱生活的猴子7 分钟前
什么情况是过拟合,什么情况判定为欠拟合,什么情况下判定微调后效果不如预训练,什么情况下说明是分类边界模糊,什么是权重过大导致过拟合
人工智能·机器学习·分类
第一程序员7 分钟前
Python数据分析:Pandas vs Polars 详细对比
python·github
程序员杰哥8 分钟前
Web UI自动化测试之PO篇
自动化测试·软件测试·python·selenium·测试工具·ui·测试用例
无责任此方_修行中9 分钟前
MkDocs宫斗事件:开源项目控制权争夺与技术社区分裂
python·程序员
lagrahhn9 分钟前
python面向对象中__new__和__init__区别
后端·python·程序员
羚羊角uou11 分钟前
【Linux网络】select详解
linux·服务器·开发语言·网络·c++
C++ 老炮儿的技术栈11 分钟前
c++ this 指针的用途
c语言·开发语言·c++·windows·qt·github
watersink12 分钟前
第7章 软件架构设计
java·开发语言
风舞雪凌月15 分钟前
【趣谈】移动系统和桌面系统编程语言思考
java·c语言·c++·python·学习·objective-c·swift