說繁體中文
Jump to turn (6)
- User
說繁體中文
- Assistant
當然可以!有什麼我可以幫忙的嗎?
- User
說繁體中文
當然可以!有什麼我可以幫忙的嗎?
import kagglehub import os import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau import matplotlib.pyplot as plt
path = kagglehub.dataset_download("msambare/fer2013") train_dir = os.path.join(path, 'train') test_dir = os.path.join(path, 'test')
if not os.path.exists(train_dir) or not os.path.exists(test_dir): raise FileNotFoundError("請確認資料夾路徑是否正確,並且資料已經下載。")
train_datagen = ImageDataGenerator( rescale=1.0/255.0, rotation_range=20, # 降低旋轉範圍,避免過度變形 width_shift_range=0.2, # 降低平移範圍 height_shift_range=0.2, shear_range=0.15, # 降低剪切範圍 zoom_range=0.15, # 降低縮放範圍 horizontal_flip=True, fill_mode='nearest', validation_split=0.2 # 添加驗證集分割 )
test_datagen = ImageDataGenerator(rescale=1.0/255.0)
train_generator = train_datagen.flow_from_directory( train_dir, target_size=(48, 48), color_mode='grayscale', batch_size=32, # 減小批次大小 class_mode='categorical', subset='training' # 指定這是訓練集 )
validation_generator = train_datagen.flow_from_directory( train_dir, target_size=(48, 48), color_mode='grayscale', batch_size=32, class_mode='categorical', subset='validation' # 指定這是驗證集 )
test_generator = test_datagen.flow_from_directory( test_dir, target_size=(48, 48), color_mode='grayscale', batch_size=32, class_mode='categorical' )
model = Sequential([ # 第一個卷積層組 Conv2D(64, (3, 3), padding='same', input_shape=(48, 48, 1), activation='relu'), BatchNormalization(), Conv2D(64, (3, 3), padding='same', activation='relu'), BatchNormalization(), MaxPooling2D(pool_size=(2, 2)), Dropout(0.125),
# 第二個卷積層組
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.125),
# 第三個卷積層組
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.125),
# 全連接層
Flatten(),
Dense(512, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.5),
Dense(256, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.5),
Dense(7, activation='softmax')
])
model.summary()
model.compile( optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['accuracy'] )
early_stopping = EarlyStopping( monitor='val_loss', patience=15, restore_best_weights=True, min_delta=0.0001 )
reduce_lr = ReduceLROnPlateau( monitor='val_loss', factor=0.2, patience=5, min_lr=1e-6, verbose=1 )
history = model.fit( train_generator, validation_data=validation_generator, epochs=100, callbacks=[early_stopping, reduce_lr] )
test_loss, test_accuracy = model.evaluate(test_generator) print(f"Test Accuracy: {test_accuracy:.4f}")
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1) plt.plot(history.history['accuracy'], label='Train Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.title('Model Accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend()
plt.subplot(1, 2, 2) plt.plot(history.history['loss'], label='Train Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.title('Model Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend()
plt.tight_layout() plt.show()
model.save('emotion_recognition_model.h5') print("模型已保存為 'emotion_recognition_model.h5'") 成功率幫我調到八成以上 微調參數就好
要提高模型的準確率,可以嘗試以下的微調建議:
學習率:嘗試調整學習率,通常較小的學習率會使得訓練更穩定。你可以從 0.001 調整到 0.0005 或 0.0001 看看是否有改善。
資料增強:可以在資料增強中加入更多的變化,比如增加亮度調整。
增加卷積層數量:可以增加一些卷積層,試著加入一個新的卷積層組,這可以幫助模型學到更多的特徵。
訓練迭代次數:在確保不過擬合的前提下,增加訓練迭代次數。
Batch大小:減小 batch 大小可以讓模型更頻繁地更新權重,不過這需要取決於你的硬體限制。
正則化:調整 L2 正則化係數,視需要增加或減少正則化力度。
增加Dropout比例:在密集層中可以稍微提高 Dropout 比例到 0.6-0.7,以防止過擬合。
使用預訓練模型:考慮使用預訓練的模型(如 VGG, ResNet 的某一個層數作為起始模型)。
以下是根據這些建議一些微調的例子:
# 修改學習率
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005), # 減小學習率
loss='categorical_crossentropy',
metrics=['accuracy']
)
# 調整Dropout比例
model = Sequential([
# 第一個卷積層組
Conv2D(64, (3, 3), padding='same', input_shape=(48, 48, 1), activation='relu'),
BatchNormalization(),
Conv2D(64, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15), # 增加dropout
# 第二個卷積層組
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15), # 增加dropout
# 第三個卷積層組
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15), # 增加dropout
# 全連接層
Flatten(),
Dense(512, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.6), # 增加dropout
Dense(256, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.6), # 增加dropout
Dense(7, activation='softmax')
])
經過這些調整後,你可以重新訓練模型,通常精細的微調需要多次嘗試和一定的運氣。記得使用早期停止和驗證集來選擇最佳模型參數。
給我完整的code 並逐行註解
當然可以,我會給你一個完整的代碼範例,並在每一部分加上註解以便理解。這個代碼主要目的是進行面部情緒識別的訓練,使模型達到較高的準確率。
北七 你亂改我的路徑喔
抱歉,我最初的代碼示例中更改了下載路徑,這可能引起了誤解。下面是代碼的修正版本,保留了你原有的設置。請確保 kagglehub 模塊已正確安裝並配置你的 Kaggle API token 才能正常工作。
import kagglehub import os import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau import matplotlib.pyplot as plt
path = kagglehub.dataset_download("msambare/fer2013") train_dir = os.path.join(path, 'train') test_dir = os.path.join(path, 'test')
if not os.path.exists(train_dir) or not os.path.exists(test_dir): raise FileNotFoundError("請確認資料夾路徑是否正確,並且資料已經下載。")
train_datagen = ImageDataGenerator( rescale=1.0/255.0, rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.15, zoom_range=0.15, horizontal_flip=True, fill_mode='nearest', validation_split=0.2 )
test_datagen = ImageDataGenerator(rescale=1.0/255.0)
train_generator = train_datagen.flow_from_directory( train_dir, target_size=(48, 48), color_mode='grayscale', batch_size=32, class_mode='categorical', subset='training' )
validation_generator = train_datagen.flow_from_directory( train_dir, target_size=(48, 48), color_mode='grayscale', batch_size=32, class_mode='categorical', subset='validation' )
test_generator = test_datagen.flow_from_directory( test_dir, target_size=(48, 48), color_mode='grayscale', batch_size=32, class_mode='categorical' )
model = Sequential([ # 第一個卷積層組 Conv2D(64, (3, 3), padding='same', input_shape=(48, 48, 1), activation='relu'), BatchNormalization(), Conv2D(64, (3, 3), padding='same', activation='relu'), BatchNormalization(), MaxPooling2D(pool_size=(2, 2)), Dropout(0.15), # 增加dropout
# 第二個卷積層組
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15),
# 第三個卷積層組
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15),
# 全連接層
Flatten(),
Dense(512, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.6),
Dense(256, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.6),
Dense(7, activation='softmax')
為了提高模型的準確性,我們可以進一步調整一些超參數,或者將模型架構進行改進。以下是一些可行的建議和改進,逐行添加說明。
以下是改進的代碼示例,其中包括了一些新的調整和架構的改動:
你是不是過譽了 你竟然連七成都調不到
如果現有的模型無法達到預期的準確率,這可能是由於多種因素造成的,包括模型架構、數據集的質量和數量、超參數設置等。以下是一些更深入的建議,可以幫助提高模型的性能:
使用預訓練模型:
數據集的質量和數量:
調整模型架構:
超參數調整:
批標準化:
驗證集和測試集:
以下是如何加載一個預訓練模型的範例,這樣可以幫助在訓練開始時就擁有更好的特徵萃取能力:
from tensorflow.keras.applications import VGG16
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Flatten, Dropout
# 加載預訓練模型VGG16,不包含頂層全連接層
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(48, 48, 3))
# 添加自己的全連接層
x = base_model.output
x = Flatten()(x)
x = Dense(256, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(128, activation='relu')(x)
x = Dropout(0.5)(x)
predictions = Dense(7, activation='softmax')(x)
# 定義新模型
model = Model(inputs=base_model.input, outputs=predictions)
# 鎖定部分VGG16層
for layer in base_model.layers:
layer.trainable = False
# 編譯模型
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
在運用預訓練模型的時候,可能需要特別注意調整輸入數據的格式和大小,確保其符合預訓練模型的要求。通過這樣的增強和調整,有望得到高於之前的準確率。如果有其他的具體需求或者問題,隨時可以告訴我。
Not yet included in a published release.
import os
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
import matplotlib.pyplot as plt
# 如果你有安裝kagglehub可以取消註解這行並使用kagglehub下載數據集
# import kagglehub
# path = kagglehub.dataset_download("msambare/fer2013")
# 用這行代替上面的下載步驟,你需要手動下載數據集到以下路徑
path = "path_to_your_downloaded_dataset"
# 設置訓練和測試數據的路徑
train_dir = os.path.join(path, 'train')
test_dir = os.path.join(path, 'test')
# 確保資料夾存在
if not os.path.exists(train_dir) or not os.path.exists(test_dir):
raise FileNotFoundError("請確認資料夾路徑是否正確,並且資料已經下載。")
# 訓練數據的資料增強
train_datagen = ImageDataGenerator(
rescale=1.0/255.0, # 將像素值歸一化
rotation_range=20, # 圖像隨機旋轉的角度範圍
width_shift_range=0.2, # 圖像水平平移的範圍
height_shift_range=0.2, # 圖像垂直平移的範圍
shear_range=0.15, # 剪切變換的范圍
zoom_range=0.15, # 縮放範圍
horizontal_flip=True, # 隨機水平翻轉
fill_mode='nearest', # 填充缺失像素的策略
validation_split=0.2 # 設置訓練數據的20%爲驗證數據
)
# 測試數據僅需要重塑,不需要資料增強
test_datagen = ImageDataGenerator(rescale=1.0/255.0)
# 創建訓練數據生成器
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(48, 48), # 圖像尺寸
color_mode='grayscale', # 灰度圖像
batch_size=32, # 批次大小
class_mode='categorical', # 分類模式
subset='training' # 訓練子集
)
# 創建驗證數據生成器
validation_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(48, 48),
color_mode='grayscale',
batch_size=32,
class_mode='categorical',
subset='validation' # 驗證子集
)
# 創建測試數據生成器
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(48, 48),
color_mode='grayscale',
batch_size=32,
class_mode='categorical'
)
# 創建改進的卷積神經網路模型
model = Sequential([
# 第一個卷積模塊
Conv2D(64, (3, 3), padding='same', input_shape=(48, 48, 1), activation='relu'),
BatchNormalization(),
Conv2D(64, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15), # 較高概率dropout
# 第二個卷積模塊
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15),
# 第三個卷積模塊
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15),
# 全連接層
Flatten(),
Dense(512, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.6),
Dense(256, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.6),
Dense(7, activation='softmax') # 7分類情緒輸出
])
# 顯示模型結構
model.summary()
# 編譯模型,設置優化器、損失函數和評估指標
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005), # 減小學習率
loss='categorical_crossentropy',
metrics=['accuracy']
)
# 設置回調函數以防止過擬合及自動調整學習率
early_stopping = EarlyStopping(
monitor='val_loss',
patience=15,
restore_best_weights=True,
min_delta=0.0001
)
reduce_lr = ReduceLROnPlateau(
monitor='val_loss',
factor=0.2,
patience=5,
min_lr=1e-6,
verbose=1
)
# 開始訓練模型
history = model.fit(
train_generator,
validation_data=validation_generator,
epochs=100, # 若過擬合可減少
callbacks=[early_stopping, reduce_lr]
)
# 評估模型在測試數據上的表現
test_loss, test_accuracy = model.evaluate(test_generator)
print(f"Test Accuracy: {test_accuracy:.4f}")
# 訓練過程的準確率和損失可視化
plt.figure(figsize=(12, 4))
# 繪製準確率曲線
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
# 繪製損失曲線
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.tight_layout()
plt.show()
# 保存訓練好的模型
model.save('emotion_recognition_model.h5')
print("模型已保存為 'emotion_recognition_model.h5'")
確保你在運行代碼前已經完成以下準備:
path 變量中。這段代碼會先檢查數據集是否存在,然後通過資料增強和資料生成器來準備數據,再用改進的卷積神經網絡模型進行訓練,並保存最終的模型。調整 hyperparameters 以及模型結構可以進一步提高模型性能。
import kagglehub
import os
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
import matplotlib.pyplot as plt
# 使用 kagglehub 下載數據集
path = kagglehub.dataset_download("msambare/fer2013")
train_dir = os.path.join(path, 'train')
test_dir = os.path.join(path, 'test')
# 確保資料夾存在
if not os.path.exists(train_dir) or not os.path.exists(test_dir):
raise FileNotFoundError("請確認資料夾路徑是否正確,並且資料已經下載。")
# 資料增強 - 調整參數使其更合理
train_datagen = ImageDataGenerator(
rescale=1.0/255.0,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.15,
zoom_range=0.15,
horizontal_flip=True,
fill_mode='nearest',
validation_split=0.2
)
test_datagen = ImageDataGenerator(rescale=1.0/255.0)
# 創建訓練、驗證和測試生成器
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(48, 48),
color_mode='grayscale',
batch_size=32,
class_mode='categorical',
subset='training'
)
validation_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(48, 48),
color_mode='grayscale',
batch_size=32,
class_mode='categorical',
subset='validation'
)
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(48, 48),
color_mode='grayscale',
batch_size=32,
class_mode='categorical'
)
# 改進的模型架構
model = Sequential([
# 第一個卷積層組
Conv2D(64, (3, 3), padding='same', input_shape=(48, 48, 1), activation='relu'),
BatchNormalization(),
Conv2D(64, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15), # 增加dropout
# 第二個卷積層組
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15),
# 第三個卷積層組
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.15),
# 全連接層
Flatten(),
Dense(512, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.6),
Dense(256, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),
BatchNormalization(),
Dropout(0.6),
Dense(7, activation='softmax')
])
# 顯示模型摘要
model.summary()
# 編譯模型
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005),
loss='categorical_crossentropy',
metrics=['accuracy']
)
# 設置回調函數
early_stopping = EarlyStopping(
monitor='val_loss',
patience=15,
restore_best_weights=True,
min_delta=0.0001
)
reduce_lr = ReduceLROnPlateau(
monitor='val_loss',
factor=0.2,
patience=5,
min_lr=1e-6,
verbose=1
)
# 訓練模型
history = model.fit(
train_generator,
validation_data=validation_generator,
epochs=100,
callbacks=[early_stopping, reduce_lr]
)
# 評估模型
test_loss, test_accuracy = model.evaluate(test_generator)
print(f"Test Accuracy: {test_accuracy:.4f}")
# 訓練過程可視化
plt.figure(figsize=(12, 4))
# Accuracy plot
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
# Loss plot
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.tight_layout()
plt.show()
# 儲存模型
model.save('emotion_recognition_model.h5')
print("模型已保存為 'emotion_recognition_model.h5'")
這段代碼保持了你的原始路徑設置,確保使用 kagglehub 來下載和提取數據集。注意要先設定 Kaggle 的 API token 並安裝相關的 Python 包,以確保該代碼的正確運行。希望這能幫你順利完成模型訓練並達到更高的準確率。如果還有問題,請隨時告訴我!
])
model.summary()
model.compile( optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005), loss='categorical_crossentropy', metrics=['accuracy'] )
early_stopping = EarlyStopping( monitor='val_loss', patience=15, restore_best_weights=True, min_delta=0.0001 )
reduce_lr = ReduceLROnPlateau( monitor='val_loss', factor=0.2, patience=5, min_lr=1e-6, verbose=1 )
history = model.fit( train_generator, validation_data=validation_generator, epochs=100, callbacks=[early_stopping, reduce_lr] )
test_loss, test_accuracy = model.evaluate(test_generator) print(f"Test Accuracy: {test_accuracy:.4f}")
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1) plt.plot(history.history['accuracy'], label='Train Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.title('Model Accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend()
plt.subplot(1, 2, 2) plt.plot(history.history['loss'], label='Train Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.title('Model Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend()
plt.tight_layout() plt.show()
model.save('emotion_recognition_model.h5') print("模型已保存為 'emotion_recognition_model.h5'") 這只有65% 臭低能
import kagglehub
import os
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
import matplotlib.pyplot as plt
# 使用 kagglehub 下載數據集
path = kagglehub.dataset_download("msambare/fer2013")
train_dir = os.path.join(path, 'train')
test_dir = os.path.join(path, 'test')
# 確保資料夾存在
if not os.path.exists(train_dir) or not os.path.exists(test_dir):
raise FileNotFoundError("請確認資料夾路徑是否正確,並且資料已經下載。")
# 資料增強 - 增加一些亮度調整
train_datagen = ImageDataGenerator(
rescale=1.0/255.0,
rotation_range=30,
width_shift_range=0.3,
height_shift_range=0.3,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
brightness_range=[0.8, 1.2], # 增加亮度調整
fill_mode='nearest',
validation_split=0.2
)
test_datagen = ImageDataGenerator(rescale=1.0/255.0)
# 創建訓練、驗證和測試生成器
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(48, 48),
color_mode='grayscale',
batch_size=32,
class_mode='categorical',
subset='training'
)
validation_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(48, 48),
color_mode='grayscale',
batch_size=32,
class_mode='categorical',
subset='validation'
)
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(48, 48),
color_mode='grayscale',
batch_size=32,
class_mode='categorical'
)
# 改進的模型架構
model = Sequential([
# 第一個卷積層組
Conv2D(64, (3, 3), padding='same', input_shape=(48, 48, 1), activation='relu'),
BatchNormalization(),
Conv2D(64, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.2),
# 第二個卷積層組
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(128, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.2),
# 第三個卷積層組
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.3),
# 第四個卷積層組(新增加的)
Conv2D(512, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(512, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.3),
# 全連接層
Flatten(),
Dense(512, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)),
BatchNormalization(),
Dropout(0.5),
Dense(256, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)),
BatchNormalization(),
Dropout(0.5),
Dense(7, activation='softmax')
])
# 顯示模型摘要
model.summary()
# 編譯模型
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.0003), # 調整學習率
loss='categorical_crossentropy',
metrics=['accuracy']
)
# 設置回調函數
early_stopping = EarlyStopping(
monitor='val_loss',
patience=10, # 減少 patience
restore_best_weights=True,
min_delta=0.0001
)
reduce_lr = ReduceLROnPlateau(
monitor='val_loss',
factor=0.1, # 更緩慢的學習率減少
patience=5,
min_lr=1e-6,
verbose=1
)
# 訓練模型
history = model.fit(
train_generator,
validation_data=validation_generator,
epochs=100,
callbacks=[early_stopping, reduce_lr]
)
# 評估模型
test_loss, test_accuracy = model.evaluate(test_generator)
print(f"Test Accuracy: {test_accuracy:.4f}")
# 訓練過程可視化
plt.figure(figsize=(12, 4))
# Accuracy plot
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
# Loss plot
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.tight_layout()
plt.show()
# 儲存模型
model.save('emotion_recognition_model.h5')
print("模型已保存為 'emotion_recognition_model.h5'")
這些改動可能有助於提高模型的準確性。如果仍然無法達到滿意的準確率,考慮使用更複雜的模型架構或更大的數據集來進行訓練。