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

相关推荐
兮动人17 小时前
C语言之指针入门
c语言·开发语言·c语言之指针入门
ada7_18 小时前
LeetCode(python)78.子集
开发语言·数据结构·python·算法·leetcode·职场和发展
我送炭你添花18 小时前
Pelco KBD300A 模拟器:06+5.串口实现的逻辑优化、配置管理与协议完善(二次迭代)
python·运维开发
databook18 小时前
前注意加工:让你的图表抓住读者的眼球
python·数据分析·数据可视化
知行学思18 小时前
Python配置管理完全指南:从dotenv到pydantic_settings
数据库·python·fastapi·环境变量·配置管理·pydantic·dotenv
nbsaas-boot19 小时前
Go 项目中如何正确升级第三方依赖(Go Modules 实战指南)
开发语言·后端·golang
wadesir19 小时前
C++基本数据类型详解(零基础掌握C++核心数据类型)
java·开发语言·c++
skywalk816319 小时前
wow文件处理trinitycore的文件处理
开发语言·游戏
一路往蓝-Anbo20 小时前
STM32单线串口通讯实战(五):RTOS架构 —— 线程安全与零拷贝设计
c语言·开发语言·stm32·单片机·嵌入式硬件·观察者模式·链表
leiming621 小时前
c++ map容器
开发语言·c++·算法