# Untitled

unknown
python
a year ago
2.6 kB
5
Indexable
Never
```import os
import numpy as np
from PIL import Image
import pandas as pd
import tensorflow as tf
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.layers import ELU
from tensorflow.keras.regularizers import l1, l2
import matplotlib.pyplot as plt

# 從檔案中載入 X_train 和 Y_train

# 對Y_train進行One-Hot編碼
Y_train_encoded = tf.keras.utils.to_categorical(Y_train, num_classes=4)

# 載入VGG16模型
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))

# 創建模型
model = Sequential()

# 凍結VGG16的權重
base_model.trainable = False

# 編譯模型
optimizer = RMSprop(learning_rate=0.00015, rho=0.95, momentum=0.1, epsilon=1e-07)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])

# 將 X_train 轉換為二維陣列
X_train_2d = X_train.reshape(X_train.shape[0], -1)

# 創建歸一化器
scaler = MinMaxScaler()

# 對 X_train_2d 進行歸一化
X_train_normalized = scaler.fit_transform(X_train_2d)

# 將歸一化後的資料重新轉換為原本的形狀
X_train_normalized = X_train_normalized.reshape(X_train.shape)

# 訓練模型並獲取 history 物件
history = model.fit(X_train_normalized, Y_train_encoded, batch_size=64, epochs=100, validation_split=0.2)

# 記錄訓練和驗證的損失和準確度
train_loss = history.history['loss']
val_loss = history.history['val_loss']
train_acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

# 繪製學習曲線
plt.plot(train_loss, label='train_loss')
plt.plot(val_loss, label='val_loss')
plt.title('training')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.legend()
plt.show()

# 繪製驗證曲線
plt.plot(train_acc, label='train_acc')
plt.plot(val_acc, label='val_acc')
plt.title('validation')
plt.xlabel('epoch')
plt.ylabel('acc')
plt.legend()
plt.show()
```