目录
Keras Sequential类型 构建CNN网络
Keras Model类型 构建CNN网络
model.fit()和fit_generator的区别
Keras Sequential类型 构建CNN网络
from Keras.models import Sequential
from Keras.models import Dense,Dropout,Flatten
from Keras.layers.convolutional import Conv2D,MaxPooling2D
model=Sequential()
model.add(Conv2D(filters=64,kernel_size=(3,3),strides=(3,3),padding="same",activation='relu',input_shape=input_shape))
#When using this layer as the first layer in a model,provide the keyword argu #`input_shape`
model.add(MaxPooling2D())
model.add(Dropout())
model.add(Flatten())
model.add(Dense(num_classes,activation=' '))
model.complile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
history=model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))#将训练过程记录在history中
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
predicted = model.predict(X_test)#对测试数据进行预测
#同时保存model和权重的方式:
model.save('******.h5')
#model = load_model("******.h5") 下载保存好的模型,需 from keras.models import load_model
train_loss = history.history['loss']
valid_loss = history.history['val_loss']
plt.plot(train_loss, label='train')
plt.plot(valid_loss, label='valid')
plt.legend(loc='upper right')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()
train_acc = history.history['acc']
valid_acc = history.history['val_acc']
plt.plot(train_acc, label='train')
plt.plot(valid_acc, label='valid')
plt.legend(loc='upper right')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.show()
Keras Model类型 构建CNN网络
from Keras.layers import Input,Dense,Flatten,Dropout
from Keras.layer.convolutional import Conv2D,Maxpooling2D
from Keras.models import Model
from keras.optimizers import Adam
input=Input(shape=())#输入数据的形状
x=Conv2D(filters=64, kernel_size=(3,3), strides=(1,1), padding='same',
activation='relu')(input)#第一层需要指定输入的形状
x=Maxpooling2D(pool_size=(2,2))(x)
x=Flatten()(x)
x=Dense(64,activation='')(x)
x=Dense(32,activation='')(x)
model=Model(input=input,outputs=x)
optimizer = Adam(lr=0.01, clipnorm=5)#定义优化器
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
history=model.fit(X_train, Y_train, epochs=epochs,batch_size=batch_size,validation_split=0.1)#将训练过程记录在history中
model.save('***.h5')#保存模型
#model = load_model("******.h5") 下载保存好的模型,需 from keras.models import load_model
scores = model.evaluate(X_test,Y_test,verbose=0)#对测试数据进行检测
train_loss = history.history['loss']
valid_loss = history.history['val_loss']
plt.plot(train_loss, label='train')
plt.plot(valid_loss, label='valid')
plt.legend(loc='upper right')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()
train_acc = history.history['acc']
valid_acc = history.history['val_acc']
plt.plot(train_acc, label='train')
plt.plot(valid_acc, label='valid')
plt.legend(loc='upper right')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.show()
model.fit()和fit_generator的区别
model.fit(x_train, y_train, epochs=10,batch_size=32,validation_split=0.2)
model.fit_generator(generator(),epochs=epochs,steps_per_epoch=steps_per_epoch=len(X_train) // batch_size)
fit()函数传入的x_train和y_train是被完整的加载进内存的,如果数据很大则需要很大的内存;fit_generator利用生成器生成训练的数据(一个batch的数据),训练的数据通过生成器依次传入内存进行序列,所需的内存较小