### Keras.applications源代码变动导致本地变量缺失错误

我之前用一段代码进行图像聚类,运行得很好。

import tensorflow.compat.v1 as tftf.disable_v2_behavior()config = tf.ConfigProto()config.gpu_options.allow_growth = Truesess = tf.Session(config=config)import osimport kerasfrom keras.preprocessing import imagefrom keras.applications.imagenet_utils import decode_predictions, preprocess_inputfrom keras.models import Modeldef get_pca_fingerprint(images):    # 为每张图像获取VGG-16指纹    # 我们将使用预训练的网络并让每张图像通过网络    # 我们将提取最后一层的特征向量。    # 这本质上是一个描述图像的指纹。    # 这个指纹用于执行聚类。        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("正在分析第 %d / %d 张图像。时间:%4.4f 秒。" % (i, len(images),elap))            tic = time.clock()        img, x = load_image(image_path);        feat = feat_extractor.predict(x)[0]        features.append(feat)    print('已完成提取 %d 张图像的特征' % 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

然而,某一天代码突然无法运行了:

AttributeError: module 'keras.applications' has no attribute 'VGG16'

我尝试将代码改为使用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.

我尝试调试但没有成功。谁能帮我解决这个问题?


回答:

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

改为

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注