如何用Tensorflow框架構建用于食品分類的機器學習模型?
這是數據框的視圖,

下一步就是制作一個對象,將圖片放入模型中。我們將練習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 執行遷移學習。我希望這項研究能鼓勵你,尤其是那些渴望在數據不足的情況下訓練深度學習模型的人。
請輸入評論內容...
請輸入評論/評論長度6~500個字
最新活動更多
-
11月7日立即參評>> 【評選】維科杯·OFweek 2025(第十屆)物聯網行業年度評選
-
11月20日立即報名>> 【免費下載】RISC-V芯片發展現狀與測試挑戰-白皮書
-
即日-11.25立即下載>>> 費斯托白皮書《柔性:汽車生產未來的關鍵》
-
11月27日立即報名>> 【工程師系列】汽車電子技術在線大會
-
11月28日立即下載>> 【白皮書】精準洞察 無線掌控——283FC智能自檢萬用表
-
12月18日立即報名>> 【線下會議】OFweek 2025(第十屆)物聯網產業大會


分享













