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

相关推荐
cup1120 小时前
[开源] Meta Assistant / 告别命令行,我为一堆 Python 脚本做了一个 Windows 任务栏的“家”
windows·python·工具·nuitka·脚本运行
晨曦中的暮雨21 小时前
Golang速通(Javaer版)
java·开发语言·后端·golang
Sirius Wu21 小时前
意图&实体ToolCall_Prompt调优
人工智能·机器学习·语言模型·prompt·aigc
小小编程路21 小时前
Python 还有容器类型互转、进制转换、字符编码转换
开发语言·windows·python
qeen8721 小时前
【C++】类与对象之类的默认成员函数(二)
android·c语言·开发语言·c++·笔记·学习
CRMEB系统商城21 小时前
CRMEB多商户系统(Java)v2.3公测版发布
java·开发语言·人工智能·小程序·开源·php
Samooyou21 小时前
RAG项目案例--02在线检索&过滤流水线
人工智能·python·ai·全文检索·检索
动能小子ohhh1 天前
DocForge平台的设计与开发--文件上传接口的实现
开发语言·人工智能·python·langchain·ocr·fastapi
满天星83035771 天前
【Qt】信号和槽(二) (自定义信号和槽)
开发语言·数据库·qt