Unable to build a proper image captioning rnn using TensorflowMinimal RNN example in tensorflowWhat's the difference between tensorflow dynamic_rnn and rnn?using pre-loaded data in TensorFlowUsing make_template() in TensorFlowHow to write a multidimentional regression predictor using an RNN in tensorflow 0.11Difficulty in interpreting the output of tensorflow's dynamic_rnnWhat is a dynamic RNN in TensorFlow?label_keys type error on DNNCLassifier TensorflowTrouble with understanding how TensorFlow receives and processes dataTensorflow RNN Input shape
How can powerful telekinesis avoid violating Newton's 3rd Law?
My mom's return ticket is 3 days after I-94 expires
Why are ambiguous grammars bad?
Does it make sense to use a wavelet that is equal to a sine of one period?
bash vs. zsh: What are the practical differences?
How do I make a Magical Dart Thrower more economical in Adventurers League?
If absolute velocity does not exist, how can we say a rocket accelerates in empty space?
What plausible reason could I give for my FTL drive only working in space
Is Dumbledore a human lie detector?
Why would a home insurer offer a discount based on credit score?
Is Jesus the last Prophet?
Was self-modifying code possible using BASIC?
Is it advisable to add a location heads-up when a scene changes in a novel?
Course development: can I pay someone to make slides for the course?
Parsing text written the millitext font
Why did the World Bank set the global poverty line at $1.90?
How does AFV select the winning videos?
What is the STRONGEST end-of-line knot to use if you want to use a steel-thimble at the end, so that you've got a steel-eyelet at the end of the line?
What is the theme of analysis?
How can I find out about the game world without meta-influencing it?
In Pandemic, why take the extra step of eradicating a disease after you've cured it?
Why do Bhargava-Skinner-Zhang consider the ordering by height?
Does a single fopen introduce TOCTOU vulnerability?
What is the proper event in Extended Events to track stored procedure executions?
Unable to build a proper image captioning rnn using Tensorflow
Minimal RNN example in tensorflowWhat's the difference between tensorflow dynamic_rnn and rnn?using pre-loaded data in TensorFlowUsing make_template() in TensorFlowHow to write a multidimentional regression predictor using an RNN in tensorflow 0.11Difficulty in interpreting the output of tensorflow's dynamic_rnnWhat is a dynamic RNN in TensorFlow?label_keys type error on DNNCLassifier TensorflowTrouble with understanding how TensorFlow receives and processes dataTensorflow RNN Input shape
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I am trying to build an image captioning RNN by following the same logic in assignment3 from Standford's CS231n class (http://cs231n.github.io/assignments2018/assignment3/). I had previously completed the assignment3 which used numpy to build the RNN. Right now, I want to build the same RNN but using Tensorflow this time, and the following is my code. However, the loss I get during training does not decrease for some reason. So, I think there must be some logical and setting issue within my code.
There are two inputs for this RNN during training, features and captions. The features is the output from a CNN, and captions is a matrix descibing words in each time point. Features is projected to become the initial output h0 by matrix multiplication. h0 with a zero matrix will form an initial state for the lstm. Captions (captions_in) will transform to a word embedding matrix which contains inputs for all the time point for the RNN. the outputs from the lstm will project to a scores matrix which is used for predicting the captions of the images. The scores matrix along with the captions_out matrix are used to evaluate the loss.
import tensorflow as tf
import tensorflow.contrib.eager as tfe
import numpy as np
tfe.enable_eager_execution()
class CaptioningRNN(object):
def __init__(self, word_to_idx, input_dim=512, wordvec_dim=128, hidden_dim=128):
self.word_to_idx = word_to_idx
self.idx_to_word = i: w for w, i in word_to_idx.items()
self.hidden_dim = hidden_dim
# initialize weights
self.W_proj = tfe.Variable(np.random.randn(input_dim, hidden_dim)/np.sqrt(input_dim), dtype=tf.float32)
self.b_proj = tfe.Variable(np.zeros(hidden_dim), dtype=tf.float32)
self.W_embed = tfe.Variable(np.random.randn(len(word_to_idx), wordvec_dim), dtype=tf.float32)
self.W_vocab = tfe.Variable(np.random.randn(hidden_dim, len(word_to_idx))/np.square(hidden_dim), dtype=tf.float32)
self.b_vocab = tfe.Variable(np.zeros(len(word_to_idx)), dtype=tf.float32)
# initialize lstm cell
self.encoder_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_dim)
def forward(self, features, captions):
outputs = []
h0 = tf.matmul(features, self.W_proj) + self.b_proj
x = tf.nn.embedding_lookup(self.W_embed, captions)
timestep_x = tf.unstack(x, axis=1)
c = tfe.Variable(np.zeros((features.shape[0], self.hidden_dim)), dtype=tf.float32)
state = tf.nn.rnn_cell.LSTMStateTuple(c=c, h=h0)
for input_steps in timestep_x:
output, state = self.encoder_cell(input_steps, state)
outputs.append(output)
outputs = tf.stack(outputs, axis=1)
reshaped_outputs = tf.reshape(outputs, [outputs.shape[0] * outputs.shape[1], outputs.shape[2]])
reshaped_scores = tf.matmul(reshaped_outputs, self.W_vocab)
scores = tf.reshape(reshaped_scores, [outputs.shape[0], outputs.shape[1], self.b_vocab.shape[0]]) + self.b_vocab
return scores
def cost(self, scores, labels):
scores_flat = tf.reshape(scores, [scores.shape[0]*scores.shape[1], scores.shape[2]])
labels_flat = tf.reshape(labels, [labels.shape[0] * labels.shape[1], 1])
cost = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_flat, logits=scores_flat)
return tf.reduce_mean(cost)
def get_loss(model, features, captions):
scores = model.forward(features, captions[:, :-1])
cost = model.cost(scores, captions[:, 1:])
return cost
N = 2 # batch_size
T = 3 # timesteps
D = 4 # input_dim
W = 5 # wordvec_dim
H = 10 # hidden_dim
word_to_idx = '<NULL>': 0, 'cat': 2, 'dog': 3
vocab_size = len(word_to_idx)
features = np.random.randn(N, D).astype(np.float32)
captions = np.random.randint(vocab_size, size=(N, T))
model = CaptioningRNN(word_to_idx, input_dim=D, wordvec_dim=W, hidden_dim=H)
# get_loss(model, features, captions)
optimizer = tf.train.AdamOptimizer(5e-3)
for i in range(5000):
optimizer.minimize(lambda: get_loss(model, features, captions))
if i % 500 == 0:
ls = get_loss(model, features, captions)
print("loss: ".format(ls))
loss: 2.4719245433807373
loss: 2.4723522663116455
loss: 2.472407579421997
loss: 2.4723868370056152
loss: 2.472378969192505
loss: 2.4724044799804688
loss: 2.472418785095215
loss: 2.472426414489746
loss: 2.472430944442749
loss: 2.4724338054656982
tensorflow recurrent-neural-network
add a comment |
I am trying to build an image captioning RNN by following the same logic in assignment3 from Standford's CS231n class (http://cs231n.github.io/assignments2018/assignment3/). I had previously completed the assignment3 which used numpy to build the RNN. Right now, I want to build the same RNN but using Tensorflow this time, and the following is my code. However, the loss I get during training does not decrease for some reason. So, I think there must be some logical and setting issue within my code.
There are two inputs for this RNN during training, features and captions. The features is the output from a CNN, and captions is a matrix descibing words in each time point. Features is projected to become the initial output h0 by matrix multiplication. h0 with a zero matrix will form an initial state for the lstm. Captions (captions_in) will transform to a word embedding matrix which contains inputs for all the time point for the RNN. the outputs from the lstm will project to a scores matrix which is used for predicting the captions of the images. The scores matrix along with the captions_out matrix are used to evaluate the loss.
import tensorflow as tf
import tensorflow.contrib.eager as tfe
import numpy as np
tfe.enable_eager_execution()
class CaptioningRNN(object):
def __init__(self, word_to_idx, input_dim=512, wordvec_dim=128, hidden_dim=128):
self.word_to_idx = word_to_idx
self.idx_to_word = i: w for w, i in word_to_idx.items()
self.hidden_dim = hidden_dim
# initialize weights
self.W_proj = tfe.Variable(np.random.randn(input_dim, hidden_dim)/np.sqrt(input_dim), dtype=tf.float32)
self.b_proj = tfe.Variable(np.zeros(hidden_dim), dtype=tf.float32)
self.W_embed = tfe.Variable(np.random.randn(len(word_to_idx), wordvec_dim), dtype=tf.float32)
self.W_vocab = tfe.Variable(np.random.randn(hidden_dim, len(word_to_idx))/np.square(hidden_dim), dtype=tf.float32)
self.b_vocab = tfe.Variable(np.zeros(len(word_to_idx)), dtype=tf.float32)
# initialize lstm cell
self.encoder_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_dim)
def forward(self, features, captions):
outputs = []
h0 = tf.matmul(features, self.W_proj) + self.b_proj
x = tf.nn.embedding_lookup(self.W_embed, captions)
timestep_x = tf.unstack(x, axis=1)
c = tfe.Variable(np.zeros((features.shape[0], self.hidden_dim)), dtype=tf.float32)
state = tf.nn.rnn_cell.LSTMStateTuple(c=c, h=h0)
for input_steps in timestep_x:
output, state = self.encoder_cell(input_steps, state)
outputs.append(output)
outputs = tf.stack(outputs, axis=1)
reshaped_outputs = tf.reshape(outputs, [outputs.shape[0] * outputs.shape[1], outputs.shape[2]])
reshaped_scores = tf.matmul(reshaped_outputs, self.W_vocab)
scores = tf.reshape(reshaped_scores, [outputs.shape[0], outputs.shape[1], self.b_vocab.shape[0]]) + self.b_vocab
return scores
def cost(self, scores, labels):
scores_flat = tf.reshape(scores, [scores.shape[0]*scores.shape[1], scores.shape[2]])
labels_flat = tf.reshape(labels, [labels.shape[0] * labels.shape[1], 1])
cost = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_flat, logits=scores_flat)
return tf.reduce_mean(cost)
def get_loss(model, features, captions):
scores = model.forward(features, captions[:, :-1])
cost = model.cost(scores, captions[:, 1:])
return cost
N = 2 # batch_size
T = 3 # timesteps
D = 4 # input_dim
W = 5 # wordvec_dim
H = 10 # hidden_dim
word_to_idx = '<NULL>': 0, 'cat': 2, 'dog': 3
vocab_size = len(word_to_idx)
features = np.random.randn(N, D).astype(np.float32)
captions = np.random.randint(vocab_size, size=(N, T))
model = CaptioningRNN(word_to_idx, input_dim=D, wordvec_dim=W, hidden_dim=H)
# get_loss(model, features, captions)
optimizer = tf.train.AdamOptimizer(5e-3)
for i in range(5000):
optimizer.minimize(lambda: get_loss(model, features, captions))
if i % 500 == 0:
ls = get_loss(model, features, captions)
print("loss: ".format(ls))
loss: 2.4719245433807373
loss: 2.4723522663116455
loss: 2.472407579421997
loss: 2.4723868370056152
loss: 2.472378969192505
loss: 2.4724044799804688
loss: 2.472418785095215
loss: 2.472426414489746
loss: 2.472430944442749
loss: 2.4724338054656982
tensorflow recurrent-neural-network
add a comment |
I am trying to build an image captioning RNN by following the same logic in assignment3 from Standford's CS231n class (http://cs231n.github.io/assignments2018/assignment3/). I had previously completed the assignment3 which used numpy to build the RNN. Right now, I want to build the same RNN but using Tensorflow this time, and the following is my code. However, the loss I get during training does not decrease for some reason. So, I think there must be some logical and setting issue within my code.
There are two inputs for this RNN during training, features and captions. The features is the output from a CNN, and captions is a matrix descibing words in each time point. Features is projected to become the initial output h0 by matrix multiplication. h0 with a zero matrix will form an initial state for the lstm. Captions (captions_in) will transform to a word embedding matrix which contains inputs for all the time point for the RNN. the outputs from the lstm will project to a scores matrix which is used for predicting the captions of the images. The scores matrix along with the captions_out matrix are used to evaluate the loss.
import tensorflow as tf
import tensorflow.contrib.eager as tfe
import numpy as np
tfe.enable_eager_execution()
class CaptioningRNN(object):
def __init__(self, word_to_idx, input_dim=512, wordvec_dim=128, hidden_dim=128):
self.word_to_idx = word_to_idx
self.idx_to_word = i: w for w, i in word_to_idx.items()
self.hidden_dim = hidden_dim
# initialize weights
self.W_proj = tfe.Variable(np.random.randn(input_dim, hidden_dim)/np.sqrt(input_dim), dtype=tf.float32)
self.b_proj = tfe.Variable(np.zeros(hidden_dim), dtype=tf.float32)
self.W_embed = tfe.Variable(np.random.randn(len(word_to_idx), wordvec_dim), dtype=tf.float32)
self.W_vocab = tfe.Variable(np.random.randn(hidden_dim, len(word_to_idx))/np.square(hidden_dim), dtype=tf.float32)
self.b_vocab = tfe.Variable(np.zeros(len(word_to_idx)), dtype=tf.float32)
# initialize lstm cell
self.encoder_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_dim)
def forward(self, features, captions):
outputs = []
h0 = tf.matmul(features, self.W_proj) + self.b_proj
x = tf.nn.embedding_lookup(self.W_embed, captions)
timestep_x = tf.unstack(x, axis=1)
c = tfe.Variable(np.zeros((features.shape[0], self.hidden_dim)), dtype=tf.float32)
state = tf.nn.rnn_cell.LSTMStateTuple(c=c, h=h0)
for input_steps in timestep_x:
output, state = self.encoder_cell(input_steps, state)
outputs.append(output)
outputs = tf.stack(outputs, axis=1)
reshaped_outputs = tf.reshape(outputs, [outputs.shape[0] * outputs.shape[1], outputs.shape[2]])
reshaped_scores = tf.matmul(reshaped_outputs, self.W_vocab)
scores = tf.reshape(reshaped_scores, [outputs.shape[0], outputs.shape[1], self.b_vocab.shape[0]]) + self.b_vocab
return scores
def cost(self, scores, labels):
scores_flat = tf.reshape(scores, [scores.shape[0]*scores.shape[1], scores.shape[2]])
labels_flat = tf.reshape(labels, [labels.shape[0] * labels.shape[1], 1])
cost = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_flat, logits=scores_flat)
return tf.reduce_mean(cost)
def get_loss(model, features, captions):
scores = model.forward(features, captions[:, :-1])
cost = model.cost(scores, captions[:, 1:])
return cost
N = 2 # batch_size
T = 3 # timesteps
D = 4 # input_dim
W = 5 # wordvec_dim
H = 10 # hidden_dim
word_to_idx = '<NULL>': 0, 'cat': 2, 'dog': 3
vocab_size = len(word_to_idx)
features = np.random.randn(N, D).astype(np.float32)
captions = np.random.randint(vocab_size, size=(N, T))
model = CaptioningRNN(word_to_idx, input_dim=D, wordvec_dim=W, hidden_dim=H)
# get_loss(model, features, captions)
optimizer = tf.train.AdamOptimizer(5e-3)
for i in range(5000):
optimizer.minimize(lambda: get_loss(model, features, captions))
if i % 500 == 0:
ls = get_loss(model, features, captions)
print("loss: ".format(ls))
loss: 2.4719245433807373
loss: 2.4723522663116455
loss: 2.472407579421997
loss: 2.4723868370056152
loss: 2.472378969192505
loss: 2.4724044799804688
loss: 2.472418785095215
loss: 2.472426414489746
loss: 2.472430944442749
loss: 2.4724338054656982
tensorflow recurrent-neural-network
I am trying to build an image captioning RNN by following the same logic in assignment3 from Standford's CS231n class (http://cs231n.github.io/assignments2018/assignment3/). I had previously completed the assignment3 which used numpy to build the RNN. Right now, I want to build the same RNN but using Tensorflow this time, and the following is my code. However, the loss I get during training does not decrease for some reason. So, I think there must be some logical and setting issue within my code.
There are two inputs for this RNN during training, features and captions. The features is the output from a CNN, and captions is a matrix descibing words in each time point. Features is projected to become the initial output h0 by matrix multiplication. h0 with a zero matrix will form an initial state for the lstm. Captions (captions_in) will transform to a word embedding matrix which contains inputs for all the time point for the RNN. the outputs from the lstm will project to a scores matrix which is used for predicting the captions of the images. The scores matrix along with the captions_out matrix are used to evaluate the loss.
import tensorflow as tf
import tensorflow.contrib.eager as tfe
import numpy as np
tfe.enable_eager_execution()
class CaptioningRNN(object):
def __init__(self, word_to_idx, input_dim=512, wordvec_dim=128, hidden_dim=128):
self.word_to_idx = word_to_idx
self.idx_to_word = i: w for w, i in word_to_idx.items()
self.hidden_dim = hidden_dim
# initialize weights
self.W_proj = tfe.Variable(np.random.randn(input_dim, hidden_dim)/np.sqrt(input_dim), dtype=tf.float32)
self.b_proj = tfe.Variable(np.zeros(hidden_dim), dtype=tf.float32)
self.W_embed = tfe.Variable(np.random.randn(len(word_to_idx), wordvec_dim), dtype=tf.float32)
self.W_vocab = tfe.Variable(np.random.randn(hidden_dim, len(word_to_idx))/np.square(hidden_dim), dtype=tf.float32)
self.b_vocab = tfe.Variable(np.zeros(len(word_to_idx)), dtype=tf.float32)
# initialize lstm cell
self.encoder_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_dim)
def forward(self, features, captions):
outputs = []
h0 = tf.matmul(features, self.W_proj) + self.b_proj
x = tf.nn.embedding_lookup(self.W_embed, captions)
timestep_x = tf.unstack(x, axis=1)
c = tfe.Variable(np.zeros((features.shape[0], self.hidden_dim)), dtype=tf.float32)
state = tf.nn.rnn_cell.LSTMStateTuple(c=c, h=h0)
for input_steps in timestep_x:
output, state = self.encoder_cell(input_steps, state)
outputs.append(output)
outputs = tf.stack(outputs, axis=1)
reshaped_outputs = tf.reshape(outputs, [outputs.shape[0] * outputs.shape[1], outputs.shape[2]])
reshaped_scores = tf.matmul(reshaped_outputs, self.W_vocab)
scores = tf.reshape(reshaped_scores, [outputs.shape[0], outputs.shape[1], self.b_vocab.shape[0]]) + self.b_vocab
return scores
def cost(self, scores, labels):
scores_flat = tf.reshape(scores, [scores.shape[0]*scores.shape[1], scores.shape[2]])
labels_flat = tf.reshape(labels, [labels.shape[0] * labels.shape[1], 1])
cost = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_flat, logits=scores_flat)
return tf.reduce_mean(cost)
def get_loss(model, features, captions):
scores = model.forward(features, captions[:, :-1])
cost = model.cost(scores, captions[:, 1:])
return cost
N = 2 # batch_size
T = 3 # timesteps
D = 4 # input_dim
W = 5 # wordvec_dim
H = 10 # hidden_dim
word_to_idx = '<NULL>': 0, 'cat': 2, 'dog': 3
vocab_size = len(word_to_idx)
features = np.random.randn(N, D).astype(np.float32)
captions = np.random.randint(vocab_size, size=(N, T))
model = CaptioningRNN(word_to_idx, input_dim=D, wordvec_dim=W, hidden_dim=H)
# get_loss(model, features, captions)
optimizer = tf.train.AdamOptimizer(5e-3)
for i in range(5000):
optimizer.minimize(lambda: get_loss(model, features, captions))
if i % 500 == 0:
ls = get_loss(model, features, captions)
print("loss: ".format(ls))
loss: 2.4719245433807373
loss: 2.4723522663116455
loss: 2.472407579421997
loss: 2.4723868370056152
loss: 2.472378969192505
loss: 2.4724044799804688
loss: 2.472418785095215
loss: 2.472426414489746
loss: 2.472430944442749
loss: 2.4724338054656982
tensorflow recurrent-neural-network
tensorflow recurrent-neural-network
asked Mar 24 at 23:00
siyi lisiyi li
295
295
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55329411%2funable-to-build-a-proper-image-captioning-rnn-using-tensorflow%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55329411%2funable-to-build-a-proper-image-captioning-rnn-using-tensorflow%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown