自定义张量流模型的OOP版本如何工作

时间:2019-03-06 10:02:16

标签: python tensorflow

大家好,我在CS231.n中看到的张量流模型的面向对象实现中有一个问题,这是该模型:

class TwoLayerFC(tf.keras.Model):
    def __init__(self, hidden_size, num_classes):
        super().__init__()        
        initializer = tf.variance_scaling_initializer(scale=2.0)
        self.fc1 = tf.layers.Dense(hidden_size, activation=tf.nn.relu,
                               kernel_initializer=initializer)
        self.fc2 = tf.layers.Dense(num_classes,
                               kernel_initializer=initializer)
    def call(self, x, training=None):
        x = tf.layers.flatten(x)
        x = self.fc1(x)
        x = self.fc2(x)
        return x

这是测试它的功能:

def test_TwoLayerFC():
    model = TwoLayerFC(hidden_size, num_classes)
    with tf.device(device):
        x = tf.zeros((64, input_size))
        scores = model(x)

# Now that our computational graph has been defined we can run the graph
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    scores_np = sess.run(scores)
    print(scores_np.shape)

我的问题是如何用输入x调用模型并生成分数,我的意思是这不是调用对象函数的Python方法,应该是:

model.call(x)

或者call方法应该是魔术方法,我的意思是:

def __call__(self, x, training=None)

0 个答案:

没有答案