이야기 생성기를 할 때 단어 표현으로 글로브 벡터를 구현하고 싶습니다. 출력에 softmax에 대해 완전히 연결된 레이어가있는 2 레이어 LSTM을 사용하고 있습니다.다중 레이어 LSTM 전에 삽입 레이어를 추가하는 방법은 무엇입니까?
archetecture은 다음과 같습니다
는Input --> LSTM --> LSTM --> Fully connected --> Output
내 입력의 경우, 모델은 그 세 단어를 기반으로 단어를 세 단어를 가지고 출력한다. 각 입력은 25의 차원을 가진 벡터입니다. 저는 훈련을 위해 사용하는 텍스트에서 100 개의 레이블 만 있습니다. 각 LSTM에는 512 개의 숨겨진 유닛이 있습니다.
참조하십시오 아래에있는 내 코드 :
# Parameters
learning_rate = 0.001
training_iters = 50000
display_step = 1000
n_input = 3
n_hidden = 512
# tf Graph input
x = tf.placeholder("float", [None, n_input, glove_dim])
y = tf.placeholder("float", [None, vocab_size])
# RNN output node weights and biases
weights = {'out': tf.Variable(tf.random_normal([n_hidden, vocab_size]))}
biases = {'out': tf.Variable(tf.random_normal([vocab_size]))}
def RNN(x, weights, biases):
# reshape to [1, n_input]
x = tf.reshape(x, [-1, n_input])
# Generate a n_input-element sequence of inputs
x = tf.split(x,n_input,1)
rnn_cell =rnn.MultiRNNCell([rnn.BasicLSTMCell(n_hidden),rnn.BasicLSTMCell(n_hidden)])
# generate prediction
outputs, states = rnn.static_rnn(rnn_cell, x, dtype=tf.float32)
return tf.matmul(outputs[-1], weights['out']) + biases['out']
pred = RNN(x, weights, biases)
# Loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.RMSPropOptimizer(learning_rate=learning_rate).minimize(cost)
# Model evaluation
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
with tf.Session() as session:
session.run(init)
step = 0
offset = random.randint(0,n_input+1)
end_offset = n_input + 1
acc_total = 0
loss_total = 0
writer.add_graph(session.graph)
while step < training_iters:
# Generate a minibatch. Add some randomness on selection process.
if offset > (len(training_data)-end_offset):
offset = random.randint(0, n_input+1)
symbols_in_keys = [ [glove_dictionary[ str(training_data[i])]] for i in range(offset, offset+n_input) ]
symbols_in_keys = np.reshape(np.array(symbols_in_keys), [-1, n_input, glove_dim])
symbols_out_onehot = np.zeros([vocab_size], dtype=float)
symbols_out_onehot[dictionary[str(training_data[offset+n_input])]] = 1.0
symbols_out_onehot = np.reshape(symbols_out_onehot,[1,-1])
_, acc, loss, onehot_pred = session.run([optimizer, accuracy, cost, pred], \
feed_dict={x:symbols_in_keys, y: symbols_out_onehot})
loss_total += loss
acc_total += acc
if (step+1) % display_step == 0:
print("Iter= " + str(step+1) + ", Average Loss= " + \
"{:.6f}".format(loss_total/display_step) + ", Average Accuracy= " + \
"{:.2f}%".format(100*acc_total/display_step))
acc_total = 0
loss_total = 0
symbols_in = [training_data[i] for i in range(offset, offset + n_input)]
symbols_out = training_data[offset + n_input]
symbols_out_pred = reverse_dictionary[int(tf.argmax(onehot_pred, 1).eval())]
print("%s - [%s] vs [%s]" % (symbols_in,symbols_out,symbols_out_pred))
step += 1
offset += (n_input+1)
print("Optimization Finished!")
print("Elapsed time: ", elapsed(time.time() - start_time))
print("Run on command line.")
print("\ttensorboard --logdir=%s" % (logs_path))
print("Point your web browser to: http://localhost:6006/")
while True:
prompt = "%s words: " % n_input
sentence = input(prompt)
sentence = sentence.strip()
words = sentence.split(' ')
if len(words) != n_input:
continue
try:
symbols_in_keys = [glove_dictionary[str(words[i])] for i in range(len(words))]
for i in range(32):
keys = np.reshape(np.array(symbols_in_keys), [-1, n_input, 1])
onehot_pred = session.run(pred, feed_dict={x: keys})
onehot_pred_index = int(tf.argmax(onehot_pred, 1).eval())
sentence = "%s %s" % (sentence,reverse_dictionary[onehot_pred_index])
symbols_in_keys = symbols_in_keys[1:]
symbols_in_keys.append(onehot_pred_index)
print(sentence)
except:
print("Word not in dictionary")
나는 이것을 실행하면, 나는 오류 받고 있어요 :
InvalidArgumentError (see above for traceback): logits and labels must have the same first dimension, got logits shape [160,14313] and labels shape [10]
[[Node: SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits = SparseSoftmaxCrossEntropyWithLogits[T=DT_FLOAT, Tlabels=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"](add, Reshape_1)]]
나는 모양이 결정된다 logits하는 방법을 알 수 있으며, 내가 무엇을 할 수 내 코드를 수정 하시겠습니까?
후
x = [tf.reshape(w, [-1, glove_dim]) for w in x]
을 추가하는 시도 할 수됩니다! 나는 모양을 할 때 지금 모양이 무엇인지 이해할 수 없다? – noobiejp
나는 당신이 무엇을 요구하고 있는지 확실히 모르겠습니다. -1을 의미합니까? – DAlolicorn
나는 x = [tf.reshape (w, [-1, glove_dim])을 x로 한 후 x의 모양을 의미합니까? – noobiejp