tensorflow/keras 常用代码

常用导包

import os,glob 
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
from PIL import Image
import IPython.display as display

import xml.etree.ElementTree as ET

print(tf.__version__)
print(tf.test.is_gpu_available())

解释

常量

img_size=224
batch_size=8
AUTOTUNE=tf.data.experimental.AUTOTUNE

预处理图片

预处理训练集

def process_train(path,label):
    t=tf.io.read_file(path)
    arr=tf.io.decode_jpeg(t,channels=3)
    arr=tf.image.resize(arr,(img_size,img_size))
    arr = arr/255
    return arr,label

Dataset

生成dataset

train_ds=tf.data.Dataset.from_tensor_slices((train_names,train_labels))

生成dataset2

train_ds2=train_ds.map(process_train,num_parallel_calls=AUTOTUNE).shuffle(train_num).batch(batch_size).prefetch(AUTOTUNE)

model

build

def build():
    base_model=tf.keras.applications.Xception(weights='imagenet', include_top=False,
                                  input_shape=(img_size, img_size, 3) )
    base_model.trainable=False

    model=tf.keras.Sequential()
    model.add(base_model)
    model.add(tf.keras.layers.GlobalAveragePooling2D())
#     model.add(tf.keras.layers.Dense(512,activation="relu",kernel_regularizer=tf.keras.regularizers.l2(0.0001)))
    model.add(tf.keras.layers.Dense(512,activation="relu"))
    model.add(tf.keras.layers.Dense(1))

    return model

编译

model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.0001),loss="mse",metrics=["mae"])

训练

history=model.fit(train_ds2,epochs=5,validation_data=test_ds2)

保存

model.save("model.h5",save_format="h5")

查看

查看损失值走势

plt.plot(history.epoch,history.history["loss"],label="loss")
plt.plot(history.epoch,history.history["val_loss"],label="val_loss")
plt.legend()

准确率走势

plt.plot(history.epoch,history.history["acc"],label="acc")
plt.plot(history.epoch,history.history["val_acc"],label="val_acc")
plt.legend()

原文出处:/show_1EF5CFJYJCG7.html