python 回归线性(或多项式)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 回归线性(或多项式)相关的知识,希望对你有一定的参考价值。

def polyfit(namex,x,namey, y, degree):
    import numpy as np
    import matplotlib.pyplot as plt

    # initialize
    results = {}

    # calculate polynomial regression
    coeffs = np.polyfit(x, y, degree)

    # build model (function)
    p = np.poly1d(coeffs)

    # fit values, and mean
    yhat = p(x)                      # or [p(z) for z in x]
    ybar = np.sum(y)/len(y)          # or sum(y)/len(y)
    ssreg = np.sum((yhat-ybar)**2)   # or sum([ (yihat - ybar)**2 for yihat in yhat])
    sstot = np.sum((y - ybar)**2)    # or sum([ (yi - ybar)**2 for yi in y])
 
    # Set regression info 
    results['polynomial'] = coeffs.tolist() # Polynomial Coefficients
    results['R2'] = ssreg / sstot # R**2
    results['correlation'] = np.corrcoef(x,y)[0,1]  # correlation index

    ## PLOT

    # build object
    fig, ax = plt.subplots()
    # plot scatter
    ax.scatter(x,y, color="blue")
    # set title    
    plt.title("REGRESSION grade %s- R**2: %.3f Correlation: %.3f"%(degree,results['R2'],results['correlation']))
    # axes labels
    plt.xlabel(namex)
    plt.ylabel(namey)
    # plot grid axis
    ax.xaxis.grid(True)
    ax.yaxis.grid(True)
    # plot fitted line
    ax.plot(x,yhat, label='fit', color="red")
    # display
    plt.show()

    # return info results
    return results

以上是关于python 回归线性(或多项式)的主要内容,如果未能解决你的问题,请参考以下文章

机器学习多项式回归原理介绍

[Python从零到壹] 十二.机器学习之回归分析万字总结全网首发(线性回归多项式回归逻辑回归)

python实现线性回归原理

如何用Python进行线性回归以及误差分析

用Python开始机器学习(3:数据拟合与广义线性回归)

机器学习线性回归(最小二乘法/梯度下降法)多项式回归logistic回归softmax回归