Type Conversion, Centering and Scaling

Set the type to np.float32.

Important: One of the main reasons being that the weights will all be of type float, and multiplication between floating numbers is much faster than between an integer and a float. So it's better to convert the input to type float.

For centering, we subtract the dataset by 127.5. The values in the dataset will now range between -127.5 to 127.5

For scaling, we divide the centered dataset by half of the maximum pixel value in the dataset i.e 255/2. This will result in a dataset with values ranging between -1 and 1.

# Converting integer values to float types 
X_train = X_train.astype(np.float32)
X_test = X_test.astype(np.float32)

# Scaling and centering
X_train = (X_train - 127.5) / 127.5
X_test = (X_test - 127.5)/ 127.5
print('Maximum pixel value in the training_set after Centering and Scaling: ', np.max(X_train))
print('Minimum pixel value in the training_set after Centering and Scaling: ', np.min(X_train))

Let's define a function to rescale the pixel values of the scaled image to range between 0 and 255.

Matplotlib Tip: Rescaling needs to be done so that you avoid errors with matplotlib if you were to use the scaled image as is without upscaling.
# Rescale the pixel values (0 and 255)
def upscale(image):
return (image*127.5 + 127.5).astype(np.uint8)

# Lets see if this works
z = upscale(X_train[0])
print('Maximum pixel value after upscaling scaled image: ',np.max(z))
print('Maximum pixel value after upscaling scaled image: ',np.min(z))

A plot of 9 centered and scaled images after upscaling...

for i in range(0, 9):
plt.subplot(331+i) # plot of 3 rows and 3 columns
plt.axis('off') # turn off axis
plt.imshow(upscale(X_train[i]), cmap='gray') # gray scale
Figure 14.4: Plot of nine centered and scaled MNIST digits after upscaling 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.233.153