This repository was archived by the owner on Apr 23, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 150
First steps in repository reorganization: extracting common MNIST dataset code #182
Merged
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
be265f0
Extracted MNIST dataset, created LeNet network, added example combini…
BradLarson bdaeb65
Extracted redundant MNIST loading code from GAN and Autoencoder examp…
BradLarson 370381e
Renamed input parameters and applied standard formatting style to MNIST.
BradLarson 4bd960c
Punctuation correction.
BradLarson d5fdcb3
README formatting update.
BradLarson 81ec5ad
Renamed trainImages -> trainingImages, corrected Python package names…
BradLarson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| // Copyright 2019 The TensorFlow Authors. All Rights Reserved. | ||
| // | ||
| // 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. | ||
|
|
||
| import Foundation | ||
| import TensorFlow | ||
|
|
||
| public struct MNIST { | ||
| public let trainImages: Tensor<Float> | ||
| public let trainLabels: Tensor<Int32> | ||
| public let testImages: Tensor<Float> | ||
| public let testLabels: Tensor<Int32> | ||
|
|
||
| public let trainingSize: Int | ||
| public let testSize: Int | ||
|
|
||
| let batchSize: Int | ||
|
BradLarson marked this conversation as resolved.
Outdated
|
||
|
|
||
| public init(batchSize: Int, flatten: Bool = false, normalize: Bool = false) { | ||
|
BradLarson marked this conversation as resolved.
Outdated
|
||
| self.batchSize = batchSize | ||
|
|
||
| let (trainImages, trainLabels) = readMNIST(imagesFile: "train-images-idx3-ubyte", | ||
| labelsFile: "train-labels-idx1-ubyte", | ||
| flatten: flatten, | ||
| normalize: normalize) | ||
| self.trainImages = trainImages | ||
| self.trainLabels = trainLabels | ||
| self.trainingSize = Int(trainLabels.shape[0]) | ||
|
|
||
| let (testImages, testLabels) = readMNIST(imagesFile: "t10k-images-idx3-ubyte", | ||
| labelsFile: "t10k-labels-idx1-ubyte", | ||
| flatten: flatten, | ||
| normalize: normalize) | ||
| self.testImages = testImages | ||
| self.testLabels = testLabels | ||
| self.testSize = Int(testLabels.shape[0]) | ||
| } | ||
| } | ||
|
|
||
| public extension Tensor { | ||
| func minibatch(at index: Int, batchSize: Int) -> Tensor { | ||
| let start = index * batchSize | ||
| return self[start..<start+batchSize] | ||
| } | ||
| } | ||
|
|
||
| /// Reads a file into an array of bytes. | ||
| func readFile(_ path: String, possibleDirectories: [String]) -> [UInt8] { | ||
| for folder in possibleDirectories { | ||
| let parent = URL(fileURLWithPath: folder) | ||
| let filePath = parent.appendingPathComponent(path) | ||
| guard FileManager.default.fileExists(atPath: filePath.path) else { | ||
| continue | ||
| } | ||
| let data = try! Data(contentsOf: filePath, options: []) | ||
| return [UInt8](data) | ||
| } | ||
| print("File not found: \(path)") | ||
| exit(-1) | ||
| } | ||
|
|
||
| /// Reads MNIST images and labels from specified file paths. | ||
| func readMNIST(imagesFile: String, labelsFile: String, flatten: Bool, normalize: Bool) -> (images: Tensor<Float>, | ||
|
BradLarson marked this conversation as resolved.
Outdated
|
||
| labels: Tensor<Int32>) { | ||
| print("Reading data from files: \(imagesFile), \(labelsFile)") | ||
|
BradLarson marked this conversation as resolved.
Outdated
|
||
| let images = readFile(imagesFile, possibleDirectories: [".", "./Datasets/MNIST"]).dropFirst(16).map(Float.init) | ||
| let labels = readFile(labelsFile, possibleDirectories: [".", "./Datasets/MNIST"]).dropFirst(8).map(Int32.init) | ||
| let rowCount = labels.count | ||
| let imageHeight = 28, imageWidth = 28 | ||
|
|
||
| print("Constructing data tensors.") | ||
|
|
||
| if flatten { | ||
| if normalize { | ||
|
BradLarson marked this conversation as resolved.
Outdated
|
||
| return ( | ||
| images: Tensor(shape: [rowCount, imageHeight * imageWidth], scalars: images) / 255.0 * 2 - 1, | ||
| labels: Tensor(labels) | ||
| ) | ||
| } else { | ||
| return ( | ||
| images: Tensor(shape: [rowCount, imageHeight * imageWidth], scalars: images) / 255.0, | ||
| labels: Tensor(labels) | ||
| ) | ||
| } | ||
| } else { | ||
| return ( | ||
| images: Tensor(shape: [rowCount, 1, imageHeight, imageWidth], scalars: images) | ||
| .transposed(withPermutations: [0, 2, 3, 1]) / 255, // NHWC | ||
| labels: Tensor(labels) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # LeNet-5 with MNIST | ||
|
|
||
| This example demonstrates how to train the [LeNet-5 network]( http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf) against the [MNIST digit classification dataset](http://yann.lecun.com/exdb/mnist/). | ||
|
|
||
| The LeNet network is instantiated from the ImageClassificationModels library of standard models, and applied to an instance of the MNIST dataset. A custom training loop is defined, and the training and test losses and accuracies for each epoch are shown during training. | ||
|
|
||
|
|
||
| ## Setup | ||
|
|
||
| To begin, you'll need the [latest version of Swift for | ||
| TensorFlow](https://github.com/tensorflow/swift/blob/master/Installation.md) | ||
| installed. Make sure you've added the correct version of `swift` to your path. | ||
|
|
||
| To train the model, run: | ||
|
|
||
| ``` | ||
|
BradLarson marked this conversation as resolved.
Outdated
|
||
| cd swift-models | ||
| swift run -c release LeNet-MNIST | ||
| ``` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| // Copyright 2019 The TensorFlow Authors. All Rights Reserved. | ||
| // | ||
| // 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. | ||
|
|
||
| import TensorFlow | ||
| import ImageClassificationModels | ||
| import Datasets | ||
|
|
||
| let epochCount = 12 | ||
| let batchSize = 128 | ||
|
|
||
| let dataset = MNIST(batchSize: batchSize) | ||
| var classifier = LeNet() | ||
|
|
||
| let optimizer = SGD(for: classifier, learningRate: 0.1) | ||
|
|
||
| print("Beginning training...") | ||
|
|
||
| struct Statistics { | ||
| var correctGuessCount: Int = 0 | ||
| var totalGuessCount: Int = 0 | ||
| var totalLoss: Float = 0 | ||
| } | ||
|
|
||
| // The training loop. | ||
| for epoch in 1...epochCount { | ||
| var trainStats = Statistics() | ||
| var testStats = Statistics() | ||
| Context.local.learningPhase = .training | ||
| for i in 0 ..< dataset.trainingSize / batchSize { | ||
| let x = dataset.trainImages.minibatch(at: i, batchSize: batchSize) | ||
| let y = dataset.trainLabels.minibatch(at: i, batchSize: batchSize) | ||
| // Compute the gradient with respect to the model. | ||
| let 𝛁model = classifier.gradient { classifier -> Tensor<Float> in | ||
| let ŷ = classifier(x) | ||
| let correctPredictions = ŷ.argmax(squeezingAxis: 1) .== y | ||
| trainStats.correctGuessCount += Int( | ||
| Tensor<Int32>(correctPredictions).sum().scalarized()) | ||
| trainStats.totalGuessCount += batchSize | ||
| let loss = softmaxCrossEntropy(logits: ŷ, labels: y) | ||
| trainStats.totalLoss += loss.scalarized() | ||
| return loss | ||
| } | ||
| // Update the model's differentiable variables along the gradient vector. | ||
| optimizer.update(&classifier.allDifferentiableVariables, along: 𝛁model) | ||
| } | ||
|
|
||
| Context.local.learningPhase = .inference | ||
| for i in 0 ..< dataset.testSize / batchSize { | ||
| let x = dataset.testImages.minibatch(at: i, batchSize: batchSize) | ||
| let y = dataset.testLabels.minibatch(at: i, batchSize: batchSize) | ||
| // Compute loss on test set | ||
| let ŷ = classifier(x) | ||
| let correctPredictions = ŷ.argmax(squeezingAxis: 1) .== y | ||
| testStats.correctGuessCount += Int(Tensor<Int32>(correctPredictions).sum().scalarized()) | ||
| testStats.totalGuessCount += batchSize | ||
| let loss = softmaxCrossEntropy(logits: ŷ, labels: y) | ||
| testStats.totalLoss += loss.scalarized() | ||
| } | ||
|
|
||
| let trainAccuracy = Float(trainStats.correctGuessCount) / Float(trainStats.totalGuessCount) | ||
| let testAccuracy = Float(testStats.correctGuessCount) / Float(testStats.totalGuessCount) | ||
| print(""" | ||
| [Epoch \(epoch)] \ | ||
| Training Loss: \(trainStats.totalLoss), \ | ||
| Training Accuracy: \(trainStats.correctGuessCount)/\(trainStats.totalGuessCount) \ | ||
| (\(trainAccuracy)), \ | ||
| Test Loss: \(testStats.totalLoss), \ | ||
| Test Accuracy: \(testStats.correctGuessCount)/\(testStats.totalGuessCount) \ | ||
| (\(testAccuracy)) | ||
| """) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -16,6 +16,8 @@ To begin, you'll need the [latest version of Swift for | |||||
| TensorFlow](https://github.com/tensorflow/swift/blob/master/Installation.md) | ||||||
| installed. Make sure you've added the correct version of `swift` to your path. | ||||||
|
|
||||||
| This example requires matplotlib and numpy to be installed, for use in image output. | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Nit: Use official product names, "Matplotlib" and "NumPy". |
||||||
|
|
||||||
| To train the model, run: | ||||||
|
|
||||||
| ```sh | ||||||
|
|
||||||
Binary file not shown.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure "train images" is the best term we should use in a Swift API design context. Albeit common in Python, "train images" which intends to be a noun phrase starts with a bare form verb that doesn't read fluently as recommended by Swift API Design Guidelines. How about using "training images" as the standard instead?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're right, that name bothered me. I've left "testImages" as-is, because I'm thinking about the name as it would be in a sentence like "these are training images" or "these are test images".
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
“Test images” sounds totally fine to me as a noun phrase. Thanks!