简体   繁体   English

向训练有素的 tensorflow keras model 添加重新缩放层(或任何层)

[英]Adding a rescaling layer (or any layer for that matter) to a trained tensorflow keras model

I have a tensorflow keras model trained with tensorflow 2.3.我有一个 tensorflow keras model 训练有 tensorflow。 The model takes as input an image, however the model was trained with scaled inputs and therefore we have to scale the image by 255 before inputting them into the model. model 将图像作为输入,但是 model 使用缩放输入进行训练,因此我们必须在将图像输入 Z20F35E630DAF44DBFA4C3F68F5399D8Z 之前将图像缩放 255。

As we use this model across a variety of platforms, I am trying to simplify this by modifying the model to simply insert a rescale layer at the start of the keras model (ie immediately after the input). As we use this model across a variety of platforms, I am trying to simplify this by modifying the model to simply insert a rescale layer at the start of the keras model (ie immediately after the input). Therefore any future consumption of this model can simply pass an image without having to scale them.因此,此 model 的任何未来消费都可以简单地传递图像而无需缩放它们。

I am having a lot of trouble getting this to work.我在让它工作时遇到了很多麻烦。 I understand I need to use the following function to create a rescaling layer;我了解我需要使用以下 function 来创建重新缩放层;

tf.keras.layers.experimental.preprocessing.Rescaling(255, 0.0, "rescaling")

But I am unsure how to insert this to the start of the model.但我不确定如何将其插入 model 的开头。

Thank you in advance先感谢您

you can insert this layer at the top of your trained model.你可以在你训练好的 model 的顶部插入这一层。 below an example where first we train a model manual scaling the input and the we using the same trained model but adding at the top a Rescaling layer下面是一个示例,首先我们训练一个 model 手动缩放输入,我们使用相同的训练 model 但在顶部添加一个Rescaling

from tensorflow.keras.layers.experimental.preprocessing import Rescaling

# generate dummy data
input_dim = (28,28,3)
n_sample = 10

X = np.random.randint(0,255, (n_sample,)+input_dim)
y = np.random.uniform(0,1, (n_sample,))

# create base model
inp = Input(input_dim)
x = Conv2D(8, (3,3))(inp)
x = Flatten()(x)
out = Dense(1)(x)

# fit base model with manual scaling
model = Model(inp, out)
model.compile('adam', 'mse')
model.fit(X/255, y, epochs=3)

# create new model with pretrained weight + rescaling at the top
inp = Input(input_dim)
scaled_input = Rescaling(1/255, 0.0, "rescaling")(inp)
out = model(scaled_input)
scaled_model = Model(inp, out)

# compare prediction with manual scaling vs layer scaling
pred = model.predict(X/255)
pred_scaled = scaled_model.predict(X)

(pred.round(5) == pred_scaled.round(5)).all() # True

Rescaling the images is part of data preprocessing, also rescaling images is called image normalization , this process is useful for providing a uniform scale for the dataset or numerical values you are using before building your model.In keras you can do this in many ways using one of the following according to your target:重新缩放图像是数据预处理的一部分,重新缩放图像也称为图像归一化,此过程对于在构建 model 之前为您正在使用的数据集或数值提供统一比例尺非常有用。在 keras 中,您可以使用多种方式执行此操作根据您的目标选择以下之一:

If you are training using an Artificial neural network model you can use:-如果您使用人工神经网络 model 进行训练,您可以使用:-

"Batch normalization layer" or "Layer Normalization" or by the rescale method of keras you mentioned. “批量归一化层”或“层归一化”或通过您提到的 keras 的重新缩放方法。 You can look at this resource for more information about normalization.您可以查看此资源以获取有关规范化的更多信息。 https://machinelearningknowledge.ai/keras-normalization-layers-explained-for-beginners-batch-normalization-vs-layer-normalization/ https://machinelearningknowledge.ai/keras-normalization-layers-explained-for-beginners-batch-normalization-vs-layer-normalization/

to use the rescale method you mentioned:使用您提到的重新缩放方法:

#importing you libraries 1st
import tensorflow as tf
from tensorflow.keras.layers import BatchNormalization
#if your are using dataset from directory 
import pathlib 

then import your Dataset:然后导入您的数据集:

Dataset_Dir = '/Dataset/ path'
image size = (256,256) #the image size in your dataset
image shape = (96,96,3) #The shape you wish for your images in your network

Then divide your dataset to train-test I use 70-30 percent然后将您的数据集划分为训练测试,我使用 70-30%

Training_set = tf.keras.preprocessing.image_dataset_from_directory(Dataset_Dir,batch_size= 32,
                                                               image_size= image_size,
                                                               validation_split= 0.3,subset = "training",seed =123)

Test set测试集

Testing_set = tf.keras.preprocessing.image_dataset_from_directory(Dataset_Dir,image_size= image_size,
                                                              validation_split=0.3,seed=123,subset ="validation")

normalization layer:标准化层:

normalization_layer = tf.keras.layers.experimental.preprocessing.Rescaling(1./255)
normalized_training_set = Training_set.map(lambda x, y: (normalization_layer(x), y))
training_image_batch,training_labels_batch = next(iter(normalized_training_set))

for more about this method too: look at tensorflow tutorial: https://www.tensorflow.org/tutorials/images/classification有关此方法的更多信息:查看 tensorflow 教程: https://www.tensorflow.org/tutorials/images/classification

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM