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

相关推荐
盼哥PyAI实验室1 天前
我用 Coze + Python,从 0 搭了一个“能真正用”的 AI 律师函系统
开发语言·人工智能·python
一路往蓝-Anbo1 天前
STM32单线串口通讯实战(四):裸机架构 —— 事件驱动与状态机设计
c语言·开发语言·stm32·单片机·嵌入式硬件·架构
zhaokuner1 天前
04-实体与标识-DDD领域驱动设计
java·开发语言·设计模式·架构
Zaralike1 天前
程序错误处理
java·开发语言
阿部多瑞 ABU1 天前
`chenmo` —— 可编程元叙事引擎 V2
python·ai·ai写作
cike_y1 天前
Spring的配置&各种依赖注入
java·开发语言·后端·spring
lly2024061 天前
JavaScript 使用误区
开发语言
算法与编程之美1 天前
探索多个卷积层的卷积神经网络
人工智能·深度学习·神经网络·机器学习·cnn
bkspiderx1 天前
C++中的访问控制:private、public与protected的深度解析
开发语言·c++·算法·访问控制·private·public·protected
lly2024061 天前
Python3 与 VSCode:高效开发环境的选择
开发语言