利用unet tensorflow深度学习
代码如下
import os
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
from keras.layers.core import Dropout
from keras.layers.convolutional import Conv2D, Conv2DTranspose
from keras.layers.pooling import MaxPooling2D
from keras.layers import Input
from keras.models import Model
from keras.layers.merge import concatenate
from keras.callbacks import EarlyStopping, ModelCheckpoint
def standardize(img):
mean = np.mean(img, axis=0)
std = np.std(img, axis=0)
return (img - mean) / std
# Get training and validation paths
def get_train_val_paths(img_folder, mask_folder, split_ratio=0.8):
img_names = os.listdir(img_folder)
print("total images: ", len(img_names))
mask_names = os.listdir(mask_folder)
img_paths = [os.path.join(img_folder, name) for name in img_names]
mask_paths = [os.path.join(mask_folder, name) for name in mask_names]
no_samples = len(img_paths)
no_train = int(np.ceil(split_ratio * no_samples))
train_paths = {name: paths_list for name, paths_list in zip(["train_imgs", "train_mask"],
[img_paths[:no_train], mask_paths[:no_train]])}
val_paths = {name: paths_list for name, paths_list in zip(["val_imgs", "val_mask"],
[img_paths[no_train:], mask_paths[no_train:]])}
return train_paths, val_paths
# Data generator to get single image and mask
def image_generator(img_paths, mask_paths):
for img_path, mask_path in zip(img_paths, mask_paths):
img = io.imread(img_path)
img = standardize(img)
img = np.expand_dims(img, axis=2)
mask = io.imread(mask_path) / 255.
mask = np.expand_dims(mask, axis=2)
yield img, mask
# Batch data generator
def img_batch_generator(img_paths, mask_paths, batch_size):
while True:
img_gen = image_generator(img_paths, mask_paths)
img_batch, mask_batch = [], []
for img, mask in img_gen:
img_batch.append(img)
mask_batch.append(mask)
if len(img_batch) == batch_size:
yield np.stack(img_batch, axis=0), np.stack(mask_batch, axis=0)
img_batch, mask_batch = [], []
if len(img_batch) != 0:
yield np.stack(img_batch, axis=0), np.stack(mask_batch, axis=0)
image_folder = "C:/Users/11962/Desktop/images1/"
masks_folder = "C:/Users/11962/Desktop/masks1/"
tr_paths, v_paths = get_train_val_paths(image_folder, masks_folder)
inputs = Input((512, 512, 1))
c1 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(inputs)
c1 = Dropout(0.1)(c1)
c1 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(c1)
p1 = MaxPooling2D((2, 2))(c1)
c2 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(p1)
c2 = Dropout(0.1)(c2)
c2 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(c2)
p2 = MaxPooling2D((2, 2))(c2)
c3 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(p2)
c3 = Dropout(0.2)(c3)
c3 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(c3)
p3 = MaxPooling2D((2, 2))(c3)
c4 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(p3)
c4 = Dropout(0.2)(c4)
c4 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(c4)
p4 = MaxPooling2D(pool_size=(2, 2))(c4)
c5 = Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(p4)
c5 = Dropout(0.3)(c5)
c5 = Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(c5)
u6 = Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(c5)
u6 = concatenate([u6, c4])
c6 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(u6)
c6 = Dropout(0.2)(c6)
c6 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(c6)
u7 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(c6)
u7 = concatenate([u7, c3])
c7 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(u7)
c7 = Dropout(0.2)(c7)
c7 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(c7)
u8 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(c7)
u8 = concatenate([u8, c2])
c8 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(u8)
c8 = Dropout(0.1)(c8)
c8 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(c8)
u9 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(c8)
u9 = concatenate([u9, c1], axis=3)
c9 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(u9)
c9 = Dropout(0.1)(c9)
c9 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same')(c9)
outputs = Conv2D(1, (1, 1), activation='sigmoid')(c9)
model = Model(inputs=[inputs], outputs=[outputs])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
print(model.summary())
batch_size = 2
train_gen = img_batch_generator(tr_paths["train_imgs"], tr_paths["train_mask"], batch_size)
val_gen = img_batch_generator(v_paths["val_imgs"], v_paths["val_mask"], batch_size)
train_steps = len(tr_paths["train_imgs"]) // batch_size
val_steps = len(v_paths["val_imgs"]) // batch_size
early_stop = EarlyStopping(patience=10, verbose=1)
checkpoint = ModelCheckpoint("./model/keras_unet_model.h5", verbose=1, save_best_only=True)
history = model.fit(train_gen, steps_per_epoch=train_steps,
epochs=30,
validation_data=val_gen,
validation_steps=val_steps,
verbose=1,
max_queue_size=4,
callbacks=[early_stop, checkpoint])
loss = history.history["loss"]
val_loss = history.history["val_loss"]
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, color="red", label="training loss")
plt.plot(epochs, val_loss, color="blue", label="validation loss")
plt.title("Training and Validation Loss")
plt.legend()
plt.figure()
plt.plot(epochs, acc, color="red", label="training acc")
plt.plot(epochs, val_acc, color="blue", label="validation acc")
plt.title("Training and Validation acc")
plt.legend()
报错:TypeError: add_argument() takes 2 positional arguments but 3 were given
应该怎么修改,急