【问题标题】:Multiplying a rank 3 tensor with a rank 2 tensor in Tensorflow在 Tensorflow 中将 3 阶张量与 2 阶张量相乘
【发布时间】:2017-05-25 03:50:56
【问题描述】:

给定一个 3 阶张量:

sentence_max_length = 5
batch_size = 3
n_hidden = 10
n_classes = 2
x = tf.constant(np.reshape(np.arange(150),(batch_size,sentence_max_length, n_hidden)), dtype = tf.float32)

还有一个 2 阶张量:

W = tf.constant(np.reshape(np.arange(20), (n_hidden, n_classes)), dtype = tf.float32)

还有一个等级为 1 的偏置张量:

b = tf.constant(np.reshape(np.arange(5), (n_classes), dtype = tf.float32))

我想知道x 的最后两个轴如何通过W 使结果向量Z 的形状为(batch_size, max_length, n_classes),尽管在我刚刚给出的图形创建过程中不知道batch_size此处是用于演示目的的值

所以澄清一下:

Z[0] = tf.matmul(x[0,:,:], W) + b

这样Wb 在所有批次之间共享。这样做的原因是我试图使用tf.dynamic_rnnoutput 从而输出形状为(batch_size, sentence_max_length, n_hidden) 并在output 之上构建另一个层,该层具有共享权重Wb

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    一种方法可能是......

    import tensorflow as tf
    import numpy as np
    from tensorflow.python.layers.core import Dense
    
    sentence_max_length = 5
    batch_size = 3
    n_hidden = 10
    n_classes = 2
    x = tf.constant(np.reshape(np.arange(150),(batch_size,sentence_max_length, n_hidden)), dtype = tf.float32)
    
    linear_layer = Dense(n_classes, use_bias=True) #required projection value
    z = linear_layer(x)
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        res = sess.run(z)
    
    res.shape
    (3, 5, 2)
    

    在内部,密集层创建可训练的 W & b 变量。并且,它使用standard_ops.tensordot 操作将最后一个维度转换为投影值。更多详情请参考源码here

    【讨论】:

      猜你喜欢
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      • 2017-08-21
      相关资源
      最近更新 更多