订阅
纠错
加入自媒体

如何用Tensorflow框架构建用于食品分类的机器学习模型?

2021-06-07 17:57
磐创AI
关注

这是数据框的视图,

下一步就是制作一个对象,将图片放入模型中。我们将练习tf.keras.preprocessing.image库的ImageDataGenerator对象。使用此对象,我们将生成图像批次。此外,我们可以扩充我们的图片以扩大数据集的乘积。因为我们还扩展了这些图片,我们进一步设置了图像增强技术的参数。

此外,因为我们应用了一个数据帧作为关于数据集的知识,因此我们将使用flow_from_dataframe方法生成批处理并增强图片。上面的代码看起来像这样from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Create the ImageDataGenerator object
train_datagen = ImageDataGenerator(
   featurewise_center=True,
   featurewise_std_normalization=True,
   rotation_range=20,
   width_shift_range=0.2,
   height_shift_range=0.2,
   horizontal_flip=True,

val_datagen = ImageDataGenerator(
   featurewise_center=True,
   featurewise_std_normalization=True,
   rotation_range=20,
   width_shift_range=0.2,
   height_shift_range=0.2,
   horizontal_flip=True,

# Generate batches and augment the images
train_generator = train_datagen.flow_from_dataframe(
   df_train,
   directory='Food-5K/training/',
   x_col='filename',
   y_col='label',
   class_mode='binary',
   target_size=(224, 224),

val_generator = train_datagen.flow_from_dataframe(
   df_val,
   directory='Food-5K/validation/',
   x_col='filename',
   y_col='label',
   class_mode='binary',
   target_size=(224, 224),

步骤3:训练模型

决定好批次之后,我们可以通过迁移学习技术来训练模型。因为我们应用了这种方法,所以我们不需要从头开始执行 CNN 架构。相反,我们将使用当前和以前预训练的架构。我们将应用 ResNet-50 作为我们新模型的脊椎。我们将生成输入并根据类别数量调整 ResNet-50 的最后一个线性层ResNet-50。

构建模型的代码如下

from tensorflow.keras.applications import ResNet50
# Initialize the Pretrained Model
feature_extractor = ResNet50(weights='imagenet',
                            input_shape=(224, 224, 3),
                            include_top=False)
# Set this parameter to make sure it's not being trained
feature_extractor.trainable = False
# Set the input layer
input_ = tf.keras.Input(shape=(224, 224, 3))
# Set the feature extractor layer
x = feature_extractor(input_, training=False)
# Set the pooling layer
x = tf.keras.layers.GlobalAveragePooling2D()(x)
# Set the final layer with sigmoid activation function
output_ = tf.keras.layers.Dense(1, activation='sigmoid')(x)
# Create the new model object
model = tf.keras.Model(input_, output_)
# Compile it
model.compile(optimizer='adam',
            loss='binary_crossentropy',
            metrics=['accuracy'])
# Print The Summary of The Model
model.summary()

为了训练模型,我们采用拟合的方法来准备模型。这是代码,model.fit(train_generator, epochs=20, validation_data=val_generator)

步骤4:测试模型

在训练模型之后,现在让我们在测试数据集上检查模型。在扩展中,我们需要结合一个pillow库来加载和调整图片大小,以及 scikit-learn 来确定模型性能。我们将练习来自 scikit-learn 库的分类报告,以生成关于模型执行的报告。此外,我们会喜欢它的混淆矩阵。这是预测实验数据及其决策的代码,from PIL import Image
from sklearn.metrics import classification_report, confusion_matrix
y_true = []
y_pred = []
for i in os.listdir('Food-5K/evaluation'):
   img = Image.open('Food-5K/evaluation/' + i)
   img = img.resize((224, 224))
   img = np.array(img)
   img = np.expand_dims(img, 0)
   
   y_true.append(int(i.split('_')[0]))
   y_pred.append(1 if model.predict(img) > 0.5 else 0)
   
print(classification_report(y_true, y_pred))
print()
print(confusion_matrix(y_true, y_pred))

从前面的内容可以看出,该模型的性能已超过95%。因此,我们可以在建立图像分类器 API 的情况下接受此模型。

步骤5:保存模型

如果你希望将模型用于后续使用或部署,你可以使用 save 方法保存模型,model.save('./resnet50_food_model')

如果你需要加载模型,你可以像这样练习load_model方法,model = tf.keras.models.load_model('./resnet50_food_model')

下一步是什么

做得好!现在你已了解如何使用 TensorFlow 执行迁移学习。我希望这项研究能鼓励你,尤其是那些渴望在数据不足的情况下训练深度学习模型的人。

<上一页  1  2  
声明: 本文由入驻维科号的作者撰写,观点仅代表作者本人,不代表OFweek立场。如有侵权或其他问题,请联系举报。

发表评论

0条评论,0人参与

请输入评论内容...

请输入评论/评论长度6~500个字

您提交的评论过于频繁,请输入验证码继续

暂无评论

暂无评论

人工智能 猎头职位 更多
扫码关注公众号
OFweek人工智能网
获取更多精彩内容
文章纠错
x
*文字标题:
*纠错内容:
联系邮箱:
*验 证 码:

粤公网安备 44030502002758号