AttributeError: Model object has no attribute predict_classes 的解决方案

第一次用的网络是在model=Sequential()下添加模块的的方法,也就是所谓的顺序模型。Sequential class可以使用model.predict_classes()的方法来实现预测;
代码如下:

model = Sequential()
model.add(Conv2D(6,kernel_size=(3,3),strides=1,activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2),strides=2)

model.add(Conv2D(16,kernel_size=(3,3),strides=1, activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2),strides=2)

model.add(Flatten)
model.add(Dense(120,activation='relu'))
model.add(Dense(84,activation='relu'))
model.add(Dense(10,activation='sigmoid'))

第二次用的方法,是编写好网络结构后使用model=Model()综合起来的方法,也就是Model class,无法使用model.predict_classes(),但是可以使用组合形式预测。
代码如下:

import tensorflow as tf
import pandas as pd
import numpy as np
from tensorflow import keras
from tensorflow.keras import Sequential
from tensorflow.keras.layers import *
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score


(train_image,train_label),(test_image, test_label)=tf.keras.datasets.cifar10.load_data()
train_image = train_image/255
test_image = test_image/255

input = keras.Input(shape=(32,32,3))
x = keras.layers.Conv2D(6,kernel_size=(3,3),strides=1,activation='relu')(input)
x = keras.layers.MaxPooling2D(pool_size=(2,2),strides=2)(x)
x = keras.layers.Conv2D(16,kernel_size=(3,3),strides=1,activation='relu')(x)
x = keras.layers.MaxPooling2D(pool_size=(2,2),strides=2)(x)
x = keras.layers.Flatten()(x)
x = keras.layers.Dense(120,activation='relu')(x)
x = keras.layers.Dense(84,activation='relu')(x)
output = keras.layers.Dense(10,activation='sigmoid')(x)
model = keras.Model(inputs=input, outputs=output)

model.compile(optimizer= tf.keras.optimizers.Adam(learning_rate=0.0001),
              loss='categorical_crossentropy',
              metrics=['acc'])
train_label_onehot=tf.keras.utils.to_categorical(train_label)
history = model.fit(train_image, train_label_onehot,batch_size=256,epochs=20,validation_split=0.2)
y_predict = model.predict_image(test_image)

但是,此时会报错:

AttributeError: 'Model' object has no attribute 'predict_classes' 

上网查了查之后发现,原因很简单,两次训练时,网络结构不同。

所以修改方法就是将

y_predict = model.predict_image(test_image)

改为:

y_predict = model.predict(test_image)
y_predict = np.argmax(y_predict,axis=-1)

即可。

你可能感兴趣的:(tensorflow,深度学习,神经网络)