深度学习之导数和偏导数

问题:给你一个可导函数,求该函数在某处的导数和偏导数

例1:求 y = 0.01x**2+0.1x 在 x = 5 和 x = 10处的导数

# 定义导数函数
def numerical_diff(f, x):
    h = 1e-4
    return (f(x + h) - f(x - h)) / (2 * h)

# 计算 y = 0.01x**2+0.1x 在 x = 5 和 x = 10处的导数
def function_1(x):
    return 0.01*x**2+0.1*x

print(numerical_diff(function_1, 5))
print(numerical_diff(function_1, 10))
"""
输出结果为
0.1999999999990898
0.2999999999986347
"""

例2:计算y = x0**2+x1**2 在x0=3, x1 = 4处x0的偏导数

# 计算x0的偏导数时,把x1看成常量,即x1=4
def function_tmp1(x0):
    return x0**2 + 4**2
print(numerical_diff(function_tmp1, 3))
# 输出结果为: 6.00000000000378
#计算x1的偏导数时,把x0看成常量,即x0=3
def function_tmp2(x1):
    return  3 ** 2 + x1 ** 2
print(numerical_diff(function_tmp2, 4))
# 输出结果为:7.999999999999119
  • 绘制二元函数的图像

    # 绘制 0.05*x1**2 + x2**2二元图像
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    fig = plt.figure()
    ax = Axes3D(fig)
    x = np.arange(0, 10, 0.01) # x轴坐标
    y = np.arange(0, 10, 0.01) # y轴坐标
    X, Y = np.meshgrid(x, y) # 网格化
    Z = 0.05 * X ** 2 + Y ** 2 # z轴坐标
    ax.plot_surface(X, Y, Z) # 绘制图形
    plt.xlabel("x")
    plt.ylabel("y")
    plt.show()
    
posted @ 2022-10-11 14:51  Reina  阅读(147)  评论(0)    收藏  举报