how to make a input tensor trainable











up vote
1
down vote

favorite












The following is the code trying to use the input image as a training variable during the optimization. It starts with a keras model and convert that to a tensorflow model. This tensorflow model take a tensor as input and try to optimize the cost function using the input tensor as a trainable variable.



The error is:





NotImplementedError: ('Trying to update a Tensor ', )





The reason is that the input tensor is not a variable. The question is how to make the input image trainable or cast a tensor to a tf.variable. Help is appreciated:



import tensorflow as tf
from keras.models import Sequential, load_model, Model
from keras import backend as K
from keras.layers.core import Dense, Dropout, Activation
import os
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io

n_classes = 10

model = Sequential()
model.add(Dense(10, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dense(n_classes, name='logits'))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')

# Write the graph in binary .pb file
outdir = "model4_tf"
try:
os.mkdir(outdir )
except:
pass


prefix = "simple_nn"
name = 'output_graph.pb'
# Alias the outputs in the model - this sometimes makes them easier to access in TF
pred =
pred_node_names =
for i, o in enumerate(model.outputs):
pred_node_names.append(prefix+'_'+str(i))
pred.append(tf.identity(o,
name=pred_node_names[i]))
print('Output nodes names are: ', pred_node_names)


sess = K.get_session()


constant_graph = graph_util.convert_variables_to_constants(sess,
sess.graph.as_graph_def(), pred_node_names)
graph_io.write_graph(constant_graph, outdir, name, as_text=False)


tf.reset_default_graph()

def load_graph(model_name):
#graph = tf.Graph()
graph = tf.get_default_graph()
graph_def = tf.GraphDef()
with open(model_name, "rb") as f:
graph_def.ParseFromString(f.read())
with graph.as_default():
tf.import_graph_def(graph_def)
return graph

my_graph = load_graph(model_name=os.path.join(outdir, name))


# In[15]:

input_op = my_graph.get_operation_by_name("import/dense_1_input")
output_op = my_graph.get_operation_by_name("import/simple_nn_0")
logit_op = my_graph.get_operation_by_name("import/logits/BiasAdd")


x_hat = input_op.outputs[0] # input tensor
labels = output_op.outputs[0] # label tensor
logits = logit_op.outputs[0] # logits tensor

learning_rate = tf.placeholder(tf.float32, ())

loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=[labels])
optim_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, var_list=[x_hat])









share|improve this question
























  • One thing you could do is not to use an optimizer, but instead get the input gradient with tf.gradients and apply updates to the input outside of TensorFlow. But you can also replace the input placeholder with an actual variable, and simply load the input value that you want to optimize.
    – jdehesa
    Nov 9 at 16:15










  • Or, about the first option, you could actually use an optimizer, but only use compute_gradients, then actually apply them out of TensorFlow (I have not tried it but I think that should work, even with non-variables).
    – jdehesa
    Nov 9 at 16:31












  • Why not cast the input as variable? This should be possible,too.
    – Lau
    Nov 9 at 17:02










  • can you please show me how to do the cast?
    – David
    Nov 9 at 18:41










  • One can come out a code to do the gradient decent but it defeat the purpose of using tensorflow which suppose to simplify the procedure
    – David
    Nov 9 at 18:44















up vote
1
down vote

favorite












The following is the code trying to use the input image as a training variable during the optimization. It starts with a keras model and convert that to a tensorflow model. This tensorflow model take a tensor as input and try to optimize the cost function using the input tensor as a trainable variable.



The error is:





NotImplementedError: ('Trying to update a Tensor ', )





The reason is that the input tensor is not a variable. The question is how to make the input image trainable or cast a tensor to a tf.variable. Help is appreciated:



import tensorflow as tf
from keras.models import Sequential, load_model, Model
from keras import backend as K
from keras.layers.core import Dense, Dropout, Activation
import os
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io

n_classes = 10

model = Sequential()
model.add(Dense(10, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dense(n_classes, name='logits'))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')

# Write the graph in binary .pb file
outdir = "model4_tf"
try:
os.mkdir(outdir )
except:
pass


prefix = "simple_nn"
name = 'output_graph.pb'
# Alias the outputs in the model - this sometimes makes them easier to access in TF
pred =
pred_node_names =
for i, o in enumerate(model.outputs):
pred_node_names.append(prefix+'_'+str(i))
pred.append(tf.identity(o,
name=pred_node_names[i]))
print('Output nodes names are: ', pred_node_names)


sess = K.get_session()


constant_graph = graph_util.convert_variables_to_constants(sess,
sess.graph.as_graph_def(), pred_node_names)
graph_io.write_graph(constant_graph, outdir, name, as_text=False)


tf.reset_default_graph()

def load_graph(model_name):
#graph = tf.Graph()
graph = tf.get_default_graph()
graph_def = tf.GraphDef()
with open(model_name, "rb") as f:
graph_def.ParseFromString(f.read())
with graph.as_default():
tf.import_graph_def(graph_def)
return graph

my_graph = load_graph(model_name=os.path.join(outdir, name))


# In[15]:

input_op = my_graph.get_operation_by_name("import/dense_1_input")
output_op = my_graph.get_operation_by_name("import/simple_nn_0")
logit_op = my_graph.get_operation_by_name("import/logits/BiasAdd")


x_hat = input_op.outputs[0] # input tensor
labels = output_op.outputs[0] # label tensor
logits = logit_op.outputs[0] # logits tensor

learning_rate = tf.placeholder(tf.float32, ())

loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=[labels])
optim_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, var_list=[x_hat])









