turns-00050.parquet:26266
3117231d1b97a806392eec75
turn 4/6gpt-4o-2024-08-06ChineseTaiwan305 words
degenerate_repetitionAbsentFinal dense release
USER
北七 你亂改我的路徑喔
ASSISTANT
抱歉,我最初的代碼示例中更改了下載路徑,這可能引起了誤解。下面是代碼的修正版本,保留了你原有的設置。請確保 `kagglehub` 模塊已正確安裝並配置你的 Kaggle API token 才能正常工作。
```python
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 包,以確保該代碼的正確運行。希望這能幫你順利完成模型訓練並達到更高的準確率。如果還有問題,請隨時告訴我!