Why is my test accuracy always 0 when I am training my model with keras?

I am generating a model to read QR codes. I figured that I kept receiving a test accuracy of 0 and a training accuracy of 1.0 due to overfitting. Once I reduced the layers in my CNN, I got a training accuracy of 98% and training loss of 3, while a testing accuracy of 0% and a testing loss of 6.

Here is my code:

# generating QR codes (10 for now)  
base = 'hello'
qr_folder = 'QR Code Images'

os.makedirs(qr_folder, exist_ok = True)

for i in range (1,301): 
    data = f'{base} {i}'
    img = qrcode.make(data)
    img.save(os.path.join(qr_folder, f'QR Code Image {i}.png'))

# preprocess qr code images 
def load_images (image_folder):
    # initilaize images and labels
    images = []
    labels = []
    for file_name in os.listdir(image_folder):
        if file_name.endswith('.png'):
            img_path = os.path.join(image_folder, file_name)
            img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
            img = cv2.resize(img, (128,128))
            images.append(img)
            # file name will be the label
            labels.append(file_name.split('.')[0])
    return np.array(images), np.array(labels)

images, labels = load_images(qr_folder)
images = images/255.0 

images = np.expand_dims(images, axis=-1)

# convert labels to numerical format
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(labels)

# split into training and testing - 20% testing, 80% training
X_train, X_test, y_train, y_test = train_test_split(images, y_encoded, test_size = 0.2, random_state = 42) # for now random state will be 42, after debugging - change to none 

# data augmentation
datagen = ImageDataGenerator(
    rotation_range = 20,
    width_shift_range = 0.2,
    height_shift_range = 0.2,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True,
    fill_mode = 'nearest'
)

datagen.fit(X_train)

# create a CNN w/ tensorflow - add more layers model is too simple 
model = tf.keras.Sequential([
    tf.keras.layers.InputLayer(shape = (128, 128, 1)),
    tf.keras.layers.Conv2D(filters = 32, kernel_size = 3, activation = 'relu', kernel_regularizer = tf.keras.regularizers.l2(0.001)),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Conv2D(filters = 64, kernel_size = 3, activation = 'relu', kernel_regularizer = tf.keras.regularizers.l2(0.001)),
    tf.keras.layers.MaxPooling2D(), 
    tf.keras.layers.Conv2D(filters = 128, kernel_size = 3, activation = 'relu', kernel_regularizer = tf.keras.regularizers.l2(0.0001)),
    #tf.keras.layers.MaxPooling2D(),
    #tf.keras.layers.Conv2D(filters = 64, kernel_size = 6, activation = 'relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)),
    #tf.keras.layers.MaxPooling2D(),
    #tf.keras.layers.Conv2D(filters = 128, kernel_size = 6, activation = 'relu'),
    tf.keras.layers.Flatten(),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Dense(256, activation = 'relu', kernel_regularizer = tf.keras.regularizers.l2(0.001)),
    tf.keras.layers.Dropout(0.5), # add in regularization constant 
    tf.keras.layers.Dense(300, activation = 'softmax')
    #tf.keras.layers.Dense(20, activation = 'sigmoid')
])

model.summary()

# compile model
model.compile(optimizer = tf.keras.optimizers.AdamW(learning_rate = 0.0001),
              loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits = False),
              metrics = ['accuracy'])
              #metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])

# early stopping
#early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience = 5, restore_best_weights = True)


# train model changed to 10
history = model.fit(X_train, y_train, epochs = 20, validation_data = (X_test, y_test)) # callbacks = [early_stopping]) 


# something's wrong - plot the training accuracy and loss 
plt.plot(history.history['accuracy'], label = 'accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0, 1])
plt.legend(loc='lower right')

plt.show()

# evaluate model
test_loss, test_acc = model.evaluate(X_test, y_test)
train_loss, train_acc = model.evaluate(X_train, y_train)
print(f'Test accuracy: {test_acc}')
print(f'Testing loss: {test_loss}')
print(f'Training loss: {train_loss}')
print(f'Training accuracy: {train_acc}')

New contributor

Riju Sinha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật