sklearn 使用make_regression生成回归样本数据及NumPy拟合

1. 介绍

sklearnmake_regression函数能生成回归样本数据。

2. 函数语法

make_regression(n_samples=100, n_features=100, n_informative=10, n_targets=1, bias=0.0, 
                effective_rank=None, tail_strength=0.5, noise=0.0, shuffle=True, coef=False, random_state=None)

3. 参数说明:

n_samples:样本数
n_features:特征数(自变量个数)
n_informative:参与建模特征数
n_targets:因变量个数
noise:噪音
bias:偏差(截距)
coef:是否输出coef标识
random_state:随机状态若为固定值则每次产生的数据都一样

4. 示例

我们先引入make_regression并调用:

from sklearn.datasets import make_regression
X,Y=make_regression(n_samples=10, n_features=1,n_targets=1,noise=1.5,random_state=1)

查看生成的数据长度:

X.shape,Y.shape
((10, 1), (10,))

查看X,Y的值:

X,Y
(array([[-2.3015387 ],
        [-0.7612069 ],
        [-0.52817175],
        [ 1.74481176],
        [ 0.3190391 ],
        [-0.61175641],
        [ 1.62434536],
        [ 0.86540763],
        [-1.07296862],
        [-0.24937038]]),
 array([-8.304904  , -5.45675077, -2.60859753,  0.2395557 ,  3.08770894,
         5.93586217]))
import matplotlib.pyplot as plt
plt.scatter(
    X, #x坐标
    Y, #y坐标
);
plt.show()

在这里插入图片描述

5. 用NumPy实现拟合

Numpy拟合基于最小二乘法

plt.scatter(
    X, #x坐标
    Y, #y坐标
);

import numpy as np
#用一次多项式拟合,相当于线性拟合
z1 = np.polyfit(X.reshape(10), Y, 1)
p1 = np.poly1d(z1)
print (z1)
print (p1)

y = z1[0] * X + z1[1]
plt.plot(X, y,c='red')
plt.show()
[2.84815324 0.2395557 ]
 
2.848 x + 0.2396

在这里插入图片描述

  • 15
    点赞
  • 81
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值