关于梯度计算(实际上用数值微分近似计算)

5 篇文章 0 订阅
# coding: utf-8
import numpy as np
import matplotlib.pylab as plt

##数值微分
def numerical_diff(f, x):
    h = 1e-4 # 0.0001
    return (f(x+h) - f(x-h)) / (2*h)


def function_1(x):
    return 0.01*x**2 + 0.1*x

##返回值是一个关于t的函数,以d为斜率 y为截距的函数
def tangent_line(f, x):
    d = numerical_diff(f, x)
    print(d)
    y = f(x) - d*x
    return lambda t1: d*t1 + y

x = np.arange(0.0, 20.0, 0.1)

y = function_1(x)
plt.xlabel("x")
plt.ylabel("f(x)")

#function_1在5上的切线
tf = tangent_line(function_1, 5)
y2 = tf(x)

plt.plot(x, y,"b") ##第一个图,原图0.01*x**2 + 0.1*x
plt.plot(x, y2,"r") ##第二个图,红色,表示5这点以这点数值微分为斜率的斜线
plt.show() ##两个图一起展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值