使用 Tensorflow 训练时修改张量的值 [英] Modify the value of a tensor when training with Tensorflow
问题描述
我想在使用 Tensorflow 训练模型时修改张量的值.
I want to modify the value of a tensor when I am training my model with Tensorflow.
这个张量是我模型中的张量之一
This tensor is one of the tensors in my model
weight = tf.Variable(np_matrix)
经过一些迭代后,weight
的值会自动更新.
After some iterations, the value of weight
will be updated automatically.
我的问题是:如何非自动修改 weight
的值.我已经尝试过这种方法,但没有奏效.
My question is: How can I modify the value of weight
nonautomatically. I have tried this method but it didn't work.
modify_weight = sess.run([weight], feed_dict = feed_dict)
modify_weight[0] = [0, 0]
weight = tf.Variable(modify_weight)
这部分代码在 tf.Session()
部分(因为我想在训练期间修改值.)
This part code is in tf.Session()
section(since I want to modify the value during the training time.)
谢谢!
推荐答案
和其他一切一样,赋值也是一个操作,我们必须用 tf.assign
并在会话中运行它.
Like everything else, also the assignment is an operation, and we have to create a graph with the tf.assign
and run it in a session.
所以你创建一个这样的操作:
So you you create an operation like this:
assign = tf.assign(weight, value)
其中 value
是一个 numpy
数组,其形状与 weight
(或一个 tf.Placeholder
您可以使用提要字典进行修改)然后在会话中运行此图:
where value
is a numpy
array with the same shape of weight
(or a tf.Placeholder
that you can modify with a feed dictionary) then you run this graph in the session:
sess.run(assign)
tf.Variable
也有一个方法assign
,因此你可以直接从变量开始创建操作:
The tf.Variable
also has a method assign
, thus you can directly create the operation starting from the variable:
assign = weight.assign(value)
然后在会话中运行它.
这篇关于使用 Tensorflow 训练时修改张量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!