-
Notifications
You must be signed in to change notification settings - Fork 0
/
mnist_keras.py
75 lines (58 loc) · 2.74 KB
/
mnist_keras.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
66
67
68
69
70
71
72
73
74
75
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""MNIST dataset provider."""
# From Python 3.9 and onward, `tuple`, `list` and other collection classes can
# also function as generic class types (see PEP 585).
#
# Once we no longer need to support Python 3.7 or 3.8, we can remove this syntax
# (added in PEP 563) for Python 3.7 and higher.
from __future__ import annotations
import numpy as np
from tensorflow import keras
class MNIST:
x_train_raw_data: np.ndarray
x_test_raw_data: np.ndarray
y_train_raw_data: np.ndarray
y_test_raw_data: np.ndarray
num_classes: int
def __init__(self):
train_data, test_data = keras.datasets.mnist.load_data()
self.x_train_raw_data, self.y_train_raw_data = train_data
self.x_test_raw_data, self.y_test_raw_data = test_data
self.num_classes = 10
def _scale_custom(self, array: np.ndarray,
target_range: tuple[float, float]) -> np.ndarray:
lower_bound, upper_bound = target_range
assert lower_bound < upper_bound, f'range {target_range} must be (low, high) with low < high'
return array * (upper_bound - lower_bound) + lower_bound
def x_train_raw(self) -> np.ndarray:
return self.x_train_raw_data
def x_train_scale_0_1(self) -> np.ndarray:
return self.x_train_raw().astype('float32') / 255.0
def x_train_scale_custom(self, target_range: tuple[float, float]) -> np.ndarray:
return self._scale_custom(self.x_train_scale_0_1(), target_range)
def x_test_raw(self) -> np.ndarray:
return self.x_test_raw_data
def x_test_scale_0_1(self) -> np.ndarray:
return self.x_test_raw_data.astype('float32') / 255.0
def x_test_scale_custom(self, target_range: tuple[float, float]) -> np.ndarray:
return self._scale_custom(self.x_test_scale_0_1(), target_range)
def y_train_raw(self) -> np.ndarray:
return self.y_train_raw_data
def y_train_categorical(self) -> np.ndarray:
return keras.utils.to_categorical(self.y_train_raw(), self.num_classes)
def y_test_raw(self) -> np.ndarray:
return self.y_test_raw_data
def y_test_categorical(self) -> np.ndarray:
return keras.utils.to_categorical(self.y_test_raw(), self.num_classes)