Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Keras.applications源代码中的更改导致localhost中缺少变量的错误_Python_Tensorflow_Machine Learning_Keras_Conv Neural Network - Fatal编程技术网

Python Keras.applications源代码中的更改导致localhost中缺少变量的错误

Python Keras.applications源代码中的更改导致localhost中缺少变量的错误,python,tensorflow,machine-learning,keras,conv-neural-network,Python,Tensorflow,Machine Learning,Keras,Conv Neural Network,对于图像聚类,我使用了一段代码,它工作得非常好 import tensorflow.compat.v1 as tf tf.disable_v2_behavior() config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) import os import keras from keras.preprocessing import image from

对于图像聚类,我使用了一段代码,它工作得非常好

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)



import os
import keras
from keras.preprocessing import image
from keras.applications.imagenet_utils import decode_predictions, preprocess_input
from keras.models import Model

def get_pca_fingerprint(images):

    # GET VGG-16 FINGERPRINT FOR EACH IMAGE
    # we will use a pretrained network and run each image through
    # the network. We will pull the feature vector for the last layer.
    # This is essentially a fingerprint that describes the image.
    # This fingerprint is used to perform clustering.
    
    model = keras.applications.VGG16(weights='imagenet', include_top=True)
    feat_extractor = Model(inputs=model.input, outputs=model.get_layer("fc2").output)

    tic = time.clock()

    features = []
    for i, image_path in enumerate(images):
        if i % 500 == 0:
            toc = time.clock()
            elap = toc-tic;
            print("analyzing image %d / %d. Time: %4.4f seconds." % (i, len(images),elap))
            tic = time.clock()
        img, x = load_image(image_path);
        feat = feat_extractor.predict(x)[0]
        features.append(feat)

    print('finished extracting features for %d images' % len(images))
    
    max_comp = 300
    if len(list(images)) < max_comp:
        max_comp=5
    
    features = np.array(features)
    pca = PCA(n_components=max_comp)
    pca.fit(features)

    pca_features = pca.transform(features)

    return pca_features
我试图用tf.keras.applications.VGG16来改变它,但是出现了一大堆我无法解决的新错误:

FailedPreconditionError                   Traceback (most recent call last)

<ipython-input-28-e0d4bda5e849> in <module>()
      2 #the variable 'images' should be a list with all the paths to the images now
      3 model = tf.keras.applications.VGG16(weights='imagenet', include_top=True)
----> 4 pca_fingerprints = get_pca_fingerprint(images)

5 frames

<ipython-input-27-151877a5d62b> in get_pca_fingerprint(images)
     46             tic = time.clock()
     47         img, x = load_image(image_path);
---> 48         feat = feat_extractor.predict(x)[0]
     49         features.append(feat)
     50 

/usr/local/lib/python3.7/dist-packages/keras/engine/training_v1.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
    978         max_queue_size=max_queue_size,
    979         workers=workers,
--> 980         use_multiprocessing=use_multiprocessing)
    981 
    982   def reset_metrics(self):

/usr/local/lib/python3.7/dist-packages/keras/engine/training_arrays_v1.py in predict(self, model, x, batch_size, verbose, steps, callbacks, **kwargs)
    703         verbose=verbose,
    704         steps=steps,
--> 705         callbacks=callbacks)

/usr/local/lib/python3.7/dist-packages/keras/engine/training_arrays_v1.py in model_iteration(model, inputs, targets, sample_weights, batch_size, epochs, verbose, callbacks, val_inputs, val_targets, val_sample_weights, shuffle, initial_epoch, steps_per_epoch, validation_steps, validation_freq, mode, validation_in_fit, prepared_feed_values_from_dataset, steps_name, **kwargs)
    374 
    375         # Get outputs.
--> 376         batch_outs = f(ins_batch)
    377         if not isinstance(batch_outs, list):
    378           batch_outs = [batch_outs]

