首页 > 解决方案 > 任何新版本的 tf.placeholder?

问题描述

我在使用 时遇到问题tf.placeholder,因为它已在新版本的 TensorFlow 2.0 中被删除。

我现在应该怎么做才能使用这个功能?

标签: tensorflowplaceholdertensorflow2.0

解决方案


您只需将数据直接作为输入应用到图层。例如:

import tensorflow as tf
import numpy as np

x_train = np.random.normal(size=(3, 2))
astensor = tf.convert_to_tensor(x_train)
logits = tf.keras.layers.Dense(2)(astensor)
print(logits.numpy())
# [[ 0.21247671  1.97068912]
#  [-0.17184766 -1.61471399]
#  [-0.03291694 -0.71419362]]

上面代码的TF1.x等价物是:

import tensorflow as tf
import numpy as np

input_ = np.random.normal(size=(3, 2))
x = tf.placeholder(tf.float32, shape=(None, 2))
logits = tf.keras.layers.Dense(2)(x)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(logits, feed_dict={x:input_}))
# [[-0.17604277  1.8991518 ]
#  [-1.5802367  -0.7124136 ]
#  [-0.5170298   3.2034855 ]]

推荐阅读