text_plain_output_1.png
from PIL import Image

from PIL import Image

from keras.preprocessing import image

from os import listdir

from tensorflow import keras

from tensorflow.keras import layers

import cv2

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import numpy as np

import tensorflow as tf

learning_rate = 0.001
weight_decay = 0.0001
batch_size = 256
num_epochs = 300
image_size = 72
patch_size = 5
num_patches = (image_size // patch_size) ** 2
projection_dim = 64
num_heads = 4
transformer_units = [projection_dim * 2, projection_dim]
transformer_layers = 8
mlp_head_units = [2048, 1024]

INIT_LR = 0.001
BS = 32
default_image_size = tuple((72, 72))
image_size = 72
directory_root = '../input/brain-tumor-classification-mri/Training'
width = 256
height = 256
depth = 3

def convert_image_to_array(image_dir):
    try:
        image = cv2.imread(image_dir)
        if image is not None:
            image = cv2.resize(image, default_image_size)
            image = cv2.convertScaleAbs(image, alpha=1.2, beta=0)
            return image.astype(np.uint8)
        else:
            return np.array([])
    except Exception as e:
        return None

image_list, label_list = ([], [])
try:
    root_dir = listdir(directory_root)
    brain_folder_list = listdir(f'{directory_root}/')
    for brain_folder in brain_folder_list:
        brain_image_list = listdir(f'{directory_root}/{brain_folder}/')
        for image in brain_image_list[:500]:
            image_directory = f'{directory_root}/{brain_folder}/{image}'
            if image_directory.endswith('.jpg') == True or image_directory.endswith('.JPG') == True:
                image_list.append(convert_image_to_array(image_directory))
                label_list.append(brain_folder)
                exit
except Exception as e:

np_image_list = np.array(image_list, dtype=np.uint8)

from PIL import Image
import matplotlib.pyplot as plt

from PIL import Image
import matplotlib.pyplot as plt

data_augmentation = keras.Sequential([layers.experimental.preprocessing.Normalization(), layers.experimental.preprocessing.Resizing(image_size, image_size), layers.experimental.preprocessing.RandomFlip('horizontal'), layers.experimental.preprocessing.RandomRotation(factor=0.02), layers.experimental.preprocessing.RandomZoom(height_factor=0.2, width_factor=0.2)], name='data_augmentation')
data_augmentation.layers[0].adapt(x_train)

def mlp(x, hidden_units, dropout_rate):
    for units in hidden_units:
        x = layers.Dense(units, activation=tf.nn.gelu)(x)
        x = layers.Dropout(dropout_rate)(x)
    return x

class Patches(layers.Layer):
    def __init__(self, patch_size):
        super(Patches, self).__init__()
        self.patch_size = patch_size
    def call(self, images):
        batch_size = tf.shape(images)[0]
        patches = tf.image.extract_patches(images=images, sizes=[1, self.patch_size, self.patch_size, 1], strides=[1, self.patch_size, self.patch_size, 1], rates=[1, 1, 1, 1], padding='VALID')
        patch_dims = patches.shape[-1]
        patches = tf.reshape(patches, [batch_size, -1, patch_dims])
        return patches

import matplotlib.pyplot as plt
plt.figure(figsize=(4, 4))
image = x_train[np.random.choice(range(x_train.shape[0]))]
print(x_train[0])
plt.imshow(image.astype('uint8'))
plt.axis('off')
resized_image = tf.image.resize(tf.convert_to_tensor([image]), size=(image_size, image_size))
patches = Patches(patch_size)(resized_image)
print(f'Image size: {image_size} X {image_size}')
print(f'Patch size: {patch_size} X {patch_size}')
print(f'Patches per image: {patches.shape[1]}')
print(f'Elements per patch: {patches.shape[-1]}')
n = int(np.sqrt(patches.shape[1]))
plt.figure(figsize=(4, 4))
for i, patch in enumerate(patches[0]):
    ax = plt.subplot(n, n, i + 1)
    patch_img = tf.reshape(patch, (patch_size, patch_size, 3))
    plt.imshow(patch_img.numpy().astype('uint8'))
    plt.axis('off')