似乎 numpy 数组会自动忽略小数
It seems numpy array automatically ignores decimals
似乎 numpy 数组会自动忽略 delta_x。以下梯度向量的输出是巨大的。下面的渐变代码需要做哪些改动?
import copy
import numpy as np
def numerical_gradient(f, x):
delta_x = 1e-7 # 0.0000001
gradient = np.zeros_like(x) # Return an array of zeros with the same shape
for i in range(x.size):
# constructs a new compound object and then, recursively,
# inserts copies into it of the objects found in the original
_x1 = copy.deepcopy(x)
_x1[i] = x[i] + delta_x
_y1 = f(_x1) # f(x + delta_x)
_x2 = copy.deepcopy(x)
_x2[i] = x[i] - delta_x
_y2 = f(_x2) # f(x - delta_x)
gradient[i] = (_y1 - _y2) / (delta_x*2)
return gradient
def f(x):
y = x[0]**2 + x[1]**2
return y
numerical_gradient(f,np.array([3,3]))
问题出在这一行:
numerical_gradient(f,np.array([3,3]))
这会初始化一个整数数组;使用 deepcopy
和 zeros_like
可以创建更多整数数组。您尝试将 2.999999 分配给 _x2 中的整数数组元素,该元素四舍五入为 2。
如果你这样做:
numerical_gradient(f,np.array([3.0, 3.0]))
输出符合预期。
似乎 numpy 数组会自动忽略 delta_x。以下梯度向量的输出是巨大的。下面的渐变代码需要做哪些改动?
import copy
import numpy as np
def numerical_gradient(f, x):
delta_x = 1e-7 # 0.0000001
gradient = np.zeros_like(x) # Return an array of zeros with the same shape
for i in range(x.size):
# constructs a new compound object and then, recursively,
# inserts copies into it of the objects found in the original
_x1 = copy.deepcopy(x)
_x1[i] = x[i] + delta_x
_y1 = f(_x1) # f(x + delta_x)
_x2 = copy.deepcopy(x)
_x2[i] = x[i] - delta_x
_y2 = f(_x2) # f(x - delta_x)
gradient[i] = (_y1 - _y2) / (delta_x*2)
return gradient
def f(x):
y = x[0]**2 + x[1]**2
return y
numerical_gradient(f,np.array([3,3]))
问题出在这一行:
numerical_gradient(f,np.array([3,3]))
这会初始化一个整数数组;使用 deepcopy
和 zeros_like
可以创建更多整数数组。您尝试将 2.999999 分配给 _x2 中的整数数组元素,该元素四舍五入为 2。
如果你这样做:
numerical_gradient(f,np.array([3.0, 3.0]))
输出符合预期。