[英]Change number of input channels to pretrained keras.applications model?
[英]Change in Keras.applications source code results in error in missing variable from localhost
對於圖像聚類,我使用了一段完美運行的代碼。
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
然而,從一天到另一天,現在的可能正在失敗:
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 行為,這已經解決了問題
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.