share|improve this question
























  • One thing you could do is not to use an optimizer, but instead get the input gradient with tf.gradients and apply updates to the input outside of TensorFlow. But you can also replace the input placeholder with an actual variable, and simply load the input value that you want to optimize.
    – jdehesa
    Nov 9 at 16:15










  • Or, about the first option, you could actually use an optimizer, but only use compute_gradients, then actually apply them out of TensorFlow (I have not tried it but I think that should work, even with non-variables).
    – jdehesa
    Nov 9 at 16:31












  • Why not cast the input as variable? This should be possible,too.
    – Lau
    Nov 9 at 17:02










  • can you please show me how to do the cast?
    – David
    Nov 9 at 18:41










  • One can come out a code to do the gradient decent but it defeat the purpose of using tensorflow which suppose to simplify the procedure
    – David
    Nov 9 at 18:44













up vote
1
down vote

favorite









up vote
1
down vote

favorite











The following is the code trying to use the input image as a training variable during the optimization. It starts with a keras model and convert that to a tensorflow model. This tensorflow model take a tensor as input and try to optimize the cost function using the input tensor as a trainable variable.



The error is:





NotImplementedError: ('Trying to update a Tensor ', )





The reason is that the input tensor is not a variable. The question is how to make the input image trainable or cast a tensor to a tf.variable. Help is appreciated:



import tensorflow as tf
from keras.models import Sequential, load_model, Model
from keras import backend as K
from keras.layers.core import Dense, Dropout, Activation
import os
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io

n_classes = 10

model = Sequential()
model.add(Dense(10, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dense(n_classes, name='logits'))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')

# Write the graph in binary .pb file
outdir = "model4_tf"
try:
os.mkdir(outdir )
except:
pass


prefix = "simple_nn"
name = 'output_graph.pb'
# Alias the outputs in the model - this sometimes makes them easier to access in TF
pred =
pred_node_names =
for i, o in enumerate(model.outputs):
pred_node_names.append(prefix+'_'+str(i))
pred.append(tf.identity(o,
name=pred_node_names[i]))
print('Output nodes names are: ', pred_node_names)


sess = K.get_session()


constant_graph = graph_util.convert_variables_to_constants(sess,
sess.graph.as_graph_def(), pred_node_names)
graph_io.write_graph(constant_graph, outdir, name, as_text=False)


tf.reset_default_graph()

def load_graph(model_name):
#graph = tf.Graph()
graph = tf.get_default_graph()
graph_def = tf.GraphDef()
with open(model_name, "rb") as f:
graph_def.ParseFromString(f.read())
with graph.as_default():
tf.import_graph_def(graph_def)
return graph

my_graph = load_graph(model_name=os.path.join(outdir, name))


# In[15]:

input_op = my_graph.get_operation_by_name("import/dense_1_input")
output_op = my_graph.get_operation_by_name("import/simple_nn_0")
logit_op = my_graph.get_operation_by_name("import/logits/BiasAdd")


x_hat = input_op.outputs[0] # input tensor
labels = output_op.outputs[0] # label tensor
logits = logit_op.outputs[0] # logits tensor

learning_rate = tf.placeholder(tf.float32, ())

loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=[labels])
optim_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, var_list=[x_hat])









share|improve this question















The following is the code trying to use the input image as a training variable during the optimization. It starts with a keras model and convert that to a tensorflow model. This tensorflow model take a tensor as input and try to optimize the cost function using the input tensor as a trainable variable.



The error is:





NotImplementedError: ('Trying to update a Tensor ', )





The reason is that the input tensor is not a variable. The question is how to make the input image trainable or cast a tensor to a tf.variable. Help is appreciated:



import tensorflow as tf
from keras.models import Sequential, load_model, Model
from keras import backend as K
from keras.layers.core import Dense, Dropout, Activation
import os
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io

n_classes = 10

