- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要使用 tf.gradients() 获取权重和偏差的梯度:
x = tf.placeholder(tf.float32, [batch_size, x_train.shape[1]])
y = tf.placeholder(tf.float32, [batch_size, y_train.shape[1]])
y_ = tf.placeholder(tf.float32, [batch_size, y_train.shape[1]])
Wx=tf.Variable(tf.random_normal(stddev=0.1,shape=[x_train.shape[1],n_hidden]))
Wy=tf.Variable(tf.random_normal(stddev=0.1,shape=[y_train.shape[1],n_hidden]))
b=tf.Variable(tf.constant(0.1,shape=[n_hidden]))
hidden_joint=tf.nn.relu((tf.matmul(x,Wx)+tf.matmul(y,Wy))+b)
hidden_marg=tf.nn.relu(tf.matmul(x,Wx)+tf.matmul(y_,Wy)+b)
Wout=tf.Variable(tf.random_normal(stddev=0.1,shape=[n_hidden, 1]))
bout=tf.Variable(tf.constant(0.1,shape=[1]))
out_joint=tf.matmul(hidden_joint,Wout)+bout
out_marg=tf.matmul(hidden_marg,Wout)+bout
optimizer = tf.train.AdamOptimizer(0.005)
t = out_joint
et = tf.exp(out_marg)
ex_delta_t = tf.reduce_mean(tf.gradients(t, tf.trainable_variables()))
ex_delta_et = tf.reduce_mean(tf.gradients(et, tf.trainable_variables()))
但我总是收到以下错误:
File "/home/ferdi/Documents/mine/mine.py", line 77, in get_mi_batched
ex_delta_t = tf.reduce_mean(tf.gradients(t, tf.trainable_variables()))
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 1490, in reduce_mean
reduction_indices),
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 1272, in _ReductionDims
return range(0, array_ops.rank(x))
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 368, in rank
return rank_internal(input, name, optimize=True)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 388, in rank_internal
input_tensor = ops.convert_to_tensor(input)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1048, in convert_to_tensor
as_ref=False)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1144, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 971, in _autopacking_conversion_function
return _autopacking_helper(v, dtype, name or "packed")
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 923, in _autopacking_helper
return gen_array_ops.pack(elems_as_tensors, name=scope)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 4689, in pack
"Pack", values=values, axis=axis, name=name)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3272, in create_op
op_def=op_def)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1790, in __init__
control_input_ops)
File "/home/ferdi/anaconda3/envs/ml_all/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1629, in _create_c_op
raise ValueError(str(e))
ValueError: Shapes must be equal rank, but are 2 and 1
From merging shape 3 with other shapes. for 'Rank/packed' (op: 'Pack') with input shapes: [512,20], [10,20], [20], [20,1], [1].
如果我 reshape 或执行类似的操作,则会发生其他错误。我知道有很多类似的问题,但我仍然无法弄清楚。我做错了什么?
最佳答案
解决方案:
ex_delta_t = tf.reduce_mean( tf.concat([tf.reshape(g, [-1]) for g in tf.gradients(t, tf.trainable_variables())], axis=0))
ex_delta_et = tf.reduce_mean( tf.concat([tf.reshape(g, [-1]) for g in tf.gradients(et, tf.trainable_variables())], axis=0))
或者展开相同的代码:
grads_t_0 = tf.gradients(t, tf.trainable_variables())
grads_et_0 = tf.gradients(t, tf.trainable_variables())
grads_t = []
grads_et = []
for gt,get in zip(grads_t_0, grads_et_0):
grads_t.append(tf.reshape(gt, [-1]))
grads_et.append(tf.reshape(get, [-1]))
grads_t_flatten = tf.concat(grads_t, axis=0)
grads_et_flatten = tf.concat(grads_et, axis=0)
ex_delta_t = tf.reduce_mean(grads_t_flatten)
ex_delta_et = tf.reduce_mean(grads_et_flatten)
说明:
您可能会收到此错误消息,因为您的梯度函数
tf.gradients(t, tf.trainable_variables())
tf.gradients(et, tf.trainable_variables()
返回多重形状的张量。因此,您的 tf.reduce_mean() 操作会提示它无法处理这种多重形状的张量。
作为解决此问题的一种可能性,您应该首先展平而不是连接渐变列表,然后将其传递给 reduce_mean 函数。
Let's see a simple example code to simulate the error and its solution!
#You dummy gradients as the output of tf.gradients()
grad_wx = tf.constant(0.1, shape=[512, 20])
grad_wy = tf.constant(0.2, shape=[10, 20])
grad_b = tf.constant(0.3, shape=[20])
grad_wout = tf.constant(0.4, shape=[20, 1])
grad_bout = tf.constant(0.5, shape=[1])
grads_0 = [grad_wx, grad_wy, grad_b, grad_wout, grad_bout]
sess = tf.Session()
result = tf.reduce_mean(grads_0)
print(sess.run(result)
输出(错误):
ValueError: Shapes must be equal rank, but are 2 and 1
From merging shape 3 with other shapes. for 'Rank/packed' (op: 'Pack') with input shapes: [512,20], [10,20], [20], [20,1], [1].
解决方案:
result = tf.reduce_mean( tf.concat([tf.reshape(g, [-1]) for g in grads_0], axis=0))
print(sess.run(result))
输出(已修复):
0.102899365
关于python - tf.gradients : ValueError: Shapes must be equal rank, 但分别是 2 和 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53306907/
在 Tensorflow(从 v1.2.1 开始)中,似乎有(至少)两个并行 API 来构建计算图。 tf.nn 中有函数,如 conv2d、avg_pool、relu、dropout,tf.laye
我正在处理眼睛轨迹数据和卷积神经网络。我被要求使用 tf.reduce_max(lastconv, axis=2)代替 MaxPooling 层和 tf.reduce_sum(lastconv,axi
TensorFlow 提供了 3 种不同的数据存储格式 tf.train.Feature .它们是: tf.train.BytesList tf.train.FloatList tf.train.In
我正在尝试为上下文强盗问题 (https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part
我在使用 Tensorflow 时遇到问题: 以下代码为卷积 block 生成正确的图: def conv_layer(self, inputs, filter_size = 3, num_filte
我正在将我的训练循环迁移到 Tensorflow 2.0 API .在急切执行模式下,tf.GradientTape替换 tf.gradients .问题是,它们是否具有相同的功能?具体来说: 在函数
tensorflow 中 tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)) 的目的是什么? 更多上下文:
我一直在努力学习 TensorFlow,我注意到不同的函数用于相同的目标。例如,为了平方变量,我看到了 tf.square()、tf.math.square() 和 tf.keras.backend.
我正在尝试使用自动编码器开发图像着色器。有 13000 张训练图像。如果我使用 tf.data,每个 epoch 大约需要 45 分钟,如果我使用 tf.utils.keras.Sequence 大约
我尝试按照 tensorflow 教程实现 MNIST CNN 神经网络,并找到这些实现 softmax 交叉熵的方法给出了不同的结果: (1) 不好的结果 softmax = tf.nn.softm
其实,我正在coursera上做deeplearning.ai的作业“Art Generation with Neural Style Transfer”。在函数 compute_layer_styl
训练神经网络学习“异或” 我正在尝试使用“批量归一化”,我创建了一个批量归一化层函数“batch_norm1”。 import tensorflow as tf import nump
我正在尝试协调来自 TF“图形和 session ”指南以及 TF“Keras”指南和 TF Estimators 指南的信息。现在在前者中它说 tf.Session 使计算图能够访问物理硬件以执行图
我正在关注此处的多层感知器示例:https://github.com/aymericdamien/TensorFlow-Examples我对函数 tf.nn.softmax_cross_entropy
回到 TensorFlow = 2.0 中消失了。因此,像这样的解决方案...... with tf.variable_scope("foo"): with tf.variable_scope
我按照官方网站中的步骤安装了tensorflow。但是,在该网站中,作为安装的最后一步,他们给出了一行代码来“验证安装”。但他们没有告诉这段代码会给出什么输出。 该行是: python -c "imp
代码: x = tf.constant([1.,2.,3.], shape = (3,2,4)) y = tf.constant([1.,2.,3.], shape = (3,21,4)) tf.ma
我正在尝试从 Github 训练一个 3D 分割网络.我的模型是用 Keras (Python) 实现的,这是一个典型的 U-Net 模型。模型,总结如下, Model: "functional_3"
我正在使用 TensorFlow 2。我正在尝试优化一个函数,该函数使用经过训练的 tensorflow 模型(毒药)的损失。 @tf.function def totalloss(x): x
试图了解 keras 优化器中的 SGD 优化代码 (source code)。在 get_updates 模块中,我们有: # momentum shapes = [K.int_shape(p) f
我是一名优秀的程序员,十分优秀!