是否可以通过仅更改变量的某些元素来最小化损失函数?换句话说,如果我有一个长度为2的变量X
,我如何通过更改X[0]
并保持X[1]
不变来最小化我的损失函数?
希望我尝试过的代码能够描述我的问题:
import tensorflow as tf
import tensorflow.contrib.opt as opt
X = tf.Variable([1.0, 2.0])
X0 = tf.Variable([3.0])
Y = tf.constant([2.0, -3.0])
scatter = tf.scatter_update(X, [0], X0)
with tf.control_dependencies([scatter]):
loss = tf.reduce_sum(tf.squared_difference(X, Y))
opt = opt.ScipyOptimizerInterface(loss, [X0])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
opt.minimize(sess)
print("X: {}".format(X.eval()))
print("X0: {}".format(X0.eval()))
输出:
INFO:tensorflow:Optimization terminated with:
Message: b'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
Objective function value: 26.000000
Number of iterations: 0
Number of functions evaluations: 1
X: [3. 2.]
X0: [3.]
我希望在哪里找到X0 = 2
的最佳值,从而找到X = [2, 2]
修改
这样做的动机:我想导入训练有素的图形/模型,然后根据我的一些新数据调整一些变量的各种元素。
答案 0 :(得分:5)
您可以使用此技巧将渐变计算限制为一个索引:
import tensorflow as tf
import tensorflow.contrib.opt as opt
X = tf.Variable([1.0, 2.0])
part_X = tf.scatter_nd([[0]], [X[0]], [2])
X_2 = part_X + tf.stop_gradient(-part_X + X)
Y = tf.constant([2.0, -3.0])
loss = tf.reduce_sum(tf.squared_difference(X_2, Y))
opt = opt.ScipyOptimizerInterface(loss, [X])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
opt.minimize(sess)
print("X: {}".format(X.eval()))
part_X
成为您想要在与X相同形状的单热矢量中更改的值。part_X + tf.stop_gradient(-part_X + X)
与正向传递中的X相同,因为part_X - part_X
是但是在向后传递中,tf.stop_gradient
会阻止所有不必要的梯度计算。
答案 1 :(得分:2)
我不确定是否可以使用SciPy优化器接口,但是使用常规tf.train.Optimizer
子类之一,您可以先调用compute_gradients
,然后屏蔽渐变和然后打电话给apply_gradients
,
而不是调用minimize
(正如文档所说,基本上调用以前的那些)。
-(void)viewDidLayoutSubviews
if(once)
{
once = No;
CALayer *featureLayer = [[CALayer alloc]init];
featureLayer.borderWidth=3;
featureLayer.backgroundColor=[[UIColor orangeColor]CGColor];
featureLayer.opacity = 0.5;
featureLayer.position = CGPointMake(0, 0);
[featureLayer setFrame:self.cardHolder.frame];
[self.videoPreviewLayer addSublayer:featureLayer]
}
}
输出:
import tensorflow as tf
X = tf.Variable([3.0, 2.0])
# Select updatable parameters
X_mask = tf.constant([True, False], dtype=tf.bool)
Y = tf.constant([2.0, -3.0])
loss = tf.reduce_sum(tf.squared_difference(X, Y))
opt = tf.train.GradientDescentOptimizer(learning_rate=0.1)
# Get gradients and mask them
((X_grad, _),) = opt.compute_gradients(loss, var_list=[X])
X_grad_masked = X_grad * tf.cast(X_mask, dtype=X_grad.dtype)
# Apply masked gradients
train_step = opt.apply_gradients([(X_grad_masked, X)])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(10):
_, X_val = sess.run([train_step, X])
print("Step {}: X = {}".format(i, X_val))
print("Final X = {}".format(X.eval()))
答案 2 :(得分:1)
使用var_list
函数的minimize
参数应该很容易做到。
trainable_var = X[0]
train_op = tf.train.GradientDescentOptimizer(learning_rate=1e-3).minimize(loss, var_list=[trainable_var])
您应该注意,按惯例,所有可训练变量都会添加到tensorflow默认集合GraphKeys.TRAINABLE_VARIABLES
中,因此您可以使用以下命令获取所有可训练变量的列表:
all_trainable_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
这只是一个变量列表,您可以根据需要进行操作并将其用作var_list
参数。
作为您问题的切线,如果您想进一步自定义优化过程,您还可以使用grads = tf.gradients(loss, var_list)
手动计算渐变,并根据需要操作渐变,然后调用{{1} }。最小化只是为你做这两个步骤。
另请注意,您可以完全自由地为不同的变量集合创建不同的优化器。您可以为某些变量创建一个学习率为1e-4的SGD优化器,为另一组变量创建另一个学习率为1e-2的Adam优化器。并不是说有任何具体的用例,我只是指出你现在的灵活性。
答案 3 :(得分:0)
Oren在下面第二个链接中给出的答案调用了一个函数(在第一个链接中定义),该函数采用要优化的参数和参数张量的布尔热矩阵。它使用stop_gradient并像我开发的神经网络的魅力一样工作。