linear regression(线性回归) 代码python

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_40279184/article/details/102630453
import random
def data():#生成数据
    x_list=[]
    y_list=[]
    w=int(random.random()*10)
    b=int(random.random()*10)
    for i in range(1000):
       x=random.random()*10
       y=w*x+b
       x_list.append(x)
       y_list.append(y)
    return x_list,y_list

def predict(x,w,b):#预测值
    y=w*x+b
    return y

def gradient(x_batch,y_batch,lr,w,b):#w b 的更新
    loss=0
    ave_w=0
    ave_b=0
    for i in range(len(x_batch)):#一个bacthsize的数据进行更新w,b
        loss+=0.5*(y_batch[i]-predict(x_batch[i],w,b))**2#计算一个batch中的loss总和
        ave_w+=(-y_batch[i]+predict(x_batch[i],w,b))*x_batch[i]#计算一个batch中的w导数总和
        ave_b+=(-y_batch[i]+predict(x_batch[i],w,b))#计算一个batch中的b导数总和
    loss/=len(x_batch)
    ave_w/=len(x_batch)#w平均梯度
    ave_b/=len(x_batch)#b的平均梯度
    w-=lr*ave_w#梯度下降
    b-=lr*ave_b#梯度下降
    return w,b,loss

def train(batch):#训练到一定精度内或者1000次迭代结束 这里采用1000次迭代效果
    x_list,y_list=data()
    lr=1e-4
    w=0
    b=0
    for i in range(1000):#训练1000次
        for j in range(0,1000-batch,batch):
            x_batch=x_list[j:j+batch] #形成batch
            y_batch=x_list[j:j+batch] #形成batch
            w,b,loss=gradient(x_batch,y_batch,lr,w,b)
            print(w,b,loss)

if __name__=="__main__":
    train(25)

猜你喜欢

转载自blog.csdn.net/weixin_40279184/article/details/102630453