《Deep Learning from Scratch》·第二集:导数、偏导数

版权声明:本文为博主原创文章,未经博主允许不得转载。若有任何问题,请联系QQ:575925154(加好友时,请备注:CSDN) https://blog.csdn.net/Miracle0_0/article/details/85239291

★★★纯Python★★★:求解函数的导数和偏导数。

导数:

#求解导数
#2018年12月24日
import numpy as np
import matplotlib.pylab as plt

#计算导数
def numerical_diff(f,x):
    h = 1e-4
    return (f(x+h)-f(x-h))/(2*h)
#函数
def function_one(x):
    return 0.01*x*x+0.1*x
#定义域
x = np.arange(0,20,0.01)
#值域
y = function_one(x)

#画图
plt.xlabel('X')
plt.ylabel('f(x)')
plt.plot(x,y)

#求解x=5,x=10处的导数
xOne = 5
xTwo = 10
#斜率
dfx1 = numerical_diff(function_one,xOne)
dfx2 = numerical_diff(function_one,xTwo)
#切线
def line(k,b,x):
    return k*x+b
#求直线的截距
yOne = function_one(xOne)-dfx1*x1
yTwo = function_one(xTwo)-dfx2*x2
#切线的值
y1 = line(dfx1,yOne,x)
y2 = line(dfx2,yTwo,x)

plt.plot(x,y1)
plt.show()
#画图
plt.plot(x,y)
plt.plot(x,y2)
plt.show()


偏导数:

#偏导数
import numpy as np
import matplotlib.pylab as plt
#函数
def functionOne(x):
    return np.sum(x**2)

#计算偏导数
def numerical_gradient(f,x):
    h = 1e-4
    grad = np.zeros_like(x)
    #循环计算每一个x
    for idx in range(x.size):
        tmp_val = x[idx]
        #原理同上的计算导数一样
        x[idx] = tmp_val + h
        fxh1 = f(x)
        
        x[idx] = tmp_val - h
        fxh2 = f(x)
        
        grad[idx] = (fxh1-fxh2)/(2*h)
        x[idx] = tmp_val
    
    return grad

x1 = np.array([3,4.0,5])
y1 = functionOne(x1)
print(y1)

grad1 = numerical_gradient(functionOne,x1)
print(grad1)

x2 = np.array([2.0,10])
grad2 = numerical_gradient(functionOne,x2)
print(grad2)

x3 = np.array([3.0])
grad3 = numerical_gradient(functionOne,x3)
print(grad3)

#Note:此处一定得是浮点型数据,如3.0。若使用整型数据,如3,将会算出一个莫名的其他结果!#

猜你喜欢

转载自blog.csdn.net/Miracle0_0/article/details/85239291