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

相关推荐
喵了meme3 小时前
C语言实战4
c语言·开发语言
码界奇点3 小时前
Python从0到100一站式学习路线图与实战指南
开发语言·python·学习·青少年编程·贴图
9ilk3 小时前
【C++】--- 特殊类设计
开发语言·c++·后端
sali-tec3 小时前
C# 基于halcon的视觉工作流-章68 深度学习-对象检测
开发语言·算法·计算机视觉·重构·c#
测试人社区-小明4 小时前
智能弹性伸缩算法在测试环境中的实践与验证
人工智能·测试工具·算法·机器学习·金融·机器人·量子计算
Laravel技术社区4 小时前
pytesseract 中英文 识别图片文字
python
生骨大头菜5 小时前
使用python实现相似图片搜索功能,并接入springcloud
开发语言·python·spring cloud·微服务
绝不收费—免费看不了了联系我5 小时前
Fastapi的单进程响应问题 和 解决方法
开发语言·后端·python·fastapi
人邮异步社区5 小时前
PRML为何是机器学习的经典书籍中的经典?
人工智能·机器学习
xqqxqxxq5 小时前
背单词软件技术笔记(V2.0扩展版)
java·笔记·python