自定义数据集使用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()
相关推荐
cup1116 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0018 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵20 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf21 小时前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent
星云穿梭2 天前
用Python写一个带图形界面的学生管理系统——完整教程
python
哥布林学者2 天前
深度学习进阶(三十一)FlashAttention:IO 感知的精确注意力
机器学习·ai