PYSpark

 画图

#SGD(Stochastic gradientdescent)随机梯度下降法:每次迭代使用一组样本
#-*- coding: utf-8 -*-  
import random  
#用y = Θ1*x1 + Θ2*x2来拟合下面的输入和输出  
#input1  1   2   5   4  
#input2  4   5   1   2  
#output  19  26  19  20  
input_x = [[1,4], [2,5], [5,1], [4,2]]  #输入  
y = [19,26,19,20]       #输出  
theta = [1,1]           #θ参数初始化  
loss = 10               #loss先定义一个数,为了进入循环迭代  
step_size = 0.01        #步长  
eps =0.0001             #精度要求  
max_iters = 10000       #最大迭代次数  
error =0                #损失值  
iter_count = 0          #当前迭代次数  
   
   
while( loss > eps and iter_count < max_iters):  #迭代条件  
    loss = 0  
    #这里每次批量选取的是2组样本进行更新,另一个点是随机点+1的相邻点  
    i = random.randint(0,3)     #随机抽取一组样本  
    j = (i+1)%4                 #抽取另一组样本,j=i+1  
    pred_y0 = theta[0]*input_x[i][0]+theta[1]*input_x[i][1]  #预测值1  
    pred_y1 = theta[0]*input_x[j][0]+theta[1]*input_x[j][1]  #预测值2  
    theta[0] = theta[0] - step_size * (1/2) * ((pred_y0 - y[i]) * input_x[i][0]+(pred_y1 - y[j]) * input_x[j][0])  #对应5式  
    theta[1] = theta[1] - step_size * (1/2) * ((pred_y0 - y[i]) * input_x[i][1]+(pred_y1 - y[j]) * input_x[j][1])  #对应5式  
    for i in range (3):  
        pred_y = theta[0]*input_x[i][0]+theta[1]*input_x[i][1]  #总预测值  
        error = (1/(2*2))*(pred_y - y[i])**2                    #损失值  
        loss = loss + error       #总损失值  
    iter_count += 1  
    print ('iters_count', iter_count)  
   
print ('theta: ',theta )  
print ('final loss: ', loss)  
print ('iters: ', iter_count) 
http://hbasefly.com/2017/03/19/sparksql-basic-join/?hmxure=1utjw3

https://www.cnblogs.com/zhaoyibing/p/9051428.html

https://www.cnblogs.com/zhaoyibing/p/9628759.html
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值