图像分类器“节点”对象没有属性“输出掩码”

时间:2019-12-09 05:00:43

标签: python

hiya很高兴我一直在为大学做这个图像分类器项目,而我一直在如何使用模型和使用什么代码方面遇到麻烦,如果我做的一切正确,我一直在阅读此书,但我仍然不知道为什么我会不断出错https://keras.io/applications/#vgg16

我使用这些代码

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
from PIL import ImageFile, Image
from tensorflow import keras

print(Image.__file__)
import numpy
import matplotlib.pyplot as plt

# dimensions of our images.
img_width, img_height = 200, 200

train_data_dir = r'C:\Users\Acer\imagerec\Brain\TRAIN'
validation_data_dir = r'C:\Users\Acer\imagerec\Brain\VAL'
nb_train_samples = 140
nb_validation_samples = 40
epochs = 20
batch_size = 5

if K.image_data_format() == 'channels_first':
    input_shape = (1, img_height, img_width)
else:
    input_shape = (img_height, img_width, 1)

from keras.applications.densenet import DenseNet121
from keras.models import Model
from keras.layers import Dense

MN = keras.applications.densenet.DenseNet121(include_top=False,
                                            weights='imagenet', input_tensor=None, input_shape=None,
                                            pooling='avg', classes=1000)
x = MN.output
x = Dense(1, activation='sigmoid')(x)
model = Model(MN.input, x)
model.summary()

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
import seaborn as sns

test_steps_per_epoch = numpy.math.ceil(validation_generator.samples / validation_generator.batch_size)

predictions = model.predict_generator(validation_generator, steps=test_steps_per_epoch)
# Get most likely class
predicted_classes = numpy.argmax(predictions, axis=1)
true_classes = validation_generator.classes
class_labels = list(validation_generator.class_indices.keys())
report = classification_report(true_classes, predicted_classes, target_names=class_labels)
print(report)

cm=confusion_matrix(true_classes,predicted_classes)

sns.heatmap(cm, annot=True)

print(cm)

plt.show()

并收到此错误

2019-12-09 12:55:02.163825: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Traceback (most recent call last):
  File "C:/Users/Acer/PycharmProjects/condas/VGG16.py", line 36, in <module>
    x = Dense(1, activation='sigmoid')(x)
  File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\backend\tensorflow_backend.py", line 75, in symbolic_fn_wrapper
    return func(*args, **kwargs)
  File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\engine\base_layer.py", line 475, in __call__
    previous_mask = _collect_previous_mask(inputs)
  File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\engine\base_layer.py", line 1441, in _collect_previous_mask
    mask = node.output_masks[tensor_index]
AttributeError: 'Node' object has no attribute 'output_masks'

Process finished with exit code 1

我使用python 3.6

1 个答案:

答案 0 :(得分:1)

GitHub上有一个与此主题GitHub Keras 10907有关的问题

在帖子中有一些关于tensorflow和keras关系的信息:

  

我遇到了类似的问题,但是架构不同。作为人   建议不要将keras与tensorflow.keras混合使用很重要,因此   尝试交换

import image from keras.models
import Model from keras.layers 
import Dense, GlobalAveragePooling2D
from keras import backend as K 
     

收件人:

     
from tensorflow.keras.preprocessing import image 
from tensorflow.keras.models import Model from tensorflow.keras.layers
import Dense, GlobalAveragePooling2D 
from tensorflow.keras import backend as K 
     

还要确保,您不在代码内使用keras.something(不是   也只能导入),希望对您有所帮助:)另外,我将Keras 2.2.4与   tensorflow 1.10.0