您在 v2 中没有相应的代码,或者 tf.keras.layers.Input() 可能就是其中之一。 tf.placeholder 是低级 API。这用于“定义并运行”样式。您使用 tf.placeholder 定义模型。在 v2 中,您应该以“Define-by-Run”的方式编写。
查看来自TensorFlow 2 quickstart for experts的sn-p。
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10)
def call(self, x):
x = self.conv1(x)
x = self.flatten(x)
x = self.d1(x)
return self.d2(x)
# Create an instance of the model
model = MyModel()
另外,请参阅来自Effective TensorFlow 2 的 sn-p。这些类继承自 tf.keras.Model。
class DynamicRNN(tf.keras.Model):
def __init__(self, rnn_cell):
super(DynamicRNN, self).__init__(self)
self.cell = rnn_cell
def call(self, input_data):
# [batch, time, features] -> [time, batch, features]
input_data = tf.transpose(input_data, [1, 0, 2])
outputs = tf.TensorArray(tf.float32, input_data.shape[0])
state = self.cell.zero_state(input_data.shape[1], dtype=tf.float32)
for i in tf.range(input_data.shape[0]):
output, state = self.cell(input_data[i], state)
outputs = outputs.write(i, output)
return tf.transpose(outputs.stack(), [1, 0, 2]), state
您也可以使用 keras api 编写模型。
import tensorflow as tf
x = tf.keras.layers.Input(input_shape)
h = tf.keras.layers.Conv2D(64, (3, 3), padding='SAME')(x)
h = tf.keras.layers.ReLU()(h)
h = tf.keras.layers.Conv2D(64, (3, 3), padding='SAME')(h)
h = tf.keras.layers.ReLU()(h)
h = tf.keras.layers.Conv2D(64, (3, 3), padding='SAME')(h)
h = tf.keras.layers.ReLU()(h)
h = tf.keras.layers.Flatten()(h)
y = tf.keras.layers.Dense(10)(h)
model = tf.keras.Model(x, y)
==== 已编辑 ====
support_set = tf.placeholder(tf.float32, [None, None, img_height, img_width, channels])
query_set = tf.placeholder(tf.float32, [None, None, img_height, img_width, channels])
可以替换为
import tf
support_set = tf.keras.layers.Input(shape=[None, img_height, img_width, channels])
query_set = tf.keras.layers.Input(shape=[None, img_height, img_width, channels])
,其中 Input 不需要明确的 Batch 大小。您可以找到更多信息
https://www.tensorflow.org/guide/keras/functional