自定义数据集使用scikit-learn中的包实现线性回归方法对其进行拟合

自定义数据集使用scikit-learn中的包实现线性回归方法对其进行拟合

python 复制代码
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score

# 生成示例数据:y = 3 * X + 4 + 噪声
np.random.seed(42)
X = 2 * np.random.rand(100, 1)  # 100个样本,1个特征
y = 3 * X + 4 + 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(f"Mean Squared Error: {mse}")

r2 = r2_score(y_test, y_pred)
print(f"R²: {r2}")

# 可视化结果
plt.scatter(X_train, y_train, color='blue', label='Training data')
plt.scatter(X_test, y_test, color='green', label='Test data')
plt.plot(X_test, y_pred, color='red', label='Regression line')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()
相关推荐
lsx2024067 小时前
JavaScript 条件语句
开发语言
玄同7657 小时前
Python 自动发送邮件实战:用 QQ/163 邮箱发送大模型生成的内容
开发语言·人工智能·python·深度学习·机器学习·邮件·邮箱
岱宗夫up7 小时前
神经网络(MLP)在时间序列预测中的实践应用
python
我的xiaodoujiao7 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 46--撰写 README项目说明文档文件
python·学习·测试工具·pytest
索荣荣7 小时前
Maven配置文件(pom.xml)终极指南
java·开发语言
Olamyh7 小时前
【手搓 ReAct Agent:告别框架,回归本质】
人工智能·python
钟智强7 小时前
React2Shell:CVE-2025-66478 Next.js 远程执行漏洞深度分析与代码剖析
开发语言·javascript·ecmascript
数研小生7 小时前
Python自然语言处理:NLTK与Gensim库
开发语言·python·自然语言处理
玄同7657 小时前
机器学习中的三大距离度量:欧式距离、曼哈顿距离、切比雪夫距离详解
人工智能·深度学习·神经网络·目标检测·机器学习·自然语言处理·数据挖掘
第七序章7 小时前
【Linux学习笔记】初识Linux —— 理解gcc编译器
linux·运维·服务器·开发语言·人工智能·笔记·学习