二阶线性回归简单代码

#!/usr/bin/python2
# -*- coding:utf-8 -*-

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# from sklearn.metrics import r2_score
# import statsmodels.api as sm

data = pd.read_csv("Advertising.csv")

def scatter():

    print (data.head())
    m=15
    # data.drop(['Unnamed: 0'], axis=1)
    area=(30*np.random.rand(m))**2
    colors=np.random.rand(m)
    plt.figure(figsize=(16, 8))
    plt.scatter(data['TV'], data['sales'], s=area,c="green",alpha=0.5)
    plt.xlabel("Money spent on TV ads ($)")
    plt.ylabel("Sales ($)")
    plt.show()

def Linereg():
    X = data['TV'].values.reshape(-1,1)
    y = data['sales'].values.reshape(-1,1)
    reg = LinearRegression()
    reg.fit(X, y)
    print("The linear model is: Y = {:.5} + {:.5}X".format(reg.intercept_[0], reg.coef_[0][0]))
    m=15
    # data.drop(['Unnamed: 0'], axis=1)
    area=(30*np.random.rand(m))**2
    colors=np.random.rand(m)
    predictions = reg.predict(X)
    plt.figure(figsize=(16, 8))
    plt.scatter(data['TV'], data['sales'], s=area,c="green",alpha=0.5)
    plt.plot( data['TV'], predictions, c='red', linewidth=2)
    plt.xlabel("Money spent on TV ads ($)")
    plt.ylabel("Sales ($)")
    plt.show()

if __name__ == '__main__':
    scatter()

    Linereg()

散点图:
在这里插入图片描述

拟合回归:
在这里插入图片描述

scatter()画散点图函数
源码:

def scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None,
            vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None,
            hold=None, data=None, **kwargs):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.scatter(x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
                         vmin=vmin, vmax=vmax, alpha=alpha,
                         linewidths=linewidths, verts=verts,
                         edgecolors=edgecolors, data=data, **kwargs)
    finally:
        ax._hold = washold
    sci(ret)
    return ret

参数说明:

x, y : 相同长度的数组,数组大小(n,),也就是绘制散点图的数据;

s:绘制点的大小,可以是实数或大小为(n,)的数组, 可选的参数 ;

c:绘制点颜色, 默认是蓝色’b’ , 可选的参数 ;

marker:表示的是标记的样式,默认的是’o’ , 可选的参数 如“x”;

cmap:当c是一个浮点数数组的时候才使用, 可选的参数 ;

norm:将数据亮度转化到0-1之间,只有c是一个浮点数的数组的时候才使用, 可选的参数 ;

vmin , vmax:实数,当norm存在的时候忽略。用来进行亮度数据的归一化 , 可选的参数 ;

alpha:实数,0-1之间, 可选的参数 ,点的透明度?;

linewidths:标记点的长度, 可选的参数 ;

sklearn的LinearRegression()

最小二乘法线性回归:sklearn.linear_model.LinearRegression(fit_intercept=True, normalize=False,copy_X=True, n_jobs=1)
参数:
1、fit_intercept:boolean,optional,default True。是否计算截距,默认为计算。如果使用中心化的数据,可以考虑设置为False,
不考虑截距。注意这里是考虑,一般还是要考虑截距。
2、normalize:boolean,optional,default False。标准化开关,默认关闭;该参数在fit_intercept设置为False时自动忽略。如果为
True,回归会标准化输入参数:(X-X均值)/||X||,当然啦,在这里还是建议将标准化的工作放在训练模型之前;若为False,在训练
模型前,可使用sklearn.preprocessing.StandardScaler进行标准化处理。
3、copy_X:boolean,optional,default True。默认为True, 否则X会被改写。
4、n_jobs:int,optional,default 1int。默认为1.当-1时默认使用全部CPUs ??(这个参数有待尝试)。
属性:
coef_:array,shape(n_features, ) or (n_targets, n_features)。回归系数(斜率)。
intercept_: 截距
方法:
1、fit(X,y,sample_weight=None)
X:array, 稀疏矩阵 [n_samples,n_features]
y:array [n_samples, n_targets]
sample_weight:array [n_samples],每条测试数据的权重,同样以矩阵方式传入(在版本0.17后添加了sample_weight)。
2、predict(x):预测方法,将返回值y_pred
3、get_params(deep=True): 返回对regressor 的设置值
4、score(X,y,sample_weight=None):评分函数,将返回一个小于1的得分,可能会小于0