/usr/local/lib/python3.7/dist-packages/keras/backend.py in __call__(self, inputs)
   4018 
   4019     fetched = self._callable_fn(*array_vals,
-> 4020                                 run_metadata=self.run_metadata)
   4021     self._call_fetch_callbacks(fetched[-len(self._fetches):])
   4022     output_structure = tf.nest.pack_sequence_as(

/usr/local/lib/python3.7/dist-packages/tensorflow/python/client/session.py in __call__(self, *args, **kwargs)
   1480         ret = tf_session.TF_SessionRunCallable(self._session._session,
   1481                                                self._handle, args,
-> 1482                                                run_metadata_ptr)
   1483         if run_metadata:
   1484           proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

FailedPreconditionError: 2 root error(s) found.
  (0) Failed precondition: Could not find variable fc1_15/kernel. This could mean that the variable has been deleted. In TF1, it can also mean the variable is uninitialized. Debug info: container=localhost, status=Not found: Container localhost does not exist. (Could not find resource: localhost/fc1_15/kernel)
     [[{{node fc1_15/MatMul/ReadVariableOp}}]]
     [[fc2_15/Relu/_27]]
  (1) Failed precondition: Could not find variable fc1_15/kernel. This could mean that the variable has been deleted. In TF1, it can also mean the variable is uninitialized. Debug info: container=localhost, status=Not found: Container localhost does not exist. (Could not find resource: localhost/fc1_15/kernel)
     [[{{node fc1_15/MatMul/ReadVariableOp}}]]
0 successful operations.
0 derived errors ignored.
FailedPremissionError回溯(最近一次调用)
在()
2#变量“images”应该是一个列表,其中包含指向图像的所有路径
3 model=tf.keras.applications.VGG16(weights='imagenet',include_top=True)
---->4 pca\u指纹=获取pca\u指纹(图像)
5帧
在获取pca指纹(图像)中
46 tic=time.clock()
47 img,x=加载图像(图像路径);
--->48专长=专长提取器。预测(x)[0]
49特征。附加(专长)
50
/预测中的usr/local/lib/python3.7/dist-packages/keras/engine/training\u v1.py(self、x、批处理大小、冗余、步骤、回调、最大队列大小、工作人员、使用多处理)
978最大队列大小=最大队列大小,
979名工人=工人,
-->980使用多处理=使用多处理)
981
982 def重置_指标(自我):
/预测中的usr/local/lib/python3.7/dist-packages/keras/engine/training_arrays_v1.py(self、model、x、批量大小、详细程度、步骤、回调、**kwargs)
703详细=详细,
704步=步,
-->705回调=回调)
/模型迭代中的usr/local/lib/python3.7/dist-packages/keras/engine/training\u arrays\u v1.py(模型、输入、目标、样本权重、批量大小、年代、详细程度、回调、val_输入、val_目标、val_样本权重、无序、初始历元、每历元步长、验证步骤、验证频率、模式、验证拟合、从数据集准备的反馈值、步骤名称、**kwargs)
374
375#获取输出。
-->376批次输出=f(批次输入)
377如果不存在(批次,列表):
378批次输出=[批次输出]
/usr/local/lib/python3.7/dist-packages/keras/backend.py在调用中(self,输入)
4018
4019 fetched=self.\u callable\u fn(*数组\u vals,
->4020运行单元元数据=self.run单元元数据)
4021 self.\u call\u fetch\u callbacks(fetched[-len(self.\u fetches):]))
4022输出\u结构=tf.nest.pack\u序列\u as(
/usr/local/lib/python3.7/dist-packages/tensorflow/python/client/session.py in_u_调用(self,*args,**kwargs)
1480 ret=tf_session.tf_SessionRunCallable(self._session._session,
1481自动控制手柄,args,
->1482运行元数据(ptr)
1483如果运行\u元数据:
1484 proto_data=tf_session.tf_GetBuffer(run_metadata_ptr)
FailedPremissionError:发现2个根错误。
(0)失败的前提条件:找不到变量fc1_15/kernel。这可能意味着该变量已被删除。在TF1中,这也可能意味着该变量未初始化。调试信息:container=localhost,status=not found:container localhost不存在。(找不到资源:localhost/fc1_15/kernel)
[{{node fc1_15/MatMul/ReadVariableOp}}]
[[fc2_15/Relu/_27]]
(1) 失败的前提条件:找不到变量fc1_15/kernel。这可能意味着该变量已被删除。在TF1中,也可能意味着该变量未初始化。调试信息:container=localhost,status=not found:container localhost不存在。(找不到资源:localhost/fc1_15/kernel)
[{{node fc1_15/MatMul/ReadVariableOp}}]
0成功的操作。
忽略0个派生错误。

我尝试了调试,但没有效果。谁能帮我解决问题?

我切换到TF2,而不是禁用v2行为,这解决了问题

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)


您的keras/TF设置是否可能以某种方式被破坏了?代码在我看来还行,我看不出它会破坏您描述的方式的原因(在Colab上的快速测试表明keras的VGG16模型似乎可以工作…).老实说,代码中没有任何更改,我有3或4个脚本在所有函数中放置,现在它们都被相同的错误消息破坏..我将尝试深入一点,但无法理解错误的核心错误抱怨某些变量丢失,这几乎是胡说八道(这就是为什么我怀疑你的库设置不知怎么搞砸了)我在Google Colab中运行了我所有的脚本,他们的库设置是动态的并且总是更新的,我猜它一定是在某个地方发生了变化。。
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
import tensorflow as tf
config = tf.compat.v1.ConfigProto

#and loading VGG16 as
tf.keras.applications.VGG16(weights='imagenet', include_top=True)