python - TensorFlow 中可训练变量和不可训练变量的串联

标签 python tensorflow

假设变量 A 的形状为 [123, 64],变量 B 的形状为 [123, 32],那么 A 和 B 的串联 tf.concat([A, B], axis=1) 可以创建变量 C形状为 [123, 96]

假设 A 被创建为可训练,B 被创建为不可训练。 C 是 A 和 B 沿轴 1 的串联。

在优化损失时,这样创建的变量C怎么样?

  1. C 是可训练的
  2. C 是不可训练的
  3. 恰好 C 的前 64 列是可训练的,而 C 的后 32 列是不可训练的。

最佳答案

您可以自行检查C 变量是否可训练,但首先您必须创建变量C

连接操作返回一个连接操作,因此不是变量(因此不可训练)。因此,您必须将结果包装到 tf.Variable 中以查看它是否可训练(因为您创建了一个新变量)。

import tensorflow as tf
a = tf.get_variable("a", (123,64))
b = tf.get_variable("b", (123, 32), trainable=False)
c = tf.concat((a,b), axis=1)
# c is an operation, hence it's not trainable
d = tf.Variable(c)
# d is a Variable created with the content of d, hence trainable
trainable = d.name in [x.name for x in tf.trainable_variables()]

只是一个简短的说明。我认为强调“(它会因为你创建了一个新变量)”部分真的很重要。 C 本身永远不会是一个可训练的变量,它的任何“部分”也不会是可训练的,它只是一个中间张量。唯一可训练的变量是 A 本身。

关于python - TensorFlow 中可训练变量和不可训练变量的串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49975340/

相关文章:

python - 如何在不进行赋值和组合的情况下更改 lambda 表达式的功能?

python - 使用 Keras 生成 LSTM 文本 : What is diversity?

python - tensorflow 导入导致numpy计算错误

tensorflow - 将张量输入 CNN 时是否应该转置它

python - 在seaborn中可视化直方图

javascript - Flask,在 Javascript 中提供静态文件和/或文件夹

python - 从 Django 模型生成分层 JSON 树结构

python - 如何在 Windows 上的 Docker 中运行带有 Tensorflow 的 python 脚本?

tensorflow - 在序列模型中使用填充时,Keras 验证准确性是否有效/可靠?

python - 使用 tf.Estimator 创建的 tensorflow 服务的图形优化