Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

b. Write a function that can shift an MNIST image in any direction (left, right,

ID: 3749633 • Letter: B

Question

b. Write a function that can shift an MNIST image in any direction (left, right, up, or down) by one pixel Then, for each image in the training set, create four shifted copies (one per direction) and add them to the training set. Finally, train your best model on this expanded training set and measure its accuracy on the test set. You can use the shift) function from the scipy.ndimage.interpolation module. For example, shift image, [2, 1], cval-0) shifts the image 2 pixels down and 1 pixel to the right.

Explanation / Answer

MNIST is a data set,which consist images of hand written digits from 0 to 9.MNIST images are in the shape of(28*28) and flattended into (none*784) here none indicates it would be of any size

We need two function,the 1st one to adjust the center of mass which is a function in the library ndimage from scipy

def getBestShift(img):

Cy Cx=ndimage.measurements.center of mass$img)

rows,cols=image.shape

Shift x=np.round(col/2.0-Cx).astype(int)

Shift y=np.round(col/2.0-Cy).astype(int)

returnShiftx.Shifty

The 2nd function i.e,warpAffine function used to shift the images in the given direction

Here is the matrix to shift the image

M=( 1 0 Sx 0 1 Sy)

def Shift(image Sx Sy):

rows cols=image.shape

M=np.float32([[1,0,Sx],[0,1Sy]])

Shifted=cv2.WarpAffine(img,M,rows,cols)

return Shifted