-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1.py
65 lines (48 loc) · 1.84 KB
/
part1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# part 1
import numpy as np
import matplotlib.pyplot as plt
# A function to plot images
def show_image(img):
image = img.reshape((28, 28))
plt.imshow(image, 'gray')
# Reading The Train Set then return train_set and test_set
def reading_files():
train_images_file = open('train-images.idx3-ubyte', 'rb')
train_images_file.seek(4)
num_of_train_images = int.from_bytes(train_images_file.read(4), 'big')
train_images_file.seek(16)
train_labels_file = open('train-labels.idx1-ubyte', 'rb')
train_labels_file.seek(8)
train_set = []
for n in range(num_of_train_images):
image = np.zeros((784, 1))
for i in range(784):
image[i, 0] = int.from_bytes(train_images_file.read(1), 'big') / 256
label_value = int.from_bytes(train_labels_file.read(1), 'big')
label = np.zeros((10, 1))
label[label_value, 0] = 1
train_set.append((image, label))
train_set.append((image, label))
# Reading The Test Set
test_images_file = open('t10k-images.idx3-ubyte', 'rb')
test_images_file.seek(4)
test_labels_file = open('t10k-labels.idx1-ubyte', 'rb')
test_labels_file.seek(8)
num_of_test_images = int.from_bytes(test_images_file.read(4), 'big')
test_images_file.seek(16)
test_set = []
for n in range(num_of_test_images):
image = np.zeros((784, 1))
for i in range(784):
image[i] = int.from_bytes(test_images_file.read(1), 'big') / 256
label_value = int.from_bytes(test_labels_file.read(1), 'big')
label = np.zeros((10, 1))
label[label_value, 0] = 1
test_set.append((image, label))
return train_set, test_set
if __name__ == "__main__":
# Plotting an image
train_set, test_set = reading_files()
show_image(train_set[5][0])
plt.show()
print(np.argmax(train_set[5][1]))