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
input_train = input_train.astype("float32") / 255
input_test = input_test.astype("float32") / 255
acc_per_fold = []
loss_per_fold = []
inputs = np.concatenate((input_train, input_test), axis=0)
targets = np.concatenate((target_train, target_test), axis=0)
kfold = KFold(n_splits=num_folds, shuffle=True)
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)
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,)這個錯誤想請問厲害各位我該怎麼解決這個錯誤
非常感謝