Simple LinearRegression

以下包含python实现和sklearn实现方法: 

#---------------Simple Linear Regression------------------------------
import numpy as np
def predict(x,y):
    n = len(x)
    b1 =0
    b2 =0
    for i in range(n):
        b1 = (x[i]-np.mean(x))*(y[i]-np.mean(y))+b1 #np.mean()返回矩阵均值
        b2 = (x[i]-np.mean(x))**2+b2
    b1 = b1/b2
    b0 = np.mean(y)-b1*np.mean(x)
    print ('y =',b1,'x','+',b0)
x = [1,3,2,1,3]
y = [14,24,18,17,27]
predict(x,y)

# x = np.array([[1,2],
              # [3,3],
              # [1,2]])
# print (np.mean(x,axis=0),
       # np.cumsum(x),#返回list包含所有元素的累计和
       # np.cumprod(x)#返回list包含所有元素的累积)

#---------------也可用sklearn实现------------------
from sklearn import linear_model
#LinearRegression也可进行单一变量线性回归模型的建立
regr = linear_model.LinearRegression()
#传入参数需要用到list[list]形式
x = [[1],[3],[2],[1],[3]]
y = [14,24,18,17,27]
regr.fit(x,y)
print (regr.coef_,regr.intercept_)

#----------------------numpy可以直接实现-------------------------
import numpy as np
x = [1,3,2,1,3]
y = [14,24,18,17,27]
coef = np.polyfit(x,y,1)  #返回系数
print (coef)

       

 

转载于:https://my.oschina.net/u/3786144/blog/1802315

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值