【问题标题】:Tensorflow: Dynamically Make Letter PredictionTensorflow:动态进行字母预测
【发布时间】:2016-01-10 21:03:21
【问题描述】:

我正在尝试使用 Tensorflow 中的 LSTM 模块在时间 (t-1) 使用单热字母预测作为时间 (t) 下一个状态的输入。我正在做一些事情:

one_hot_dictionary = {0:np.array([1.,0.,0.]),1:np.array([0.,1.,0.]),\
                         2:np.array([0.,0.,1.])}
state = init_state
for time in xrange(sequence_length):
    #run the cell
    output, state = rnn_cell.cell(input,state)

    #transform the output so they are of the one-hot letter dimension
    transformed_val = tf.nn.xw_plus_b(output, W_o, b_o)

    #take the softmax to normalize
    softmax_val = tf.nn.softmax(transformed_val)

    #then get the argmax of these to know what the predicted letter is
    argmax_val = tf.argmax(softmax_val,1)

    #finally, turn these back into one-hots with a number to numpy
    #   array dictionary
    input = [one_hot_dictionary[argmax_val[i]] for i in xrange(batch_size)]

但是,我得到了错误:

input = [one_hot_dictionary[argmax_val[i]] for i in xrange(batch_size)]
KeyError: <tensorflow.python.framework.ops.Tensor object at 0x7f772991ce50>

有没有什么方法可以用我的字典从 argmax 值动态创建这些 one-hot 字母编码?

【问题讨论】:

    标签: python machine-learning tensorflow


    【解决方案1】:

    您可以通过多种方式实现这一目标。

    对您的代码最直接的修改是使用tf.gather() 操作从单位矩阵中选择行,如下所示:

    # Build the matrix [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]].
    identity_matrix = tf.diag(tf.ones([3]))
    
    for ...:
    
      # Compute a vector of predicted letter indices.
      argmax_val = ...
    
      # For each element of `argmax_val`, select the corresponding row
      # from `identity_matrix` and concatenate them into matrix.
      input = tf.gather(identity_matrix, argmax_val)
    

    对于您展示的只有 3 个不同字母的情况,性能可能并不重要。但是,如果字母的数量(以及因此identity_matrix 的大小)比批量大小大得多——您可以通过构建tf.SparseTensor 并使用tf.sparse_tensor_to_dense() 操作构建@987654329 来获得更好的内存效率@。

    【讨论】:

    • 单行修复——我的最爱。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2018-02-04
    • 2016-02-16
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多