我正在尝试从 this site 开始熟悉 TensorFlow 框架通过使用线性回归(LR)。 LR的源码可以找到here ,名称为 03_linear_regression_sol.py
。
一般来说,LR的定义模型是Y_predicted = X * w + b
,其中
w
和b
是参数 (tf.Variable
)Y_predicted
和X
是训练数据(占位符
)
对于w
和b
,在示例代码中,它们的定义如下
w = tf.Variable(0.0, name='weights')
b = tf.Variable(0.0, name='bias')
我对这两行代码做了一些修改,如下
w = tf.get_variable('weights', [], dtype=tf.float32)
b = tf.get_variable('bias', [], dtype=tf.float32)
对于这个实验,我为这两个版本获得了两个不同的total_loss/n_samples
。更具体地说,在原始版本中,我随时得到确定性结果,1539.0050282141283
。但是,在修改后的版本中,我在不同的运行时间得到了不确定的结果,例如,total_loss/n_samples
可能是1531.3039793868859
、1526.3752814714044
、。 ..等等
tf.Variable()
和 tf.get_variable()
有什么区别?
最佳答案
tf.Variable
在创建时接受初始值(常量),这解释了使用它时的确定性结果。
tf.get_variable
略有不同:它有一个 initializer
参数,默认为 None
,解释如下:
If
initializer
isNone
(the default), the default initializer passed in the variable scope will be used. If that one isNone
too, aglorot_uniform_initializer
will be used.
由于您没有传递初始值设定项,因此变量获得了统一的随机初始值。
关于python - 使用 tf.Variable() 和 tf.get_variable() 时的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46774412/