Python 变量有';无';梯度
我目前正在使用TensorFlow 1.14版 在下面的代码中,我试图创建一个虚拟模型,该模型接受2个输入并提供两个输出,所有权重设置为1,偏差设置为0(单层感知器)。我定义了一个自定义损失函数,用于计算输入层wrt输出层的雅可比矩阵Python 变量有';无';梯度,python,python-3.x,tensorflow,machine-learning,keras,Python,Python 3.x,Tensorflow,Machine Learning,Keras,我目前正在使用TensorFlow 1.14版 在下面的代码中,我试图创建一个虚拟模型,该模型接受2个输入并提供两个输出,所有权重设置为1,偏差设置为0(单层感知器)。我定义了一个自定义损失函数,用于计算输入层wrt输出层的雅可比矩阵 def my_loss(y_pred, y_true): jacobian_tf = jacobian_tensorflow3(sim.output, sim.input) loss = tf.abs(tf.linalg.det(jacobian_
def my_loss(y_pred, y_true):
jacobian_tf = jacobian_tensorflow3(sim.output, sim.input)
loss = tf.abs(tf.linalg.det(jacobian_tf))
return K.mean(loss)
def jacobian_tensorflow3(x,y, verbose=False):
jacobian_matrix = []
it = tqdm(range(ndim)) if verbose else range(ndim)
for o in it:
grad_func = tf.gradients(x[:,o], y)
jacobian_matrix.append(grad_func[0])
jacobian_matrix = tf.stack(jacobian_matrix)
jacobian_matrix1 = tf.transpose(jacobian_matrix, perm=[1,0,2])
return jacobian_matrix1
sim = Sequential()
sim.add(Dense(2, kernel_initializer='ones', bias_initializer='zeros', activation='linear', input_dim=2))
sim.compile(optimizer='adam', loss=my_loss)
sim.fit(B, np.random.random(B.shape), batch_size=100, epochs=2)
虽然该模型能够给出雅可比矩阵的结果,并且在编译方面也没有问题,但当我运行sim.fit时,我得到以下错误:
ValueError: Variable <tf.Variable 'dense_14/bias:0' shape=(2,) dtype=float32> has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.
ValueError:变量的梯度为'None'。请确保所有操作都定义了梯度(即可微)。无梯度的普通操作:K.argmax、K.round、K.eval。
我在这一步上被困了很长时间,我无法继续前进。任何帮助/建议都是有益的