MCPcopy Create free account
hub / github.com/tensorflow/tfjs-examples / MnistData

Class MnistData

mnist-core/data.js:40–146  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

38 * manipulation manually.
39 */
40export class MnistData {
41 constructor() {
42 this.shuffledTrainIndex = 0;
43 this.shuffledTestIndex = 0;
44 }
45
46 async load() {
47 // Make a request for the MNIST sprited image.
48 const img = new Image();
49 const canvas = document.createElement('canvas');
50 const ctx = canvas.getContext('2d');
51 const imgRequest = new Promise((resolve, reject) => {
52 img.crossOrigin = '';
53 img.onload = () => {
54 img.width = img.naturalWidth;
55 img.height = img.naturalHeight;
56
57 const datasetBytesBuffer =
58 new ArrayBuffer(NUM_DATASET_ELEMENTS * IMAGE_SIZE * 4);
59
60 const chunkSize = 5000;
61 canvas.width = img.width;
62 canvas.height = chunkSize;
63
64 for (let i = 0; i < NUM_DATASET_ELEMENTS / chunkSize; i++) {
65 const datasetBytesView = new Float32Array(
66 datasetBytesBuffer, i * IMAGE_SIZE * chunkSize * 4,
67 IMAGE_SIZE * chunkSize);
68 ctx.drawImage(
69 img, 0, i * chunkSize, img.width, chunkSize, 0, 0, img.width,
70 chunkSize);
71
72 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
73
74 for (let j = 0; j < imageData.data.length / 4; j++) {
75 // All channels hold an equal value since the image is grayscale, so
76 // just read the red channel.
77 datasetBytesView[j] = imageData.data[j * 4] / 255;
78 }
79 }
80 this.datasetImages = new Float32Array(datasetBytesBuffer);
81
82 resolve();
83 };
84 img.src = MNIST_IMAGES_SPRITE_PATH;
85 });
86
87 const labelsRequest = fetch(MNIST_LABELS_PATH);
88 const [imgResponse, labelsResponse] =
89 await Promise.all([imgRequest, labelsRequest]);
90
91 this.datasetLabels = new Uint8Array(await labelsResponse.arrayBuffer());
92
93 // Create shuffled indices into the train/test set for when we select a
94 // random dataset element for training / validation.
95 this.trainIndices = tf.util.createShuffledIndices(NUM_TRAIN_ELEMENTS);
96 this.testIndices = tf.util.createShuffledIndices(NUM_TEST_ELEMENTS);
97

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected