FailedPreconditionError:尝试将未初始化的值与Keras一起使用

时间:2017-07-13 10:45:17

标签: python keras

我试图调整我在博客文章中看到的NN架构:https://sorenbouma.github.io/blog/oneshot/ 我唯一想改变的是输入,而不是(105,105,1)灰度,我希望使用(100,100,3)RGB。因此,我使用Keras来定义博客文章中的架构,但输入不同:

def W_init(shape,name=None):
    """Initialize weights as in paper"""
    values = rng.normal(loc=0,scale=1e-2,size=shape)
    return K.variable(values,name=name)
#//TODO: figure out how to initialize layer biases in keras.
def b_init(shape,name=None):
    """Initialize bias as in paper"""
    values=rng.normal(loc=0.5,scale=1e-2,size=shape)
    return K.variable(values,name=name)

input_shape = (100, 100, 3)
left_input = Input(input_shape)
right_input = Input(input_shape)
#build convnet to use in each siamese 'leg'
convnet = Sequential()
convnet.add(Conv2D(64,(10,10),activation='relu',input_shape=input_shape,
                   kernel_initializer=W_init,kernel_regularizer=l2(2e-4)))
convnet.add(MaxPooling2D())
convnet.add(Conv2D(128,(7,7),activation='relu',
                   kernel_regularizer=l2(2e-4),kernel_initializer=W_init,bias_initializer=b_init))
convnet.add(MaxPooling2D())
convnet.add(Conv2D(128,(4,4),activation='relu',kernel_initializer=W_init,kernel_regularizer=l2(2e-4),bias_initializer=b_init))
convnet.add(MaxPooling2D())
convnet.add(Conv2D(256,(4,4),activation='relu',kernel_initializer=W_init,kernel_regularizer=l2(2e-4),bias_initializer=b_init))
convnet.add(Flatten())
convnet.add(Dense(4096,activation="sigmoid",kernel_regularizer=l2(1e-3),kernel_initializer=W_init,bias_initializer=b_init))
#encode each of the two inputs into a vector with the convnet
encoded_l = convnet(left_input)
encoded_r = convnet(right_input)
#merge two encoded inputs with the l1 distance between them
L1_distance = lambda x: K.abs(x[0]-x[1])
both = merge([encoded_l,encoded_r], mode = L1_distance, output_shape=lambda x: x[0])
prediction = Dense(1,activation='sigmoid',bias_initializer=b_init)(both)
siamese_net = Model(input=[left_input,right_input],output=prediction)
#optimizer = SGD(0.0004,momentum=0.6,nesterov=True,decay=0.0003)

optimizer = Adam(0.00006)
#//TODO: get layerwise learning rates and momentum annealing scheme described in paperworking
siamese_net.compile(loss="binary_crossentropy",optimizer=optimizer)

siamese_net.count_params()

然后我按照论文对我的数据进行网络训练:

#Training loop
evaluate_every = 500
loss_every=50
batch_size = 20
N_way = 20
n_val = 250
#siamese_net.load_weights("/home/soren/keras-oneshot/weights")
max_epochs = 100
for i in range(0,max_epochs):
    (inputs,targets)=loader.get_batch(batch_size)
    loss=siamese_net.train_on_batch(inputs,targets)
    if i % evaluate_every == 0:
        val_acc = loader.test_oneshot(siamese_net,N_way,n_val,verbose=True)
        if val_acc >= best:
            print("saving")
            siamese_net.save('/home/soren/keras-oneshot/weights')
            best=val_acc

    if i % loss_every == 0:
        print("iteration {}, training loss: {:.2f},".format(i,loss))

但是我得到了

 FailedPreconditionError: Attempting to use uninitialized value conv2d_1/Variable
     [[Node: conv2d_1/Variable/read = Identity[T=DT_FLOAT, _class=["loc:@conv2d_1/Variable"], _device="/job:localhost/replica:0/task:0/cpu:0"](conv2d_1/Variable)]]

这是完整的错误输出:

---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
/usr/local/lib/python3.4/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1138     try:
-> 1139       return fn(*args)
   1140     except errors.OpError as e:

/usr/local/lib/python3.4/dist-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1120                                  feed_dict, fetch_list, target_list,
-> 1121                                  status, run_metadata)
   1122 