model = Sequential()
model.add(Dense(10, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dense(n_classes, name='logits'))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')

# Write the graph in binary .pb file
outdir = "model4_tf"
try:
os.mkdir(outdir )
except:
pass


prefix = "simple_nn"
name = 'output_graph.pb'
# Alias the outputs in the model - this sometimes makes them easier to access in TF
pred =
pred_node_names =
for i, o in enumerate(model.outputs):
pred_node_names.append(prefix+'_'+str(i))
pred.append(tf.identity(o,
name=pred_node_names[i]))
print('Output nodes names are: ', pred_node_names)


sess = K.get_session()


constant_graph = graph_util.convert_variables_to_constants(sess,
sess.graph.as_graph_def(), pred_node_names)
graph_io.write_graph(constant_graph, outdir, name, as_text=False)


tf.reset_default_graph()

def load_graph(model_name):
#graph = tf.Graph()
graph = tf.get_default_graph()
graph_def = tf.GraphDef()
with open(model_name, "rb") as f:
graph_def.ParseFromString(f.read())
with graph.as_default():
tf.import_graph_def(graph_def)
return graph

my_graph = load_graph(model_name=os.path.join(outdir, name))


# In[15]:

input_op = my_graph.get_operation_by_name("import/dense_1_input")
output_op = my_graph.get_operation_by_name("import/simple_nn_0")
logit_op = my_graph.get_operation_by_name("import/logits/BiasAdd")


x_hat = input_op.outputs[0] # input tensor
labels = output_op.outputs[0] # label tensor
logits = logit_op.outputs[0] # logits tensor

learning_rate = tf.placeholder(tf.float32, ())

loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=[labels])
optim_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, var_list=[x_hat])






python-3.x tensorflow keras






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 15:46

























asked Nov 9 at 15:35









David

263




263












  • One thing you could do is not to use an optimizer, but instead get the input gradient with tf.gradients and apply updates to the input outside of TensorFlow. But you can also replace the input placeholder with an actual variable, and simply load the input value that you want to optimize.
    – jdehesa
    Nov 9 at 16:15










  • Or, about the first option, you could actually use an optimizer, but only use compute_gradients, then actually apply them out of TensorFlow (I have not tried it but I think that should work, even with non-variables).
    – jdehesa
    Nov 9 at 16:31












  • Why not cast the input as variable? This should be possible,too.
    – Lau
    Nov 9 at 17:02










  • can you please show me how to do the cast?
    – David
    Nov 9 at 18:41










  • One can come out a code to do the gradient decent but it defeat the purpose of using tensorflow which suppose to simplify the procedure
    – David
    Nov 9 at 18:44


















  • One thing you could do is not to use an optimizer, but instead get the input gradient with tf.gradients and apply updates to the input outside of TensorFlow. But you can also replace the input placeholder with an actual variable, and simply load the input value that you want to optimize.
    – jdehesa
    Nov 9 at 16:15










  • Or, about the first option, you could actually use an optimizer, but only use compute_gradients, then actually apply them out of TensorFlow (I have not tried it but I think that should work, even with non-variables).
    – jdehesa
    Nov 9 at 16:31












  • Why not cast the input as variable? This should be possible,too.
    – Lau
    Nov 9 at 17:02










  • can you please show me how to do the cast?
    – David
    Nov 9 at 18:41










  • One can come out a code to do the gradient decent but it defeat the purpose of using tensorflow which suppose to simplify the procedure
    – David
    Nov 9 at 18:44
















One thing you could do is not to use an optimizer, but instead get the input gradient with tf.gradients and apply updates to the input outside of TensorFlow. But you can also replace the input placeholder with an actual variable, and simply load the input value that you want to optimize.
– jdehesa
Nov 9 at 16:15




One thing you could do is not to use an optimizer, but instead get the input gradient with tf.gradients and apply updates to the input outside of TensorFlow. But you can also replace the input placeholder with an actual variable, and simply load the input value that you want to optimize.
– jdehesa
Nov 9 at 16:15












Or, about the first option, you could actually use an optimizer, but only use compute_gradients, then actually apply them out of TensorFlow (I have not tried it but I think that should work, even with non-variables).
– jdehesa
Nov 9 at 16:31






Or, about the first option, you could actually use an optimizer, but only use compute_gradients, then actually apply them out of TensorFlow (I have not tried it but I think that should work, even with non-variables).
– jdehesa
Nov 9 at 16:31














Why not cast the input as variable? This should be possible,too.
– Lau
Nov 9 at 17:02




Why not cast the input as variable? This should be possible,too.
– Lau
Nov 9 at 17:02












can you please show me how to do the cast?
– David
Nov 9 at 18:41




can you please show me how to do the cast?
– David
Nov 9 at 18:41












One can come out a code to do the gradient decent but it defeat the purpose of using tensorflow which suppose to simplify the procedure
– David
Nov 9 at 18:44




One can come out a code to do the gradient decent but it defeat the purpose of using tensorflow which suppose to simplify the procedure
– David
Nov 9 at 18:44

















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',
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
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53228768%2fhow-to-make-a-input-tensor-trainable%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































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.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • 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.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53228768%2fhow-to-make-a-input-tensor-trainable%23new-answer', 'question_page');
}
);

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







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()