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

相关推荐
隔山打牛牛2 分钟前
Spring的两大核心
java·开发语言
皮卡蛋炒饭.3 分钟前
Linux进程信号
开发语言·c++
kishu_iOS&AI3 分钟前
机器学习 —— 总结
人工智能·python·机器学习·线性回归
API快乐传递者5 分钟前
Python 爬虫获取 1688 商品详情 API 接口实战指南
java·前端·python
疯狂成瘾者6 分钟前
LangChain Middleware 技术解析:从“插槽机制”到 Agent 运行时控制
数据库·python·langchain
报错小能手9 分钟前
ios开发方向——swift并发进阶核心 Task、Actor、await 详解
开发语言·学习·ios·swift
小辉同志15 分钟前
208. 实现 Trie (前缀树)
开发语言·c++·leetcode·图论
A-刘晨阳15 分钟前
当数据学会“秒回“:工业4.0时代的实时计算革命
开发语言·数据库·perl
沐知全栈开发17 分钟前
Lua 基本语法
开发语言
Where-17 分钟前
LangChain、LangGraph入门
python·langchain·langgraph