|
| 1 | +// Copyright 2018 The TensorFlow Authors. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import XCTest |
| 16 | +import Python |
| 17 | +@testable import DeepLearning |
| 18 | + |
| 19 | +let gzip = Python.import("gzip") |
| 20 | +let np = Python.import("numpy") |
| 21 | + |
| 22 | +func readImagesFile(_ filename: String) -> [Float] { |
| 23 | + let file = gzip.open(filename, "rb").read() |
| 24 | + let data = np.frombuffer(file, dtype: np.uint8, offset: 16) |
| 25 | + let array = data.astype(np.float32) / 255 |
| 26 | + return Array(numpyArray: array)! |
| 27 | +} |
| 28 | + |
| 29 | +func readLabelsFile(_ filename: String) -> [Int32] { |
| 30 | + let file = gzip.open(filename, "rb").read() |
| 31 | + let data = np.frombuffer(file, dtype: np.uint8, offset: 8) |
| 32 | + let array = data.astype(np.int32) |
| 33 | + return Array(numpyArray: array)! |
| 34 | +} |
| 35 | + |
| 36 | +/// Reads MNIST images and labels from specified file paths. |
| 37 | +func readMNIST(imagesFile: String, labelsFile: String) |
| 38 | + -> (images: Tensor<Float>, labels: Tensor<Int32>) { |
| 39 | + print("Reading data.") |
| 40 | + let images = readImagesFile(imagesFile) |
| 41 | + let labels = readLabelsFile(labelsFile) |
| 42 | + let rowCount = Int32(labels.count) |
| 43 | + let columnCount = Int32(images.count) / rowCount |
| 44 | + |
| 45 | + print("Constructing data tensors.") |
| 46 | + let imagesTensor = Tensor(shape: [rowCount, columnCount], scalars: images) / 255 |
| 47 | + let labelsTensor = Tensor(labels) |
| 48 | + return (imagesTensor, labelsTensor) |
| 49 | +} |
| 50 | + |
| 51 | +struct MNISTClassifier: Layer { |
| 52 | + var l1, l2: Dense<Float> |
| 53 | + init(hiddenSize: Int) { |
| 54 | + l1 = Dense<Float>(inputSize: 784, outputSize: hiddenSize) |
| 55 | + l2 = Dense<Float>(inputSize: hiddenSize, outputSize: 10) |
| 56 | + } |
| 57 | + func applied(to input: Tensor<Float>) -> Tensor<Float> { |
| 58 | + let h1 = sigmoid(l1.applied(to: input)) |
| 59 | + return logSoftmax(l2.applied(to: h1)) |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +final class MNISTTests: XCTestCase { |
| 64 | + func testMNIST() { |
| 65 | + // Get training data. |
| 66 | + let (images, numericLabels) = readMNIST(imagesFile: "train-images-idx3-ubyte.gz", |
| 67 | + labelsFile: "train-labels-idx1-ubyte.gz") |
| 68 | + let labels = Tensor<Float>(oneHotAtIndices: numericLabels, depth: 10) |
| 69 | + |
| 70 | + let batchSize = images.shape[0] |
| 71 | + let optimizer = RMSProp<MNISTClassifier, Float>(learningRate: 0.2) |
| 72 | + var classifier = MNISTClassifier(hiddenSize: 30) |
| 73 | + |
| 74 | + // Hyper-parameters. |
| 75 | + let epochCount = 20 |
| 76 | + let minibatchSize: Int32 = 10 |
| 77 | + let learningRate: Float = 0.2 |
| 78 | + var loss = Float.infinity |
| 79 | + |
| 80 | + // Training loop. |
| 81 | + print("Begin training for \(epochCount) epochs.") |
| 82 | + |
| 83 | + func minibatch<Scalar>(_ x: Tensor<Scalar>, index: Int32) -> Tensor<Scalar> { |
| 84 | + let start = index * minibatchSize |
| 85 | + return x[start..<start+minibatchSize] |
| 86 | + } |
| 87 | + |
| 88 | + for epoch in 0...epochCount { |
| 89 | + // Store information for printing accuracy and loss. |
| 90 | + var correctPredictions = 0 |
| 91 | + var totalLoss: Float = 0 |
| 92 | + |
| 93 | + let iterationCount = batchSize / minibatchSize |
| 94 | + for i in 0..<iterationCount { |
| 95 | + let images = minibatch(images, index: i) |
| 96 | + let numericLabels = minibatch(numericLabels, index: i) |
| 97 | + let labels = minibatch(labels, index: i) |
| 98 | + |
| 99 | + let (loss, 𝛁model) = classifier.valueWithGradient { classifier -> Tensor<Float> in |
| 100 | + let ŷ = classifier.applied(to: images) |
| 101 | + |
| 102 | + // Update number of correct predictions. |
| 103 | + let correctlyPredicted = ŷ.argmax(squeezingAxis: 1) .== numericLabels |
| 104 | + correctPredictions += Int(Tensor<Int32>(correctlyPredicted).sum().scalarized()) |
| 105 | + |
| 106 | + return -(labels * ŷ).sum() / Tensor(10) |
| 107 | + } |
| 108 | + optimizer.update(&classifier.allDifferentiableVariables, along: 𝛁model) |
| 109 | + totalLoss += loss.scalarized() |
| 110 | + } |
| 111 | + print(""" |
| 112 | + [Epoch \(epoch)] \ |
| 113 | + Accuracy: \(correctPredictions)/\(batchSize) \ |
| 114 | + (\(Float(correctPredictions) / Float(batchSize)))\t\ |
| 115 | + Loss: \(totalLoss / Float(batchSize)) |
| 116 | + """) |
| 117 | + } |
| 118 | + print("Done training MNIST.") |
| 119 | + } |
| 120 | + |
| 121 | + static var allTests = [ |
| 122 | + ("testMNIST", testMNIST), |
| 123 | + ] |
| 124 | +} |
0 commit comments