我正在阅读用于文本分类的CNN模型code link,我在第70行想知道代码:
b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
为什么它可以同时定义为变量和常量?这等于:
b = tf.Variable(0.1, shape=[num_classes], name="b")
答案 0 :(得分:1)
是的,两者都是一样的。 Tensorflow隐式将tf.constant值复制到tf.Variable值。操作a.op,b.op和c.op解释一切
import tensorflow as tf
with tf.Session() as sess:
a=tf.constant(0.1);
b = tf.Variable(tf.constant(0.1), name="b");
c = tf.Variable(0.1, name="b");
sess.run(tf.global_variables_initializer());
print(a.dtype);
print(b.dtype);
print(c.dtype);
print("**********************")
print(a.op);
print(b.op);
print(c.op);
输出:
<dtype: 'float32'>
<dtype: 'float32_ref'>
<dtype: 'float32_ref'>
**********************
name: "Const_40"
op: "Const"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_FLOAT
tensor_shape {
}
float_val: 0.10000000149
}
}
}
name: "b_38"
op: "VariableV2"
attr {
key: "container"
value {
s: ""
}
}
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "shape"
value {
shape {
}
}
}
attr {
key: "shared_name"
value {
s: ""
}
}
name: "b_39"
op: "VariableV2"
attr {
key: "container"
value {
s: ""
}
}
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "shape"
value {
shape {
}
}
}
attr {
key: "shared_name"
value {
s: ""
}
}