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

相关推荐
万联WANFLOW1 小时前
多分支企业组网,IP 网段到底该怎么规划
开发语言·php
阿里嘎多学长1 小时前
2026-07-07 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Alan_6912 小时前
聊聊 Swagger/Postman/Apifox 的真实选型与 Python 项目实战
python·测试工具·postman
cookies_s_s3 小时前
C++ 字符串动态创建对象 -- 工厂模式、自动注册、模板递归动态调用
服务器·开发语言·c++
z小猫不吃鱼3 小时前
模型剪枝经典论文精读:Pruning Filters for Efficient ConvNets
算法·机器学习·剪枝
智慧物业老杨3 小时前
物业绿化数智化权责管控方案:基于工单平台的双层权限追溯模块落地实践
python
盐焗鹌鹑蛋4 小时前
【C++】继承
开发语言·c++
Metaphor6924 小时前
使用 Python 在 Word 文档中添加批注
python·word
FreakStudio4 小时前
WIZnet 开源方案分享:W55MH32 开发板 + 小智 AI实现以太网版本的小智机器人
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
栈溢出了4 小时前
Java Lambda 表达式笔记
java·开发语言·intellij-idea