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

相关推荐
Chengbei116 分钟前
JsOwl|AI 赋能 JS 敏感信息扫描器,AST + 正则、source‑map 源码还原、登录态爬虫输出交互式 HTML 报告
开发语言·javascript·网络·人工智能·爬虫·网络安全·自动化
David猪大卫8 分钟前
【C++修炼】string类:string类的模拟实现
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
geovindu11 分钟前
rust: Iterator Pattern
开发语言·后端·设计模式·rust·行为模式·迭代器模
细节处有神明13 分钟前
零样本时序预测:Mistral Timestral 本地实测
人工智能·机器学习·时间序列
pride.li18 分钟前
第12章 Python 教程-流程控制:循环结构
linux·服务器·python·算法
SDWAN_Cheap36 分钟前
深度解析什么是CDN加速:从原理到实践的技术拆解
开发语言·cdn加速
鬼手点金37 分钟前
模型即 Agent:当模型本身成为产品
开发语言·前端·人工智能·python·机器学习
田里的水稻42 分钟前
PyTorch-Dataset\DataLoader数据加载
人工智能·pytorch·python
卷无止境1 小时前
Python 3.14 自由线程:拆掉 GIL 之后,我们到底得到了什么
后端·python
染指11101 小时前
147.Agent-LangGraph归并函数
开发语言·人工智能·python·langchain·agents