当取梯度时,张量流为2.0;错误表示没有为任何变量提供梯度 嘿,我从张量流的旧版本转换,考虑一个简单的线性回归模型,我们< /P> import tensorflow as tf import tensorflow_probability as tfp from tensorflow import keras import numpy as np import matplotlib.pyplot as plt dtype = "float32" # define my model here model = keras.Sequential([ keras.layers.Dense(2,name='l1'), keras.layers.Dense(128, activation='relu',name='l2'), keras.layers.Dense(1) ]) # create the train data x_train = np.asarray([[2,3],[6,7],[1,5],[4,6],[10,-1],[0,0],[5,6], [8,9],[4.5,6.2],[1,1],[0.3,0.2]]).astype(dtype) # true weights and bias w_train = np.asarray([[2,1]]).astype(dtype) b = np.asarray([[-3]]).astype(dtype) # create response y_train = np.dot(x_train, w_train.T) + b # do prediction and define loss predictions = model(x_train) loss = lambda: tf.keras.losses.mse(predictions, y_train) optimizer = tf.keras.optimizers.Adam() opt_op = optimizer.minimize(loss,var_list = model.trainable_weights)

当取梯度时,张量流为2.0;错误表示没有为任何变量提供梯度 嘿,我从张量流的旧版本转换,考虑一个简单的线性回归模型,我们< /P> import tensorflow as tf import tensorflow_probability as tfp from tensorflow import keras import numpy as np import matplotlib.pyplot as plt dtype = "float32" # define my model here model = keras.Sequential([ keras.layers.Dense(2,name='l1'), keras.layers.Dense(128, activation='relu',name='l2'), keras.layers.Dense(1) ]) # create the train data x_train = np.asarray([[2,3],[6,7],[1,5],[4,6],[10,-1],[0,0],[5,6], [8,9],[4.5,6.2],[1,1],[0.3,0.2]]).astype(dtype) # true weights and bias w_train = np.asarray([[2,1]]).astype(dtype) b = np.asarray([[-3]]).astype(dtype) # create response y_train = np.dot(x_train, w_train.T) + b # do prediction and define loss predictions = model(x_train) loss = lambda: tf.keras.losses.mse(predictions, y_train) optimizer = tf.keras.optimizers.Adam() opt_op = optimizer.minimize(loss,var_list = model.trainable_weights),tensorflow,Tensorflow,现在它引发了错误状态ValueError:没有为任何变量提供梯度:['sequential_1/l1/kernel:0'、'sequential_1/l1/bias:0'、'sequential_1/l2/bias:0'、'sequential_1/dense_1/kernel:0'、'sequential_1/dense_1/bias:0'. 这太奇怪了,因为我把神经网络作为可训练变量,它在正向过程中传递。我看了教程,但看起来所有新的实现都需要手动调用梯度函数并将梯度应用到优化器 旧的方法,通

现在它引发了错误状态
ValueError:没有为任何变量提供梯度:['sequential_1/l1/kernel:0'、'sequential_1/l1/bias:0'、'sequential_1/l2/bias:0'、'sequential_1/dense_1/kernel:0'、'sequential_1/dense_1/bias:0'.

这太奇怪了,因为我把神经网络作为可训练变量,它在正向过程中传递。我看了教程,但看起来所有新的实现都需要手动调用梯度函数并将梯度应用到优化器


旧的方法,通过定义操作可以自动处理此问题。我想继续用这种方式。有什么帮助吗?

在tensorflow 2.0中,您需要使用
tf.GradientTape
上下文来计算梯度,然后对模型的变量应用梯度

将tf.GradientTape()作为t:
#做预测和定义损失吗
预测=模型(x_列车)
损失=tf.keras.loss.mse(预测,y_列)
梯度=t.梯度(损失、模型、可训练变量)
optimizer=tf.keras.optimizers.Adam()
优化器。应用_梯度(zip(梯度、模型、可训练_变量))

在tensorflow 2.0中,您需要使用
tf.GradientTape
上下文来计算梯度,然后对模型的变量应用梯度

将tf.GradientTape()作为t:
#做预测和定义损失吗
预测=模型(x_列车)
损失=tf.keras.loss.mse(预测,y_列)
梯度=t.梯度(损失、模型、可训练变量)
optimizer=tf.keras.optimizers.Adam()
优化器。应用_梯度(zip(梯度、模型、可训练_变量))