python - Tensorflow 初始化变量
问题描述
到目前为止,我只想查看我的输出,但我无法初始化我的变量,相同的功能在另一个笔记本中有效,但在这个笔记本中无效。我尝试了两种方法并不断得到:
FailedPreconditionError: Attempting to use uninitialized value Variable.
我正在使用 1.2.1。
mnist = input_data.read_data_sets('./', one_hot=True)
n1=500
n2=300
nclasses=10
batchsize=100
def layers(data):
layer1={'weights':tf.Variable(tf.random_normal([784,n1])),
'bias':tf.Variable(tf.random_normal([n1]))}
layer2={'weights':tf.Variable(tf.random_normal([n1,n2])),
'bias':tf.Variable(tf.random_normal([n2]))}
output={'weights':tf.Variable(tf.random_normal([n2,nclasses])),
'bias':tf.Variable(tf.random_normal([nclasses]))}
l1=tf.add(tf.matmul(data,layer1['weights']),layer1['bias'])
l1=tf.nn.relu(l1)
l2=tf.add(tf.matmul(l1,layer2['weights']),layer2['bias'])
l2=tf.nn.relu(l2)
output=tf.add(tf.matmul(l2,output['weights']),output['bias'])
return output
session=tf.Session().
session.run(tf.global_variables_initializer())
result=session.run(layers(mnist.test.images))
print(type(result))
也试过了——
with tf.Session() as sess:
session.run(tf.global_variables_initializer())
result=sess.run(layers(mnist.test.images))
print(type(result))
解决方案
您的问题是该图是在函数调用中构造的layers
。但是您在构建图形之前初始化了所有变量。
因此,你需要写
output_op = layers(mnist.test.images)
session.run(tf.global_variables_initializer())
result = session.run(output_op)
操作)
然后构建图,TensorFlow 可以初始化所有变量。完整的工作示例:
import tensorflow as tf
import numpy as np
def fake_mnist():
return np.random.randn(1, 28 * 28)
n1 = 500
n2 = 300
nclasses = 10
batchsize = 100
def layers(data):
layer1 = {'weights': tf.Variable(tf.random_normal([784, n1])),
'bias': tf.Variable(tf.random_normal([n1]))}
layer2 = {'weights': tf.Variable(tf.random_normal([n1, n2])),
'bias': tf.Variable(tf.random_normal([n2]))}
output = {'weights': tf.Variable(tf.random_normal([n2, nclasses])),
'bias': tf.Variable(tf.random_normal([nclasses]))}
l1 = tf.add(tf.matmul(data, layer1['weights']), layer1['bias'])
l1 = tf.nn.relu(l1)
l2 = tf.add(tf.matmul(l1, layer2['weights']), layer2['bias'])
l2 = tf.nn.relu(l2)
output = tf.add(tf.matmul(l2, output['weights']), output['bias'])
return output
with tf.Session() as sess:
data_inpt = tf.placeholder(tf.float32)
output_op = layers(data_inpt)
sess.run(tf.global_variables_initializer())
result = sess.run(output_op, {data_inpt: fake_mnist()})
print(type(result))
print(result)
我非常怀疑您的代码是否在任何其他笔记本文件中运行。我猜在另一个笔记本文件中,您已经多次执行单元格,layers
以便在第二次调用tf.global_variables_initializer
图中的变量时已经存在。但是您发布的代码绝对不正确。
推荐阅读
- jquery - 从 Woocommerce 可变产品中获取当前选择的变体和数据
- python - 在 AWS Lambda 函数中进行 REST API 调用的标准方法是什么?
- ruby-on-rails - 检索和显示 Active Record 数据
- android - Xamarin.Forms:调试器在 GetPositionAsync() 处停止?
- html - 如何将我的图像与内联块中的文本对齐?
- react-native - 我有一个使用 react-navigation 3.3.0 的堆栈导航器,我想要一个特定屏幕的抽屉导航
- android - How do I read the value of my RadioGroup in an AlertDialog?
- javascript - 如何在共享主机上部署 NuxtJS 项目?
- javascript - Using the isAbsolute() function in Javascript not working as expected
- javascript - 有没有办法在不使用标记名的情况下调用 HTML 元素?