/usr/lib/python3.4/contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

FailedPreconditionError: Attempting to use uninitialized value conv2d_1/Variable
     [[Node: conv2d_1/Variable/read = Identity[T=DT_FLOAT, _class=["loc:@conv2d_1/Variable"], _device="/job:localhost/replica:0/task:0/cpu:0"](conv2d_1/Variable)]]

During handling of the above exception, another exception occurred:

    FailedPreconditionError                   Traceback (most recent call last)
    <ipython-input-15-06f79f757a6e> in <module>()
          9 for i in range(0,max_epochs):
         10     (inputs,targets)=loader.get_batch(batch_size)
    ---> 11     loss=siamese_net.train_on_batch(inputs,targets)
         12     if i % evaluate_every == 0:
         13         val_acc = loader.test_oneshot(siamese_net,N_way,n_val,verbose=True)

    /usr/local/lib/python3.4/dist-packages/keras/engine/training.py in train_on_batch(self, x, y, sample_weight, class_weight)
       1563             ins = x + y + sample_weights
       1564         self._make_train_function()
    -> 1565         outputs = self.train_function(ins)
       1566         if len(outputs) == 1:
       1567             return outputs[0]

    /usr/local/lib/python3.4/dist-packages/keras/backend/tensorflow_backend.py in __call__(self, inputs)
       2263                 value = (indices, sparse_coo.data, sparse_coo.shape)
       2264             feed_dict[tensor] = value
    -> 2265         session = get_session()
       2266         updated = session.run(self.outputs + [self.updates_op],
       2267                               feed_dict=feed_dict,

    /usr/local/lib/python3.4/dist-packages/keras/backend/tensorflow_backend.py in get_session()
        166     if not _MANUAL_VAR_INIT:
        167         with session.graph.as_default():
    --> 168             _initialize_variables()
        169     return session
        170 

    /usr/local/lib/python3.4/dist-packages/keras/backend/tensorflow_backend.py in _initialize_variables()
        339     if uninitialized_variables:
        340         sess = get_session()
    --> 341         sess.run(tf.variables_initializer(uninitialized_variables))
        342 
        343 

    /usr/local/lib/python3.4/dist-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
        787     try:
        788       result = self._run(None, fetches, feed_dict, options_ptr,
    --> 789                          run_metadata_ptr)
        790       if run_metadata:
        791         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

    /usr/local/lib/python3.4/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
        995     if final_fetches or final_targets:
        996       results = self._do_run(handle, final_targets, final_fetches,
    --> 997                              feed_dict_string, options, run_metadata)
        998     else:
        999       results = []

    /usr/local/lib/python3.4/dist-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
       1130     if handle is None:
       1131       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
    -> 1132                            target_list, options, run_metadata)
       1133     else:
       1134       return self._do_call(_prun_fn, self._session, handle, feed_dict,

    /usr/local/lib/python3.4/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
       1150         except KeyError:
       1151           pass
    -> 1152       raise type(e)(node_def, op, message)
       1153 
       1154   def _extend_graph(self):

    FailedPreconditionError: Attempting to use uninitialized value conv2d_1/Variable
         [[Node: conv2d_1/Variable/read = Identity[T=DT_FLOAT, _class=["loc:@conv2d_1/Variable"], _device="/job:localhost/replica:0/task:0/cpu:0"](conv2d_1/Variable)]]

    Caused by op 'conv2d_1/Variable/read', defined at:
      File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
        "__main__", mod_spec)
      File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
        exec(code, run_globals)
      File "/usr/local/lib/python3.4/dist-packages/ipykernel_launcher.py", line 16, in <module>
        app.launch_new_instance()
      File "/usr/local/lib/python3.4/dist-packages/traitlets/config/application.py", line 658, in launch_instance
        app.start()
      File "/usr/local/lib/python3.4/dist-packages/ipykernel/kernelapp.py", line 477, in start
        ioloop.IOLoop.instance().start()
      File "/usr/local/lib/python3.4/dist-packages/zmq/eventloop/ioloop.py", line 177, in start
        super(ZMQIOLoop, self).start()
      File "/usr/local/lib/python3.4/dist-packages/tornado/ioloop.py", line 888, in start
        handler_func(fd_obj, events)
      File "/usr/local/lib/python3.4/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
        return fn(*args, **kwargs)
      File "/usr/local/lib/python3.4/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
        self._handle_recv()
      File "/usr/local/lib/python3.4/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
        self._run_callback(callback, msg)
      File "/usr/local/lib/python3.4/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
        callback(*args, **kwargs)
      File "/usr/local/lib/python3.4/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
        return fn(*args, **kwargs)
      File "/usr/local/lib/python3.4/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
        return self.dispatch_shell(stream, msg)
      File "/usr/local/lib/python3.4/dist-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
        handler(stream, idents, msg)
      File "/usr/local/lib/python3.4/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
        user_expressions, allow_stdin)
      File "/usr/local/lib/python3.4/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
        res = shell.run_cell(code, store_history=store_history, silent=silent)
      File "/usr/local/lib/python3.4/dist-packages/ipykernel/zmqshell.py", line 533, in run_cell
        return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
      File "/usr/local/lib/python3.4/dist-packages/IPython/core/interactiveshell.py", line 2698, in run_cell
        interactivity=interactivity, compiler=compiler, result=result)
      File "/usr/local/lib/python3.4/dist-packages/IPython/core/interactiveshell.py", line 2802, in run_ast_nodes
        if self.run_code(code, result):
      File "/usr/local/lib/python3.4/dist-packages/IPython/core/interactiveshell.py", line 2862, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-2-51595f796dab>", line 17, in <module>
        kernel_initializer=W_init,kernel_regularizer=l2(2e-4)))
      File "/usr/local/lib/python3.4/dist-packages/keras/models.py", line 436, in add
        layer(x)
      File "/usr/local/lib/python3.4/dist-packages/keras/engine/topology.py", line 569, in __call__
        self.build(input_shapes[0])
      File "/usr/local/lib/python3.4/dist-packages/keras/layers/convolutional.py", line 134, in build
        constraint=self.kernel_constraint)
      File "/usr/local/lib/python3.4/dist-packages/keras/legacy/interfaces.py", line 87, in wrapper
        return func(*args, **kwargs)
      File "/usr/local/lib/python3.4/dist-packages/keras/engine/topology.py", line 391, in add_weight
        weight = K.variable(initializer(shape), dtype=dtype, name=name)
      File "<ipython-input-2-51595f796dab>", line 4, in W_init
        return K.variable(values,name=name)
      File "/usr/local/lib/python3.4/dist-packages/keras/backend/tensorflow_backend.py", line 321, in variable
        v = tf.Variable(value, dtype=_convert_string_dtype(dtype), name=name)
      File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/ops/variables.py", line 200, in __init__
        expected_shape=expected_shape)
      File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/ops/variables.py", line 319, in _init_from_args
        self._snapshot = array_ops.identity(self._variable, name="read")
      File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1303, in identity
        result = _op_def_lib.apply_op("Identity", input=input, name=name)
      File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
        op_def=op_def)
      File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 2506, in create_op
        original_op=self._default_original_op, op_def=op_def)
      File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 1269, in __init__
        self._traceback = _extract_stack()

    FailedPreconditionError (see above for traceback): Attempting to use uninitialized value conv2d_1/Variable
         [[Node: conv2d_1/Variable/read = Identity[T=DT_FLOAT, _class=["loc:@conv2d_1/Variable"], _device="/job:localhost/replica:0/task:0/cpu:0"](conv2d_1/Variable)]]

关于错误的Googlign并没有真正说清楚。我在使用Tensorflow时看到了一些关于错误的帖子,但没有关于这个错误和Keras的内容,所以我对发生的事情感到有点困惑。

1 个答案:

答案 0 :(得分:0)

我几天前经历过同样的错误 错误的原因是重量初始化 您尝试更改以下代码。

(之前)

convnet.add(Conv2D(64,(10,10),activation='relu',input_shape=input_shape,
               kernel_initializer=W_init,kernel_regularizer=l2(2e-4)))

(后)

convnet.add(Conv2D(64,(10,10),activation='relu',input_shape=input_shape,
            kernel_initializer=keras.initializers.RandomNormal(mean=0.0, 
            stddev=1e-2, seed=None),kernel_regularizer=l2(2e-4)))

请从所有W_init和b_init更改为keras.initializers.RandomNormal(...)。