我正在建立一个uNet模型来分割水滴。 训练模型很顺利,但是当我尝试做出预测时,会弹出一个错误。 我正在将项目的部分代码上传到此处。 这是模型:
def unettest():
inputs = tf.keras.layers.Input((256,256,1))
# Contraction path
c1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(inputs)
c1 = tf.keras.layers.Dropout(0.1)(c1)
c1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c1)
p1 = tf.keras.layers.MaxPooling2D((2, 2))(c1)
c2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p1)
c2 = tf.keras.layers.Dropout(0.1)(c2)
c2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c2)
p2 = tf.keras.layers.MaxPooling2D((2, 2))(c2)
c3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p2)
c3 = tf.keras.layers.Dropout(0.2)(c3)
c3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c3)
p3 = tf.keras.layers.MaxPooling2D((2, 2))(c3)
c4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p3)
c4 = tf.keras.layers.Dropout(0.2)(c4)
c4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c4)
p4 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(c4)
c5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p4)
c5 = tf.keras.layers.Dropout(0.3)(c5)
c5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c5)
# Expansive path
u6 = tf.keras.layers.Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(c5)
u6 = tf.keras.layers.concatenate([u6, c4])
c6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u6)
c6 = tf.keras.layers.Dropout(0.2)(c6)
c6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c6)
u7 = tf.keras.layers.Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(c6)
u7 = tf.keras.layers.concatenate([u7, c3])
c7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u7)
c7 = tf.keras.layers.Dropout(0.2)(c7)
c7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c7)
u8 = tf.keras.layers.Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(c7)
u8 = tf.keras.layers.concatenate([u8, c2])
c8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u8)
c8 = tf.keras.layers.Dropout(0.1)(c8)
c8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c8)
u9 = tf.keras.layers.Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(c8)
u9 = tf.keras.layers.concatenate([u9, c1], axis=3)
c9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u9)
c9 = tf.keras.layers.Dropout(0.1)(c9)
c9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c9)
outputs = tf.keras.layers.Conv2D(1, (1, 1), activation='sigmoid')(c9)
model = tf.keras.Model(inputs=[inputs], outputs=[outputs])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.summary()
return model
预处理图像和蒙版
def preprocessImage():
x = np.zeros((176, 256, 256, 1), dtype=np.float32)
y = np.zeros((176, 256, 256, 1), dtype=np.float32)
lstofmasks = os.listdir(r'C:\Users\loai0\PycharmProjects\pythonProject3\traintrain_masks')
lstofimages = os.listdir(r'C:\Users\loai0\PycharmProjects\pythonProject3\traintrain_images')
lstofimages.sort()
lstofmasks.sort()
c = 0
for img in lstofimages:
dir_img = os.path.join(r'C:\Users\loai0\PycharmProjects\pythonProject3\traintrain_images', img)
image = cv2.imread(dir_img)
image = cv2.resize(image, (256, 256))
image = np.array(image, dtype=np.uint8)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = image.reshape(256, 256, 1) / 255
x[c] = image
lstofimages = []
for img in lstofmasks:
dir_img = os.path.join(r'C:\Users\loai0\PycharmProjects\pythonProject3\traintrain_masks', img)
image = cv2.imread(dir_img)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, (256, 256))
image = np.array(image, dtype=np.uint8)
image = image.reshape(256, 256, 1) / 255
# plt.imshow(image)
# plt.show()
y[c] = image
lstofmasks = []
return x,y
火车:
def train():
images, maskes = preprocessImage()
#x_train, x_test, y_train, y_test = train_test_split(images, maskes, test_size=0.2, shuffle=42)
x_train = images[:140]
x_test = images[140:]
y_train = maskes[:140]
y_test = maskes[140:]
#model = unet()
model = unettest()
model_checkpoint = ModelCheckpoint('unet_membrane.hdf5', monitor='loss', verbose=1, save_best_only=True)
results = model.fit(x_train, y_train, epochs=5, batch_size=2)
# evaluate
score, accuracy = model.evaluate(x_test, y_test, batch_size=1)
# the results
print("Our Models' Score = {:.2f}".format(score))
print("The Accuracy of the model = {:.2f}".format(accuracy * 100))
# after Evaluating we save the model and the weights into the .h5 file
print("--- saving the model ---")
model.save("image_model.h5")
测试(预测):
def test():
print("testing")
loaded_model = load_model("image_model.h5")
image = cv2.imread("test1.tif")
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, (256, 256))
image = np.array(image, dtype=np.uint8)
image = image.reshape(256, 256, 1) / 255
prediction = loaded_model.predict(image)
模型的构建很不错,但是当我尝试做出预测时,会弹出该错误
ValueError: Negative dimension size caused by subtracting 2 from 1 for '{{node functional_1/max_pooling2d/MaxPool}} = MaxPool[T=DT_FLOAT, data_format="NHWC", ksize=[1, 2, 2, 1], padding="VALID", strides=[1, 2, 2, 1]](functional_1/conv2d_1/Relu)' with input shapes: [32,256,1,16]
感谢您的帮助。