白话梯度下降

Homework2

1. Generate n = 2,000 points uniformly at random in the two-dimensional unit square. Which point do you expect the centroid to be?

答: 因为有2000个点,所以质点应该是(0.5,0.5)

2. What objective does the centroid of the points optimize?

答: 优化的目标就是到各个点的欧式距离之和最小,也就是说最小化f(x):\min f\left( x,y\right) = \min \sum _{i} \sqrt{(x-x_i)^2+(y-y_i)^2}

3. Apply gradient descent (GD) to find the centroid.

答:

  1. 损失函数为f(x),对f(x)x,y的偏导后可得:
    \frac{df}{dx} = \sum _{i} \frac{x-x_i}{\sqrt{(x-x_i)^2+(y-y_i)^2}}
    \frac{df}{dy} = \sum _{i} \frac{y-y_i}{\sqrt{(x-x_i)^2+(y-y_i)^2}}
def cal_grad(point,all_point):
    #通过算偏导数得出x,y的梯度
    grad_x = sum(-(all_point[:,0]-point[0])/(sum((all_point-point)**2,1)**0.5))
    grad_y = sum(-(all_point[:,1]-point[1])/(sum((all_point-point)**2,1)**0.5))
    return np.array([grad_x/n,grad_y/n])
  1. 设置超参数:学习率与阈值
  2. 进行参数更新
def update(point,grad):
    point = point - lr*grad
    return point
  1. 进行迭代
# 梯度下降gd
start_point = rand(2)
pre_loss = 0
point_hist=start_point
for i in range(max_iter):
    grad = cal_grad(start_point,data)
    start_point = update(start_point,grad)
    point_hist = np.vstack((point_hist,start_point))
    loss = cal_loss(start_point,data)
    if abs(pre_loss - loss) < threshold:
        #loss变化小于阈值后停止
        break
    pre_loss = loss    
# print(point_hist)
pylab.plot(point_hist[:,0],point_hist[:,1],'r-')
pylab.plot(data[:,0],data[:,1],'g.')

可视化后得到如下结果,红色为收敛路径:

image

4.Apply stochastic gradient descent (SGD) to find the centroid. Can you say in simple words, what the algorithm is doing?

答:简单的说就是每次只通过一个样本算出梯度,然后进行更新,这样减少了很多计算量.

具体实现很简单,从样本中抽出一个传入cal_grad函数就好了.

路径如下,可以看出是有很大震荡的,并且对学习率/阈值的要求较严格,否则可能会造成不收敛:

image
import pandas as pd
import numpy as np
import pylab
from scipy import *
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
n = 2000
data = rand(n,2)
# pylab.plot(data[:,0],data[:,1],'g.')
start_point = rand(2)
lr = 0.01
threshold = 1e-6
max_iter = 20000
def cal_grad(point,all_point):
    #通过算偏导数得出x,y的梯度
    grad_x = sum(-(all_point[:,0]-point[0])/(sum((all_point-point)**2,1)**0.5))
    grad_y = sum(-(all_point[:,1]-point[1])/(sum((all_point-point)**2,1)**0.5))
    g = (grad_x ** 2 + grad_y ** 2) ** 0.5 #归一化
    return np.array([grad_x/g,grad_y/g])

cal_grad(start_point,data)

def update(point,grad):
    point = point - lr*grad
    return point

def cal_loss(point,all_point):
    return sum(sum((all_point-point)**2,1)**0.5)
# 梯度下降gd
start_point = rand(2)
pre_loss = 0
point_hist=start_point
for i in range(max_iter):
    grad = cal_grad(start_point,data)
    start_point = update(start_point,grad)
    point_hist = np.vstack((point_hist,start_point))
    loss = cal_loss(start_point,data)
    if abs(pre_loss - loss) < threshold:
        #loss变化小于阈值后停止
        break
    pre_loss = loss    
# print(point_hist)
pylab.plot(point_hist[:,0],point_hist[:,1],'r-')
pylab.plot(data[:,0],data[:,1],'g.')
# pylab.show()
[<matplotlib.lines.Line2D at 0x119e27da0>]
image
# 随机梯度下降SGD
start_point = np.array([1,0])
pre_loss = 0
point_hist=start_point
lr = 0.02
count = 0
max_iter = 100000
threshold = 1e-4
for i in range(max_iter):
    random_choice = np.random.randint(0,2000)
    grad = cal_grad(start_point,array([data[random_choice]]))
    start_point = update(start_point,grad)
    point_hist = np.vstack((point_hist,start_point))
    loss = cal_loss(start_point,data)
    if abs(pre_loss - loss) < threshold:
        #loss变化小于阈值后停止
        count +=1
        if count > 1:
            break
    else:
        count = 0
    if loss-pre_loss > 0.1:
        lr = lr *0.8
    pre_loss = loss    
# print(len(point_hist))
pylab.plot(point_hist[:,0],point_hist[:,1],'r-')
pylab.plot(data[:,0],data[:,1],'g.')
start_point
array([0.5021768 , 0.48251419])
image
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容