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

代码

python 复制代码
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# 自定义数据集
data = np.array([
    [0.8, 1.0],
    [1.7, 0.9],
    [2.7, 2.4],
    [3.2, 2.9],
    [3.7, 2.8],
    [4.2, 3.8],
    [4.2, 2.7]
])

# 提取特征(X)和目标值(y)
X = data[:, 0].reshape(-1, 1)  # 特征值(二维数组)
y = data[:, 1]  # 目标值

# 创建并训练线性回归模型
model = LinearRegression()
model.fit(X, y)

# 生成预测值
y_pred = model.predict(X)

# 可视化数据和拟合结果

plt.figure('show figure')
plt.xlim(0, 5)
plt.ylim(0, 5)

# 绘制原始数据点
plt.scatter(X, y, color='blue')

# 绘制回归直线
plt.plot(X, y_pred, color='red')

# 添加标题和标签
plt.xlabel("X")
plt.ylabel("y")

# 显示图例
plt.legend()

# 显示图形
plt.show()

实验结果

相关推荐
Warson_L1 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅1 天前
海天线算法的前世今生
python·计算机视觉
韩师傅1 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L1 天前
LangGraph的MessageState and HumanMessage
python
韩师傅1 天前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L1 天前
python的类&继承
python
Warson_L1 天前
类型标注/type annotation
python
ThreeS1 天前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵1 天前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