nswamy closed pull request #11250: [MXNET-531] MNIST Examples for Scala new API URL: https://github.com/apache/incubator-mxnet/pull/11250
This is a PR merged from a forked repository. As GitHub hides the original diff on merge, it is displayed below for the sake of provenance: As this is a foreign pull request (from a fork), the diff is supplied below (as it won't show otherwise due to GitHub magic): diff --git a/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/ModelTrain.scala b/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/ModelTrain.scala index ab86314a42a..1a77775b985 100644 --- a/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/ModelTrain.scala +++ b/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/ModelTrain.scala @@ -30,7 +30,7 @@ object ModelTrain { network: Symbol, dataLoader: (String, Int, KVStore) => (DataIter, DataIter), kvStore: String, numEpochs: Int, modelPrefix: String = null, loadEpoch: Int = -1, lr: Float = 0.1f, lrFactor: Float = 1f, lrFactorEpoch: Float = 1f, - clipGradient: Float = 0f, monitorSize: Int = -1): Unit = { + clipGradient: Float = 0f, monitorSize: Int = -1): Accuracy = { // kvstore var kv = KVStore.create(kvStore) @@ -96,15 +96,17 @@ object ModelTrain { if (monitorSize > 0) { model.setMonitor(new Monitor(monitorSize)) } + val acc = new Accuracy() model.fit(trainData = train, evalData = validation, - evalMetric = new Accuracy(), + evalMetric = acc, kvStore = kv, batchEndCallback = new Speedometer(batchSize, 50), epochEndCallback = checkpoint) if (kv != null) { kv.dispose() } + acc } // scalastyle:on parameterNum } diff --git a/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/README.md b/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/README.md new file mode 100644 index 00000000000..5141f441b1e --- /dev/null +++ b/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/README.md @@ -0,0 +1,17 @@ +# MNIST Example for Scala +This is the MNIST Training Example implemented for Scala type-safe api +## Setup +### Download the source File +```$xslt +https://s3.us-east-2.amazonaws.com/mxnet-scala/scala-example-ci/mnist/mnist.zip +``` +### Unzip the file +```$xslt +unzip mnist.zip +``` +### Arguement Configuration +Then you need to define the arguments that you would like to pass in the model: +```$xslt +--data-dir <location of your downloaded file> +``` +You can find more information [here](https://github.com/apache/incubator-mxnet/blob/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/TrainMnist.scala#L169-L207) \ No newline at end of file diff --git a/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/TrainMnist.scala b/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/TrainMnist.scala index e9171bd47c2..b0ecc7d29cc 100644 --- a/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/TrainMnist.scala +++ b/scala-package/examples/src/main/scala/org/apache/mxnetexamples/imclassification/TrainMnist.scala @@ -21,8 +21,8 @@ import org.apache.mxnet._ import org.kohsuke.args4j.{CmdLineParser, Option} import org.slf4j.LoggerFactory -import scala.collection.mutable import scala.collection.JavaConverters._ +import scala.collection.mutable object TrainMnist { private val logger = LoggerFactory.getLogger(classOf[TrainMnist]) @@ -31,6 +31,7 @@ object TrainMnist { def getMlp: Symbol = { val data = Symbol.Variable("data") + // val fc1 = Symbol.FullyConnected(name = "relu")()(Map("data" -> data, "act_type" -> "relu")) val fc1 = Symbol.api.FullyConnected(data = Some(data), num_hidden = 128, name = "fc1") val act1 = Symbol.api.Activation (data = Some(fc1), "relu", name = "relu") val fc2 = Symbol.api.FullyConnected(Some(act1), None, None, 64, name = "fc2") @@ -40,10 +41,6 @@ object TrainMnist { mlp } - // LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick - // Haffner. "Gradient-based learning applied to document recognition." - // Proceedings of the IEEE (1998) - def getLenet: Symbol = { val data = Symbol.Variable("data") // first conv @@ -95,6 +92,19 @@ object TrainMnist { (train, eval) } + def test(dataPath : String) : Float = { + val (dataShape, net) = (Shape(784), getMlp) + val devs = Array(Context.cpu(0)) + val envs: mutable.Map[String, String] = mutable.HashMap.empty[String, String] + val Acc = ModelTrain.fit(dataDir = dataPath, + batchSize = 128, numExamples = 60000, devs = devs, + network = net, dataLoader = getIterator(dataShape), + kvStore = "local", numEpochs = 10) + logger.info("Finish test fit ...") + val (_, num) = Acc.get + num(0) + } + def main(args: Array[String]): Unit = { val inst = new TrainMnist diff --git a/scala-package/examples/src/test/scala/org/apache/mxnetexamples/imclassification/MNISTExampleSuite.scala b/scala-package/examples/src/test/scala/org/apache/mxnetexamples/imclassification/MNISTExampleSuite.scala new file mode 100644 index 00000000000..0e3b7ec8f34 --- /dev/null +++ b/scala-package/examples/src/test/scala/org/apache/mxnetexamples/imclassification/MNISTExampleSuite.scala @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ + +package org.apache.mxnetexamples.imclassification + +import java.io.File +import java.net.URL + +import org.apache.commons.io.FileUtils +import org.apache.mxnet.Context +import org.scalatest.{BeforeAndAfterAll, FunSuite} +import org.slf4j.LoggerFactory + +import scala.sys.process.Process + +/** + * Integration test for imageClassifier example. + * This will run as a part of "make scalatest" + */ +class MNISTExampleSuite extends FunSuite with BeforeAndAfterAll { + private val logger = LoggerFactory.getLogger(classOf[MNISTExampleSuite]) + + test("Example CI: Test MNIST Training") { + // This test is CPU only + if (System.getenv().containsKey("SCALA_TEST_ON_GPU") && + System.getenv("SCALA_TEST_ON_GPU").toInt == 1) { + logger.info("CPU test only, skipped...") + } else { + logger.info("Downloading mnist model") + val baseUrl = "https://s3.us-east-2.amazonaws.com/mxnet-scala/scala-example-ci" + val tempDirPath = System.getProperty("java.io.tmpdir") + val modelDirPath = tempDirPath + File.separator + "mnist/" + logger.info("tempDirPath: %s".format(tempDirPath)) + val tmpFile = new File(tempDirPath + "/mnist/mnist.zip") + if (!tmpFile.exists()) { + FileUtils.copyURLToFile(new URL(baseUrl + "/mnist/mnist.zip"), + tmpFile) + } + // TODO: Need to confirm with Windows + Process("unzip " + tempDirPath + "/mnist/mnist.zip -d " + + tempDirPath + "/mnist/") ! + + var context = Context.cpu() + + val output = TrainMnist.test(modelDirPath) + Process("rm -rf " + modelDirPath) ! + + assert(output >= 0.95f) + } + + } +} diff --git a/scala-package/examples/src/test/scala/org/apache/mxnetexamples/infer/imageclassifier/ImageClassifierExampleSuite.scala b/scala-package/examples/src/test/scala/org/apache/mxnetexamples/infer/imageclassifier/ImageClassifierExampleSuite.scala index 63196ed8172..a08e1576ff3 100644 --- a/scala-package/examples/src/test/scala/org/apache/mxnetexamples/infer/imageclassifier/ImageClassifierExampleSuite.scala +++ b/scala-package/examples/src/test/scala/org/apache/mxnetexamples/infer/imageclassifier/ImageClassifierExampleSuite.scala @@ -65,14 +65,13 @@ class ImageClassifierExampleSuite extends FunSuite with BeforeAndAfterAll { val output = ImageClassifierExample.runInferenceOnSingleImage(modelDirPath + "resnet-18", inputImagePath, context) - assert(output(0).toList.head._1 === "n02110958 pug, pug-dog") - val outputList = ImageClassifierExample.runInferenceOnBatchOfImage(modelDirPath + "resnet-18", inputImageDir, context) - assert(outputList(0).toList.head._1 === "n02110958 pug, pug-dog") - Process("rm -rf " + modelDirPath + " " + inputImageDir) ! + assert(output(0).toList.head._1 === "n02110958 pug, pug-dog") + assert(outputList(0).toList.head._1 === "n02110958 pug, pug-dog") + } } diff --git a/scala-package/examples/src/test/scala/org/apache/mxnetexamples/infer/objectdetector/ObjectDetectorExampleSuite.scala b/scala-package/examples/src/test/scala/org/apache/mxnetexamples/infer/objectdetector/ObjectDetectorExampleSuite.scala index 9725eebb645..ed63116e7cf 100644 --- a/scala-package/examples/src/test/scala/org/apache/mxnetexamples/infer/objectdetector/ObjectDetectorExampleSuite.scala +++ b/scala-package/examples/src/test/scala/org/apache/mxnetexamples/infer/objectdetector/ObjectDetectorExampleSuite.scala @@ -68,14 +68,14 @@ class ObjectDetectorExampleSuite extends FunSuite with BeforeAndAfterAll { val output = SSDClassifierExample.runObjectDetectionSingle(modelDirPath + "resnet50_ssd_model", inputImagePath, context) - assert(output(0)(0)._1 === "car") - val outputList = SSDClassifierExample.runObjectDetectionBatch( modelDirPath + "resnet50_ssd_model", inputImageDir, context) + Process("rm -rf " + modelDirPath + " " + inputImageDir) ! + + assert(output(0)(0)._1 === "car") assert(output(0)(0)._1 === "car") - Process("rm -rf " + modelDirPath + " " + inputImageDir) ! } } ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org With regards, Apache Git Services