tensorflow下 使用keras构建卷积神经网络
1.初始化模型model。创建Sequential类,并添加层
2.编译模型 调用compile(),指定优化方法,损失函数等
3.定义Callback(可选) 定义训练终止条件
4.图片生成器 创建图片生成器,从文件夹中读取图片,并处理图片
5 训练 调用model的的fit_generator 训练数据
初始化
import tensorflow as tf
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(16,(3,3),activation = tf.nn.relu,input_shape = (300,300,3)),
tf.keras.layers.MaxPool2D(2,2),
tf.keras.layers.Conv2D(32,(3,3),activation=tf.nn.relu),
tf.keras.layers.MaxPool2D(2,2),
tf.keras.layers.Conv2D(64,(3,3),activation=tf.nn.relu),
tf.keras.layers.MaxPool2D(2,2),
tf.keras.layers.Conv2D(64,(3,3),activation=tf.nn.relu),
tf.keras.layers.MaxPool2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512,activation=tf.nn.relu),
tf.keras.layers.Dense(1,activation= tf.nn.sigmoid)
])
编译
from tensorflow.keras.optimizers import RMSprop
model.compile(optimizer = RMSprop(lr=0.0003),loss = "binary_crossentropy",metrics = ["acc"])
图片生成器
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1/255.0)
train_generator = train_datagen.flow_from_directory(
"/tmp/h-or-s",
target_size = (300,300),
batch_size = 10,
class_mode = "binary",
)
回调
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epochs,logs={}):
if logs.get("acc") > 0.999:
print("\nReached 99.9% accuracy so cancelling training!")
self.model.stop_training = True
callbacks = myCallback()
训练
hist = model.fit_generator(
train_generator,
steps_per_epoch=8,
epochs=10,
verbose=1,
callbacks=[callbacks])