简单案例:


# 样本数据集,第一列为x,第二列为y,在x和y之间建立回归模型
data=[
    [0.067732,3.176513],[0.427810,3.816464],[0.995731,4.550095],[0.738336,4.256571],[0.981083,4.560815],
    [0.526171,3.929515],[0.378887,3.526170],[0.033859,3.156393],[0.132791,3.110301],[0.138306,3.149813],
    [0.247809,3.476346],[0.648270,4.119688],[0.731209,4.282233],[0.236833,3.486582],[0.969788,4.655492],
    [0.607492,3.965162],[0.358622,3.514900],[0.147846,3.125947],[0.637820,4.094115],[0.230372,3.476039],
    [0.070237,3.210610],[0.067154,3.190612],[0.925577,4.631504],[0.717733,4.295890],[0.015371,3.085028],
    [0.335070,3.448080],[0.040486,3.167440],[0.212575,3.364266],[0.617218,3.993482],[0.541196,3.891471]
]
 
#生成X和y矩阵
dataMat = np.array(data)
X = dataMat[:,0:1]   # 变量x
y = dataMat[:,1]   #变量y
 
# ========线性回归========
model = LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
model.fit(X, y)   # 线性回归建模
print('系数矩阵:\n',model.coef_)
print('线性回归模型:\n',model)
# 使用模型预测
predicted = model.predict(X)
 
# 绘制散点图 参数:x横轴 y纵轴
plt.scatter(X, y, marker='x')
plt.plot(X, predicted,c='r')
 
# 绘制x轴和y轴坐标
plt.xlabel("x")
plt.ylabel("y")
 
# 显示图形

————————————————
版权声明:本文为CSDN博主「ls秦」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38328378/article/details/80775351

改进视图呈现方式:

竖放:


def Fig1():
    fig = plt.figure()
    #在plt中,figure是整个画布,想要在画布上绘制多个子图axes,用fig.add_subplot()
    
    ax1 = fig.add_subplot(3,1,1) # 画2行1列个图形的第1个
    ax2 = fig.add_subplot(3,1,2) # 画2行1列个图形的第2个
    ax3 = fig.add_subplot(3,1,3)
    plt.subplots_adjust(hspace=0.2,wspace=0.1,left=0.2,bottom=0.05, right=0.8,top=0.95)

    TVpredictions = TVLinereg()
    ax1.scatter(data['TV'], data['sales'],s=50,c="green",label='TV')
    ax1.plot( data['TV'], TVpredictions, c='red', linewidth=2)
    ax1.set_xlabel("Money spent on TV ads ($)")
    ax1.set_ylabel("Sales ($)")
    ax1.legend(loc='best')

    Radiopredictions = RadioLinereg()
    ax2.scatter(data['radio'], data['sales'],s=50,c="orange",label='Radio')
    ax2.plot( data['radio'], Radiopredictions, c='red', linewidth=2)
    ax2.set_xlabel("Money spent on radio ads ($)")
    ax2.set_ylabel("Sales ($)")
    ax2.legend(loc='best')

    Paperpredictions =  PaperLinereg()
    ax3.scatter(data['newspaper'], data['sales'],s=50,c="blue",label='NewsPaper')
    ax3.plot( data['newspaper'], Paperpredictions, c='red', linewidth=2)
    ax3.set_xlabel("Money spent on newspaper ads ($)")
    ax3.set_ylabel("Sales ($)")
    ax3.legend(loc='best')

    plt.show() 

输出:
在这里插入图片描述
放在一张画布:

def Fig2():
    fig = plt.figure()
    #在plt中,figure是整个画布,想要在画布上绘制多个子图axes,用fig.add_subplot()
    
    # plt = fig.add_subplot(3,1,1) # 画2行1列个图形的第1个
    # plt = fig.add_subplot(3,1,2) # 画2行1列个图形的第2个
    # plt = fig.add_subplot(3,1,3)
    # plt.subplots_adjust(hspace=0.2,wspace=0.1,left=0.2,bottom=0.05, right=0.8,top=0.95)

    TVpredictions = TVLinereg()
    plt.scatter(data['TV'], data['sales'],s=50,c="green",marker="o",label='TV')
    plt.plot( data['TV'], TVpredictions, c='green',label='TV', linewidth=2)

    Radiopredictions = RadioLinereg()
    plt.scatter(data['radio'], data['sales'],s=50,c="orange",marker="x",label='Radio')
    plt.plot( data['radio'], Radiopredictions, c='orange',label='Radio', linewidth=2)

    Paperpredictions =  PaperLinereg()
    plt.scatter(data['newspaper'], data['sales'],s=50,c="blue",marker="*",label='NewsPaper')
    plt.plot( data['newspaper'], Paperpredictions, c='blue',label='NewsPaper', linewidth=2)
    plt.xlabel("Money spent on ads ($)")
    plt.ylabel("Sales ($)")
    plt.legend(loc='best')

    plt.show() 

输出:
在这里插入图片描述

如果你是这个公司的老板,你收到一份这样的报告,你知道如何决策了吧

遇到的问题总结

1.添加子图时,plt = fig.add_subplot(3,1,1)第一个参数是你要布局几行,第二个参数相当于列,第三个参数是第几个,如我上面的例子就传参1,2,3,
2.没有axes时,添加X轴y轴lable用函数plt.xlable()/plt.ylable();如果有子图axes,则需要用axes.set_xlable()/axes.set_ylable(),用错会panic,‘AxesSubplot’ object has no attribute ‘xlabel’

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
牛顿法是一种数值优化方法,可以用于求解非线性回归。它的基本思想是利用二阶泰勒展开来近似目标函数,然后求解近似函数的极值点。在非线性回归问题中,目标函数通常是似然函数或者残差平方和,其中包含了未知参数。通过牛顿法求解非线性回归,可以得到最优的参数估计。 下面是一个使用牛顿法求解非线性回归的示例代码: ```python import numpy as np # 定义目标函数,这里使用的是一个简单的非线性回归模型 def f(x, a, b): return a * x + b * x ** 2 # 定义求导函数,这里使用的是目标函数的一阶和二阶导数 def df(x, a, b): return np.array([a + 2 * b * x, 2 * b * np.ones_like(x)]) # 定义牛顿法求解函数 def newton_method(x0, f, df, max_iter=100, tol=1e-6): x = x0 for i in range(max_iter): # 计算当前点的一阶和二阶导数 grad = df(x[0], *x[1:]) hess = np.diag(df(x[0], *x[1:])) # 计算牛顿方向和步长 d = -np.linalg.solve(hess, grad) alpha = 1.0 # 进行线搜索,找到最优的步长 while f(x[0] + alpha * d[0], *x[1:]) > f(x[0], *x[1:]) + alpha * 0.5 * grad.dot(d): alpha *= 0.5 # 更新参数估计值 x_new = x + np.hstack((alpha * d[0], d[1:])) # 判断是否满足收敛条件 if np.linalg.norm(x_new - x) < tol: break x = x_new return x # 生成样本数据 np.random.seed(0) x = np.linspace(-5, 5, 100) y = f(x, 2, 3) + np.random.normal(scale=0.5, size=100) # 利用牛顿法求解非线性回归问题 x0 = np.array([0, 1, 1]) params = newton_method(x0, lambda a, b, c: np.sum((y - f(x, a, b)) ** 2), lambda a, b, c: np.array([2 * np.sum(y - f(x, a, b)), -2 * np.sum((y - f(x, a, b)) * x), -2 * np.sum((y - f(x, a, b)) * x ** 2)])) print(params) ``` 在上述代码中,首先定义了目标函数 `f` 和求导函数 `df`。然后,定义了牛顿法求解函数 `newton_method`,其中包括了计算一阶和二阶导数、计算牛顿方向和步长、进行线搜索、更新参数值等步骤。最后,利用样本数据和牛顿法求解函数,得到了最优的参数估计。 需要注意的是,牛顿法有可能会出现收敛不稳定的情况,因此在实际应用中需要进行一定的调参和验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值