自定义数据集使用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()
相关推荐
TDengine (老段)7 分钟前
基于 TSBS 标准数据集下 TimescaleDB、InfluxDB 与 TDengine 性能对比测试报告
java·大数据·开发语言·数据库·时序数据库·tdengine·iotdb
lgily-122510 分钟前
常用的设计模式详解
java·后端·python·设计模式
鸿蒙布道师21 分钟前
宇树科技安全漏洞揭示智能机器人行业隐忧
运维·网络·科技·安全·机器学习·计算机视觉·机器人
陈苏同学1 小时前
MPC控制器从入门到进阶(小车动态避障变道仿真 - Python)
人工智能·python·机器学习·数学建模·机器人·自动驾驶
mahuifa1 小时前
python实现usb热插拔检测(linux)
linux·服务器·python
rylshe13141 小时前
在scala中sparkSQL连接mysql并添加新数据
开发语言·mysql·scala
小宋加油啊1 小时前
Mac QT水平布局和垂直布局
开发语言·qt·macos
MyhEhud2 小时前
kotlin @JvmStatic注解的作用和使用场景
开发语言·python·kotlin
想睡hhh2 小时前
c++进阶——哈希表的实现
开发语言·数据结构·c++·散列表·哈希
yzx9910132 小时前
支持向量机案例
算法·机器学习·支持向量机