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

相关推荐
小马过河R1 小时前
EdgeOne深度解析:从原理、适用场景到COS接入的技术逻辑
java·开发语言·前端·spring·cos
Marst Code1 小时前
上位机开发日记 · 第 12 篇 · 测试:设备模拟器是核心资产
python
多弗朗皮卡丘1 小时前
C++ 红黑树
开发语言·c++·红黑树
ZoeLandia1 小时前
TypeScript 04:类型断言与类型守卫
开发语言·前端·typescript
geovindu1 小时前
rust: pool Pattern
开发语言·后端·设计模式·rust·对象池简写模式
坊钰1 小时前
【LangGraph框架入门级】4. 支持联网搜索的智能代理系统
python·ai编程·langgraph
运维@小兵2 小时前
安装Pycharm并破解
ide·python·pycharm
jimy12 小时前
标准的动态类型定义与“多态”无关,非多态对象同样会出现动态类型不同于静态类型的情形
开发语言·c++
冬、不眠的夜2 小时前
Nuitka 将 python 程序编译成 exe 指南
开发语言·python
CVer儿2 小时前
起源1引擎相关知识点2--World Brush+func_detail
开发语言