我正在尝试通过将我的tensorflow1.13脚本(如下)转换为tensorflow2.0脚本来学习tensorflow2.0的动态。但是,我正在努力做到这一点。
我认为自己挣扎的主要原因是因为我见过训练神经网络的tensorflow2.0的示例,因此它们具有model
和compile
的{{1}}。但是在下面的简单示例中,我没有使用神经网络,所以我看不到如何使该代码适应tensorflow2.0(例如,如何替换会话?)。非常感谢您的帮助,并在此先感谢您。
fit
我看过this(最相关),到目前为止,我提出了以下内容:
data = tf.placeholder(tf.int32)
theta = tf.Variable(np.zeros(100))
p_s = tf.nn.softmax(theta)
loss = tf.reduce_mean(-tf.log(tf.gather(p_s, data)))
train_step = tf.train.AdamOptimizer().minimize(loss)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(10):
for datum in sample_data(): #sample_data() is a list of integer datapoints
_ = sess.run([train_step], feed_dict={data:datum})
print(sess.run(p_s))
但是,以上内容显然无法运行,因为损失函数内的占位符#data = tf.placeholder(tf.int32)
theta = tf.Variable(np.zeros(100))
p_s = tf.nn.softmax(theta)
loss = tf.reduce_mean(-tf.math.log(tf.gather(p_s, **data**)))
optimizer = tf.keras.optimizers.Adam()
for epoch in range(10):
for datum in sample_data():
optimizer.apply_gradients(loss)
print(p_s)
不再存在-但是我不确定如何替换它。 :S
有人吗? 请注意,我没有输入 data
,因为我输入的信息 def forward(x)
未被转换-它直接用于计算丢失。
答案 0 :(得分:2)
我没有使用转换工具(该工具已经存在,但我不喜欢它,因为它只是(或多或少)在API调用前加上tf.compat.v1
并使用了旧的Tensoflow 1.x API)对我有帮助您将代码转换为新版本。
会话消失,占位符也消失。原因?该代码逐行执行-这是Tensorflow急切模式。
要训练模型,您必须正确使用优化器。如果要使用minimize
方法,则在Tensorflowe 2.0中,您必须将函数定义为最小(损失)为Python可调用。
# This is your "model"
theta = tf.Variable(np.zeros(100))
p_s = tf.nn.softmax(theta)
# Define the optimizer
optimizer = tf.keras.optimizers.Adam()
# Define the training loop with the loss inside (because we use the
# .minimnize method that requires a callable with no arguments)
trainable_variables = [theta]
for epoch in range(10):
for datum in sample_data():
# The loss must be callable and return the value to minimize
def loss_fn():
loss = tf.reduce_mean(-tf.math.log(tf.gather(p_s, datum)))
return loss
optimizer.minimize(loss_fn, var_list=trainable_variables)
tf.print("epoch ", epoch, " finished. ps: ", p_s)
免责声明:我尚未测试代码-但它应该可以工作(或者至少可以让您了解如何实现TF 2中要实现的目标)