有关keras模型以及如何编译模型的问题

时间:2018-10-14 15:01:00

标签: python tensorflow keras

我正在尝试在pycharm中创建CNN。运行代码时,控制台输出
RuntimeError: You must compile your model before using it.

我写下编译。 这是我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-o
from keras.models import Sequential
from keras.layers import Dense, MaxPool2D, Flatten, Conv2D, Dropout
from keras.preprocessing import image
from keras.optimizers import adadelta

generator = image.ImageDataGenerator(
                rescale=1./255,
                featurewise_center=False,
                samplewise_center=False,
                featurewise_std_normalization=False,
                samplewise_std_normalization=False,
                zca_whitening=False,
                rotation_range=10,
                width_shift_range=0.1,
                height_shift_range=0.1,
                horizontal_flip=True,
                vertical_flip=False,
               )

dateset = generator.flow_from_directory(
               shuffle=True,
               batch_size=100,
               target_size=(80, 80),
               directory='/Users/Username/Documents/Project AI/Dateset/blood-cells/dataset2-master/images/TRAIN')


def model():
    model = Sequential()
    model.add(Conv2D(80, (3, 3), strides=(1, 1), activation='relu'))
    model.add(Conv2D(64, (3, 3), strides=(1, 1), activation='relu',     
              input_shape=(80, 80, 3)))
    model.add(MaxPool2D(pool_size=(2, 2)))
    model.add(Conv2D(64, (3, 3), strides=(1, 1), activation='relu'))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4, activation='softmax'))
    model.compile(optimizer=adadelta(lr=0.001),    
    loss='categorical_crossentropy', metrics=['accuracy'])
    return model

nn = model()
nn.fit_generator(dateset,steps_per_epoch=None, epochs=30, verbose=1)
nn.save('/Users/yangzichen/Documents/Project AI/Model.txt')

1 个答案:

答案 0 :(得分:1)

您似乎用您的函数覆盖了Keras model()函数。尝试以下方法:

def get_model():  
    model = Sequential() 
    ...
    < *rest of your function code here* >
    ...

    return model

nn = get_model()