我一直在做图像分类器,这些源代码来自我的大学,但是当我使用这些代码时,我一直遇到错误,源代码是针对多个图像分类器的,我只是将分类器更改为二进制,我认为我正在做某事错误,但idk什么
import numpy as np
import keras
from keras.layers import Dense,GlobalAveragePooling2D
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt
train_path=r'C:\Users\Acer\imagerec\Brain\TRAIN'
valid_path=r'C:\Users\Acer\imagerec\Brain\VAL'
test_path=r'C:\Users\Acer\imagerec\Brain\TEST'
class_labels=['yes', 'no']
train_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
.flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
valid_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
.flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
test_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
.flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5, shuffle=False)
base_model=keras.applications.xception.Xception(include_top=False)
x=base_model.output
x=GlobalAveragePooling2D
x=Dense(1,activation='sigmoid')(x)
predictions=Dense(2,activation='Adam')(x)
for layer in base_model.layers:
layer.trainable=False
model=Model(inputs=base_model.input,outputs=predictions)
model.summary()
N=30
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
history=model.fit_generator(train_batches, steps_per_epoch=412,
validation_data=valid_batches,
validation_steps=35,epochs=N,verbose=1)
我收到此错误
2019-12-09 13:43:11.107461: 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\Anaconda3\envs\condas\lib\site-packages\keras\engine\base_layer.py", line 310, in assert_input_compatibility
K.is_keras_tensor(x)
File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\backend\tensorflow_backend.py", line 697, in is_keras_tensor
str(type(x)) + '`. '
ValueError: Unexpectedly found an instance of type `<class 'type'>`. Expected a symbolic tensor instance.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Acer/PycharmProjects/condas/nyah.py", line 28, 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 446, in __call__
self.assert_input_compatibility(inputs)
File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\engine\base_layer.py", line 316, in assert_input_compatibility
str(inputs) + '. All inputs to the layer '
ValueError: Layer dense_1 was called with an input that isn't a symbolic tensor. Received type: <class 'type'>. Full input: [<class 'keras.layers.pooling.GlobalAveragePooling2D'>]. All inputs to the layer should be tensors.
答案 0 :(得分:2)
事物的结合。
1)对于二进制分类,请使用sigmoid
激活,且损失binary_crossentropy
。
2)adam
不是激活功能。这是一个优化器。
3)您尝试在for
循环中定义模型。
更多信息,请参阅Keras文档:https://keras.io/
修改后的代码:
import numpy as np
import keras
from keras.layers import Dense,GlobalAveragePooling2D
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt
train_path=r'C:\Users\Acer\imagerec\Brain\TRAIN'
valid_path=r'C:\Users\Acer\imagerec\Brain\VAL'
test_path=r'C:\Users\Acer\imagerec\Brain\TEST'
class_labels=['yes', 'no']
train_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
.flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
valid_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
.flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
test_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
.flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5, shuffle=False)
base_model=keras.applications.xception.Xception(include_top=False, input_shape=(299,299,3))
x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1, activation='sigmoid')(x)
model=Model(inputs=base_model.input, outputs=x)
for layer in base_model.layers:
layer.trainable=False
N=30
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
history=model.fit_generator(train_batches, steps_per_epoch=412,
validation_data=valid_batches,
validation_steps=35,epochs=N,verbose=1)
答案 1 :(得分:1)
如上所述,您的代码中存在多个错误。
首先,亚当是一个优化器,而不是激活函数。
其次,在for循环中定义模型。
第三,GlobalAveragePooling2D图层后面没有(x),因此未将其添加到模型中。
此外,您无需将图层设置为在for循环中不可训练。您可以只写base_model.trainable = False
最后,将tf.keras与tensorflow 2.0一起使用也会更好。
参见What is the difference between keras and tf.keras?
下面是更正的代码。
import numpy as np
from tensorflow import keras
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt
train_path=r'C:\Users\Acer\imagerec\Brain\TRAIN'
valid_path=r'C:\Users\Acer\imagerec\Brain\VAL'
test_path=r'C:\Users\Acer\imagerec\Brain\TEST'
class_labels=['yes', 'no']
train_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
.flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
valid_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
.flow_from_directory(valid_path, target_size=(299,299),classes=class_labels,batch_size=5)
test_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
.flow_from_directory(test_path, target_size=(299,299),classes=class_labels,batch_size=5, shuffle=False)
base_model=keras.applications.xception.Xception(include_top=False, input_shape=(299,299,3))
x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1)(x)
x=Dense(2, activation='sigmoid')(x)
model=Model(inputs=base_model.input, outputs=x)
base_model.trainable = False
N=30
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
history=model.fit_generator(train_batches, steps_per_epoch=412,
validation_data=valid_batches,
validation_steps=35,epochs=N,verbose=1)