【问题标题】:what does x[:t:] do in python? <RNN> [closed]x[:t:] 在 python 中做了什么? <RNN> [关闭]
【发布时间】:2017-09-08 18:49:20
【问题描述】:

我一直在研究用于语言模型的 RNN,并在一本书中找到了它与 Tensorflow 的代码。 但我真的不明白x[:t:] 在下面的代码中做了什么..... 我是机器学习的初学者,如果有人知道,请给我一个线索。

=======代码========

def inference(x, n_batch, maxlen=None, n_hidden=None, n_out=None):
    def weight_variable(shape):
        initial = tf.truncated_normal(shape, stddev=0.01)
        return tf.Variable(initial)

    def bias_variable(shape):
        initial = tf.zeros(shape, dtype=tf.float32)
        return tf.Variable(initial)

    cell = tf.contrib.rnn.BasicRNNCell(n_hidden)
    initial_state = cell.zero_state(n_batch, tf.float32)

    state = initial_state
    outputs = []
    with tf.variable_scope('RNN'):
        for t in range(maxlen):
            if t > 0:
                tf.get_variable_scope().reuse_variables()
            (cell_output, state) = cell(x[:, t, :], state)
            outputs.append(cell_output)

    output = outputs[-1]

    V = weight_variable([n_hidden, n_out])
    c = bias_variable([n_out])
    y = tf.matmul(output, V) + c

    return y

【问题讨论】:

  • x[:t:] 还是 x[:, t, :]?
  • 这完全取决于您没有提供的x 的类型。
  • @timgeb -- 基于标签,我敢打赌它几乎肯定是一个张量流张量(它的行为很像一个 numpy 数组)。

标签: python numpy tensorflow


【解决方案1】:

看起来x 是一个 3D 矩阵。在这种情况下,[:,t,:] 在 XZ 平面中提取一个二维矩阵作为立方体的第 tth 切片。

>>> import numpy as np
>>> x = np.arange(27).reshape(3,3,3)
>>> x
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])
>>> x[:,1,:]
array([[ 3,  4,  5],
       [12, 13, 14],
       [21, 22, 23]])

: 表示该轴保持不变。 [:,:,:] 将返回整个矩阵,[1,:,:] 将沿第一个轴提取第二个切片:

>>> x[1,:,:]
array([[ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17]])

这是对应的documentation

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 2021-06-25
    • 2021-09-08
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    相关资源
    最近更新 更多