梯度法

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import numpy as np

def function(x):
    return x[0]**2+x[1]**2

def numerical_gradient(x,f):
    h = 0.0001
    grad = np.zeros_like(x)
    for index in range(x.size):#x.size()
        temp_x = x[index]
        x[index] = temp_x + h
        fxh1= f(x)
        
        x[index] = temp_x - h
        fxh2 = f(x)
        grad[index] = (fxh1 - fxh2)/(2*h) 
        x[index] = temp_x
    return grad
        
        


        
    
        

def gradient_descent(init_x,y, lr = 0.1, step_num=100):
    x = init_x
    for i in range(step_num):
        grad = numerical_gradient(x, y)
        x = x - lr *grad
    
    return x

if __name__ == "__main__":
    int_x = np.array([-3.0, 4.0])
    c = gradient_descent(int_x,function, lr = 0.01, step_num=100)
    print(c)








 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值