iT邦幫忙

0

python cnn 交叉驗證

def read_directory(directory_name):
list_of_ans=[]
list_of_img=[]
for filename in os.listdir(directory_name):
img=cv2.imread(directory_name+"/"+filename)
img_resize = cv2.resize(img,(32,32))
list_of_img.append(img_resize)
list_of_ans.append(int(filename.split('.')[0])-1)
array_of_img = np.array(list_of_img,dtype="float32")
return(array_of_img,list_of_ans)

指定亂數種子

seed = 14
np.random.seed(14)

載入資料集

img_width, img_height, img_num_channels = 32, 32, 3
(input_train,target_train)=read_directory(r"C:\Users\COSH\Desktop\Ch09\train")
(input_test, target_test)=read_directory(r"C:\Users\COSH\Desktop\Ch09\test")
input_shape = (img_width, img_height, img_num_channels)
epochs=10
batch_size=10
verbose=1
num_folds = 10
no_classes = 14
loss_function = sparse_categorical_crossentropy

因為是固定範圍, 所以執行正規化, 從 0-255 至 0-1

input_train = input_train.astype("float32") / 255
input_test = input_test.astype("float32") / 255

acc_per_fold = []
loss_per_fold = []

Merge inputs and targets

inputs = np.concatenate((input_train, input_test), axis=0)
targets = np.concatenate((target_train, target_test), axis=0)

Define the K-fold Cross Validator

kfold = KFold(n_splits=num_folds, shuffle=True)

K-fold Cross Validation model evaluation

fold_no = 1
for train, test in kfold.split(inputs, targets):
# One-hot編碼
target_train = to_categorical(target_train)
target_test= to_categorical(target_test)

定義模型

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), padding="same",
             input_shape=input_shape, activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, kernel_size=(3, 3), padding="same",
             activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=(3, 3), padding="same",
             activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation="relu"))
model.add(Dense(no_classes, activation="softmax"))
model.summary()   # 顯示模型摘要資訊

編譯模型

model.compile(loss=loss_function, 
              optimizer="adam",
              metrics=["accuracy"])
print('------------------------------------------------------------------------')
print(f'Training for fold {fold_no} ...')

訓練模型

history = model.fit(inputs[train], targets[train],
                batch_size=batch_size,
                epochs=epochs,
                verbose=verbose)

Generate generalization metrics

scores = model.evaluate(inputs[train], targets[train], verbose=0)
print(f'Score for fold {fold_no}: {model.metrics_names[0]} of {scores[0]}; {model.metrics_names[1]} of {scores[1]*100}%')
acc_per_fold.append(scores[1] * 100)
loss_per_fold.append(scores[0])
 # Increase fold number
fold_no = fold_no + 1

在跑的時候都會跑出Error when checking target: expected dense_4 to have shape (14,) but got array with shape (1,)這個錯誤想請問厲害各位我該怎麼解決這個錯誤
非常感謝

model.add(Conv2D(64, kernel_size=(3, 3), padding="same", activation="relu"))這行嗎?
9a715072 iT邦新手 5 級 ‧ 2021-04-11 00:54:56 檢舉
他的錯誤是顯示model.add(Dense(no_classes, activation="softmax"))這行
把訓練資料跟測試資料的形狀輸出出來你應該就會發現問題了。

尚未有邦友回答

立即登入回答