python - 尝试在 Tensorflow 中使用未初始化的值变量(使用了 sess.run(tf.global_variables_initializer()) !)

标签 python python-2.7 machine-learning tensorflow neural-network

我尝试通过将随机权重设置为零来划分我的神经网络模型和 restore() 函数。 这是型号代码:http://pastebin.com/TqN6kkeb (它工作正常)。

函数如下:

from __future__ import print_function

import tensorflow as tf
tf.GraphKeys.VARIABLES = tf.GraphKeys.GLOBAL_VARIABLES
import random
from LogReg import accuracy
from LogReg import W
from LogReg import x,y


# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)


def restore(model_file):

    with tf.Session() as sess:

        new_saver = tf.train.import_meta_graph(model_file + ".meta")
        new_saver.restore(sess, model_file)

        with tf.variable_scope("foo", reuse=True):
            temp_var = tf.get_variable("W")
            size_2a = tf.get_variable("b")

        size_2 = tf.shape(size_2a).eval()[0]
        size_1 = tf.shape(temp_var).eval()[0]

        ones_mask = tf.Variable(tf.ones([size_1, size_2]))
        arg = random.sample(xrange(size_1), size_1/2)
        index_num=tf.convert_to_tensor(arg, dtype=tf.int32)
        print("om", ones_mask)
        print("index", index_num)
        print(W)

        zeroes = tf.zeros([size_1/2, size_2])
        update = tf.scatter_update(ones_mask, index_num, zeroes)
        print(update)

        assign_op = W.assign(tf.mul(W, update))
        sess.run(update)
        sess.run(assign_op)
        init_op = tf.global_variables_initializer()
        sess.run(init_op)
        new_saver.save(sess, model_file)
        print("Accuracy_new:", accuracy.eval({x: mnist.test.images, y:mnist.test.labels}))

restore('./MyModel2')

问题是: 1)是它一直在写信给我 FailedPreconditionError(回溯见上文):尝试在此行中使用未初始化的值变量:

update = tf.scatter_update(ones_mask, index_num, zeroes)

不管怎样。我已经阅读了这些主题:Prettytensor: Attempting to use uninitialized valueUpdate a subset of weights in TensorFlow (和许多其他人),但那里的建议无助于修复我的错误。 而且我不明白,只要我运行 tf.global_variables_initializer(); 初始化有什么问题

2) 所有权重似乎都设置为零而不是一半,我不明白为什么。

请帮忙,我真的卡住了。

最佳答案

仅作记录(以及其他找到这篇文章的人),方法名称已更改,根据此处的页面:https://www.tensorflow.org/versions/r0.10/how_tos/variables/#initialization

您应该像这样运行 initialize_all_variables() 方法:

import tensorflow as tf
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

关于python - 尝试在 Tensorflow 中使用未初始化的值变量(使用了 sess.run(tf.global_variables_initializer()) !),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968605/

相关文章:

python - 什么是 X_train 和 y_train?

PHP脚本无法正确运行python脚本,但它在终端上正确运行

python - 使用cql从python插入到cassandra

python - Django:Gmail SMTP 错误:请先运行 connect()

python - 使用 openpyxl 在 python 中对齐单元格的正确方法

python - 使用 pool.map 将函数并行应用于字符串列表?

python - Python Flask 单元测试中登录测试失败

python - Scikit - SGDRegressor 不适合

python - 如何在 seaborn 中使用 'hue' 参数绘制联合图

python - 重新编码无法在 python 中以 utf-8 解码的字节