我创建了一个具有 3 个输入和一个输出的单个节点,偏置为 0,没有激活函数。据我所知,这里唯一发生的事情是输入向量和随机初始化权重之间的矩阵乘法,但是当我自己用相同的输入和权重进行乘法时,我得到了不同的结果?我错过了什么/做错了什么?
提前致谢!
我的计算基于这里提供的一些代码
这是代码:
def example_code(self):
import tensorflow as tf
data = [[1.0,2.0,3.0]]
x = tf.placeholder(tf.float32,shape=[1,3],name="mydata")
node = tf.layers.Dense(units=1)
y = node(x)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
print("input: "+str(data))
outcome = sess.run(y,feed_dict={x:data})
#print("outcome from tensorflow: "+str(outcome))
weights = node.get_weights()[0]
bias = node.get_weights()[1]
print("weights: "+str(weights))
print("bias: "+str(bias))
print("outcome from tensorflow: " + str(outcome))
outcome = tf.matmul(data,weights)
print("manually calculated outcome: "+str(sess.run(outcome)))
代码输出:
input: [[1.0, 2.0, 3.0]]
weights: [[ 0.72705185] [-0.70188504] [ 0.5336163 ]]
bias: [0.]
outcome from tensorflow: [[-1.3463312]]
manually calculated outcome: [[0.9241307]]
问题是tf.layers
不使用 uses 不使用您的 session sess
。这反过来导致权重的不同初始化,因此两个不同的值。tf.layers
最终tf.keras.backend.get_session()
用于检索用于初始化和检索权重 ( node.get_weights()
)的会话。tf.keras.backend.get_session()
如果有,则尝试使用默认会话,如果没有,则创建自己的会话。在这种情况下,sess
未配置为默认会话(仅tf.InteractiveSession
在构建时自动配置为默认会话)。最简单的解决方法是以tf.Session
推荐的方式使用,作为上下文管理器:
def example_code(self):
import tensorflow as tf
with tf.Session() as sess:
data = [[1.0,2.0,3.0]]
x = tf.placeholder(tf.float32,shape=[1,3],name="mydata")
node = tf.layers.Dense(units=1)
y = node(x)
init = tf.global_variables_initializer()
sess.run(init)
print("input: "+str(data))
outcome = sess.run(y,feed_dict={x:data})
#print("outcome from tensorflow: "+str(outcome))
weights = node.get_weights()[0]
bias = node.get_weights()[1]
print("weights: "+str(weights))
print("bias: "+str(bias))
print("outcome from tensorflow: " + str(outcome))
outcome = tf.matmul(data,weights)
print("manually calculated outcome: "+str(sess.run(outcome)))
这将设置sess
为默认会话,并且还将确保在函数完成时释放其资源(这是您代码中的另一个问题)。如果出于某种原因您想使用某个会话作为默认值但不想使用上下文管理器关闭它,您可以使用as_default()
:
def example_code(self):
import tensorflow as tf
sess = tf.Session():
with sess.as_default():
data = [[1.0,2.0,3.0]]
x = tf.placeholder(tf.float32,shape=[1,3],name="mydata")
node = tf.layers.Dense(units=1)
y = node(x)
init = tf.global_variables_initializer()
sess.run(init)
print("input: "+str(data))
outcome = sess.run(y,feed_dict={x:data})
#print("outcome from tensorflow: "+str(outcome))
weights = node.get_weights()[0]
bias = node.get_weights()[1]
print("weights: "+str(weights))
print("bias: "+str(bias))
print("outcome from tensorflow: " + str(outcome))
outcome = tf.matmul(data,weights)
print("manually calculated outcome: "+str(sess.run(outcome)))
# You need to manually ensure that the session gets closed after
sess.close()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句