2017-11-14 12 views
0

입력 번호 목록에 대한 텐서 흐름 LSTM 회귀 모델을 구현하려고합니다. 예 :텐서 흐름을 사용하는 LSTM 회귀 모델 구현

input_data = [1, 2, 3, 4, 5] 
time_steps = 2 
    -> X == [[1, 2], [2, 3], [3, 4]] 
    -> y == [3, 4, 5] 

코드는 아래와 같다 :

TIMESTEPS = 20 
num_hidden=20 

Xd, yd = load_data() 

train_input = Xd['train'] 
train_input = train_input.reshape(-1,20,1) 
train_output = yd['train'] 

# train_input = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],.. 
# train_output = [[21],[22],[23].... 

test_input = Xd['test'] 
test_output = yd['test'] 

X = tf.placeholder(tf.float32, [None, 20, 1]) 
y = tf.placeholder(tf.float32, [None, 1]) 

cell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True) 

val, state = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32) 
val = tf.Print(val, [tf.argmax(val,1)], 'argmax(val)=' , summarize=20, first_n=7) 

val = tf.transpose(val, [1, 0, 2]) 
val = tf.Print(val, [tf.argmax(val,1)], 'argmax(val2)=' , summarize=20, first_n=7) 

# Take only the last output after 20 time steps 
last = tf.gather(val, int(val.get_shape()[0]) - 1) 
last = tf.Print(last, [tf.argmax(last,1)], 'argmax(val3)=' , summarize=20, first_n=7) 

# define variables for weights and bias 
weight = tf.Variable(tf.truncated_normal([num_hidden, int(y.get_shape()[1])])) 
bias = tf.Variable(tf.constant(0.1, shape=[y.get_shape()[1]])) 

# Prediction is matmul of last value + wieght + bias 
prediction = tf.matmul(last, weight) + bias 

# Cost function using softmax 
# y is the true distrubution and prediction is the predicted 
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(prediction), reduction_indices=[1])) 
#cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) 

optimizer = tf.train.AdamOptimizer() 
minimize = optimizer.minimize(cost) 

from tensorflow.python import debug as tf_debug 
inita = tf.initialize_all_variables() 
sess = tf.Session() 
sess.run(inita) 

batch_size = 100 
no_of_batches = int(len(train_input)/batch_size) 
epoch = 10 
test_size = 100 
for i in range(epoch): 
    for start, end in zip(range(0, len(train_input), batch_size), range(batch_size, len(train_input)+1, batch_size)): 
     sess.run(minimize, feed_dict={X: train_input[start:end], y: train_output[start:end]}) 

    test_indices = np.arange(len(test_input)) # Get A Test Batch 
    np.random.shuffle(test_indices) 
    test_indices = test_indices[0:test_size] 
    print (i, mean_squared_error(np.argmax(test_output[test_indices], axis=1), sess.run(prediction, feed_dict={X: test_input[test_indices]}))) 

print ("predictions", prediction.eval(feed_dict={X: train_input}, session=sess)) 
y_pred = prediction.eval(feed_dict={X: test_input}, session=sess) 
sess.close() 
test_size = test_output.shape[0] 
ax = np.arange(0, test_size, 1) 
plt.plot(ax, test_output, 'r', ax, y_pred, 'b') 
plt.show() 

하지만 비용을 최소화 할 수 아니라고 계산 된 MSE 대신 감소의 각 단계에서 증가한다. 나는 사용하고있는 비용 문제에 문제가 있다고 생각합니다.

내가 뭘 잘못하고 있는지에 대한 생각이나 제안이 있으십니까? 주석에서 언급 한 바와 같이

감사

+0

크로스 엔트로피 대신 평균 제곱 오류를 사용하려고하면 여기서 분류를 수행하지 않습니다. 비용 = 0.5 * tf.square (y- 예측); 비용 = tf.reduce_mean (비용) –

+0

안녕하세요. 안토니, 의견을 보내 주셔서 감사합니다. 나는 당신이 제안한 것처럼 MSE를 비용으로 사용하려고 시도했으나, 각시기 후에 계산 된 MSE 오류는 여전히 증가하고 있습니다. 내 말은, – Praveen

+1

. Adam Optimizer를 사용하여 학습 률을 줄였습니까? –

답변

1

, 당신은 MSE 기능에 손실 함수를 변경하고 학습 속도를 감소했다. 오류가 0으로 수렴하고 있습니까?

+0

이제 저는 사인 함수를 사용하여 장난감 예제 데이터 세트를 테스트했습니다. MSE는 작은 범위 (이 경우 0.6 ~ 0.5)에서 변동하지만 결코 그 값 아래로 감소하지 않습니다. 사인 함수와 같은 단순한 경우에는 0으로 수렴해야한다고 생각합니까? – Praveen