使用连续输入和离散输出实现生成RNN

问题描述 投票:2回答:1

我目前正在使用生成RNN对序列中的索引进行分类(有点说是某些东西是噪音还是非噪音)。

我的连续输入(即0到1之间的实际值)和我的输出是(0或1)。

例如,如果模型标记1表示大于0.5的数字,否则为0

[.21, .35, .78, .56, ..., .21] => [0, 0, 1, 1, ..., 0]:

   0     0     1     1          0
   ^     ^     ^     ^          ^
   |     |     |     |          |
o->L1  ->L2  ->L3  ->L4 ->... ->L10
   ^     ^     ^     ^          ^
   |     |     |     |          |
   .21  .35   .78   .56   ...  .21

运用

n_steps = 10
n_inputs = 1
n_neurons = 7
X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
y = tf.placeholder(tf.float32, [None, n_steps, n_outputs])

cell = tf.contrib.rnn.BasicRNNCell(num_units=n_neurons, activation=tf.nn.relu)
rnn_outputs, states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)

rnn_outputs变为(?,10,7)形状张量,每10个时间步长可推测7个输出。

以前,我在输出投影包裹rnn_outputs上运行以下片段,以获得每个序列的分类标签。

xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=logits)

loss = tf.reduce_mean(xentropy)

我如何在rnn_outputs上运行类似的东西来获取序列?

特别,

1.我可以从每个步骤获取rnn_output并将其输入softmax吗?

curr_state = rnn_outputs[:,i,:]
logits = tf.layers.dense(states, n_outputs)
xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)

2.我应该使用什么损失函数,是否应该应用于每个序列的每个值? (对于序列i和步骤j,loss = y_{ij} (true) - y_{ij}(predicted))?

我的损失应该是loss = tf.reduce_mean(np.sum(xentropy))吗?

编辑我似乎正在尝试在TensorFlow中实现类似于https://machinelearningmastery.com/develop-bidirectional-lstm-sequence-classification-python-keras/中类似的东西。

在Keras,有一个TimeDistributed功能:

然后,您可以使用TimeDistributed将Dense图层独立应用于10个时间步长中的每一个

我将如何在Tensorflow中实现类似的东西?

machine-learning tensorflow neural-network lstm recurrent-neural-network
1个回答
1
投票

首先,看起来你正在进行seq-to-seq建模。在这种问题中,通常使用编码器 - 解码器架构而不是预测来自相同RNN的序列是个好主意。 Tensorflow有一个关于它的大型教程,名为"Neural Machine Translation (seq2seq) Tutorial",我建议你去看看。

但是,如果n_steps是静态知道的(尽管使用dynamic_rnn),你所询问的架构也是可能的。在这种情况下,可以计算每个单元输出的交叉熵,然后总结所有损失。如果RNN长度也是动态的,那么它可能会更加毛茸茸。这是代码:

n_steps = 2
n_inputs = 3
n_neurons = 5

X = tf.placeholder(dtype=tf.float32, shape=[None, n_steps, n_inputs], name='x')
y = tf.placeholder(dtype=tf.int32, shape=[None, n_steps], name='y')
basic_cell = tf.nn.rnn_cell.BasicRNNCell(num_units=n_neurons)
outputs, states = tf.nn.dynamic_rnn(basic_cell, X, dtype=tf.float32)

# Reshape to make `time` a 0-axis
time_based_outputs = tf.transpose(outputs, [1, 0, 2])
time_based_labels = tf.transpose(y, [1, 0])
losses = []
for i in range(n_steps):
  cell_output = time_based_outputs[i]   # get the output, can do apply further dense layers if needed
  labels = time_based_labels[i]         # get the label (sparse)
  loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=cell_output)
  losses.append(loss)                   # collect all losses
total_loss = tf.reduce_sum(losses)      # compute the total loss
© www.soinside.com 2019 - 2024. All rights reserved.