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

相关推荐
民乐团扒谱机6 小时前
【读论文】深度学习中的卷积算术指南 A guide to convolution arithmetic for deep learning
人工智能·深度学习·神经网络·机器学习·cnn·卷积神经网络·图像识别
geovindu6 小时前
python: Memento Pattern
开发语言·python·设计模式·备忘录模式
学无止境_永不停歇6 小时前
十、C++多态
开发语言·c++
寻星探路6 小时前
【JVM 终极通关指南】万字长文从底层到实战全维度深度拆解 Java 虚拟机
java·开发语言·jvm·人工智能·python·算法·ai
lbb 小魔仙6 小时前
【Java】Java 实战项目:手把手教你写一个电商订单系统
android·java·python
Aric_Jones6 小时前
JavaScript 从入门到精通:完整语法指南
开发语言·javascript·ecmascript
岱宗夫up6 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
Dxy12393102167 小时前
中文乱码恢复方案
开发语言·python
浅念-7 小时前
C/C++内存管理
c语言·开发语言·c++·经验分享·笔记·学习
回敲代码的猴子7 小时前
2月8日上机
开发语言·c++·算法