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

相关推荐
草莓火锅1 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
j_xxx404_1 小时前
C++ STL:阅读list源码|list类模拟|优化构造|优化const迭代器|优化迭代器模板|附源码
开发语言·c++
DreamNotOver1 小时前
批量转换论文正文引用为上标
开发语言·论文上标
散峰而望1 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
fie88892 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
gihigo19982 小时前
MATLAB中生成混淆矩阵
开发语言·matlab·矩阵
dreams_dream2 小时前
Flask
后端·python·flask
曾几何时`2 小时前
C++——this指针
开发语言·c++
小冯的编程学习之路2 小时前
【C++】: C++基于微服务的即时通讯系统(1)
开发语言·c++·微服务
mywpython2 小时前
用Python和Websockets库构建一个高性能、低延迟的实时消息推送服务
python·websocket