The_Chicken_Lord
The_Chicken_Lord

Reputation: 129

Correct use of sequence_length in dynamic_rnn

I am attempting to design an RNN for sequence classification purposes using tensorflow's dynamic_rnn. My examples can vary in length and through my research I learned that I can pass "sequence_length" as a parameter that designates the length of my examples. However, when I attempt to do so I am getting some peculiar results. In short, the inclusion of the variable prevents my system from learning, thankful I am still able to train when I buffer my sequences with 0s out to the maximum length but I would really like to know what is going wrong for my future work.

The pattern I am trying to learn is simple, if we see 1 by itself we assign it class 1, if we see a 2 anywhere in the sequence it is assigned class 2, and if we see a 1 in both the first and second time slice we should assign class 3.

Here is my test code:

from __future__ import print_function
import tensorflow as tf
import numpy as np

import random

dataset = [[1, 0], [2, 0], [1,2], [1,1]]
labels = [[1,0,0], [0,1,0], [0,1,0], [0,0,1]]

#---------------------------------------------
#define model

# placeholders
data_ph = tf.placeholder("float", [1, None, 1], name="data_placeholder")
len_ph = tf.placeholder("int32", [1], name="seq_len_placeholder")
y_ph = tf.placeholder("float", [1, None, 3], name="y_placeholder")

n_hidden = 10
n_out = len(labels[0])

# variable definition
out_weights=tf.Variable(tf.random_normal([n_hidden,n_out]))
out_bias=tf.Variable(tf.random_normal([n_out]))

# lstm definition
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden, state_is_tuple=True)
state_series, final_state = tf.nn.dynamic_rnn(
                                        cell=lstm_cell, 
                                        inputs=data_ph, 
                                        dtype=tf.float32,
                                        sequence_length=len_ph,
                                        time_major=False
                                        )
out = state_series[:, -1, :]

prediction=tf.nn.softmax(tf.matmul(out,out_weights)+out_bias)

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y_ph))
optimizer=tf.train.AdamOptimizer(learning_rate=1e-3).minimize(loss)

#---------------------------------------------
#run model
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())

#TRAIN
for iteration in range(5000):
    if (iteration%100 == 0):
        print(iteration)
    ind = random.randint(0, len(dataset)-1)

    example = np.reshape(dataset[ind], (1,-1,1))
    label = np.reshape(labels[ind], (1,-1,3))

    vals={data_ph: example,
        len_ph: [len(example)],
        y_ph: label,
    }
    #print(sess.run(state_series, feed_dict=vals))
    sess.run(optimizer, feed_dict=vals)


#TEST
for x in range(len(dataset)):

    example = np.reshape(dataset[x], (1,-1,1))
    label = np.reshape(labels[x], (1,-1,3))
    vals = {data_ph: example,
        len_ph: [len(example)],
        y_ph: label,
    }

    classification = sess.run([prediction, loss], feed_dict=vals)
    print("predicted values: "+str(np.matrix.round(classification[0][0], decimals=2)), "loss: "+str(classification[1]))

When I evaluate the system when I define the sequence_length all of my test examples return the same prediction:

predicted values: [ 0.25999999  0.58999997  0.15000001] loss: 1.19235
predicted values: [ 0.25999999  0.58999997  0.15000001] loss: 0.855842
predicted values: [ 0.25999999  0.58999997  0.15000001] loss: 0.855842
predicted values: [ 0.25999999  0.58999997  0.15000001] loss: 1.30355

Compare these results to when I do not define the sequence length, or when I fix the length at size 2:

predicted values: [ 0.99000001  0.          0.01      ] loss: 0.559447
predicted values: [ 0.  1.  0.] loss: 0.554004
predicted values: [ 0.          0.92000002  0.08      ] loss: 0.603042
predicted values: [ 0.02        0.02        0.95999998] loss: 0.579448

Any input would be appreciated. Thank you

Upvotes: 1

Views: 1695

Answers (1)

Vijay Mariappan
Vijay Mariappan

Reputation: 17201

The sequence_length parameter that you are passing is actually set to 1 and not 2and thats why the network is unable to train.

len(example) returns 1 because its of shape (1,2,1). You can fix it by using len(example.flatten()) and you should see proper output.

Upvotes: 2

Related Questions