首页 > 解决方案 > 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))

标签: pythontensorflow

解决方案


您的问题是该图是在函数调用中构造的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图中的变量时已经存在。但是您发布的代码绝对不正确。


推荐阅读