You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@submarine.apache.org by GitBox <gi...@apache.org> on 2020/03/03 04:35:33 UTC

[GitHub] [submarine] lowc1012 commented on a change in pull request #200: SUBMARINE-337. MXNET example in mini-submarine

lowc1012 commented on a change in pull request #200: SUBMARINE-337. MXNET example in mini-submarine
URL: https://github.com/apache/submarine/pull/200#discussion_r386794841
 
 

 ##########
 File path: dev-support/mini-submarine/submarine/image_classification.py
 ##########
 @@ -0,0 +1,467 @@
+# 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.
+
+from __future__ import division
+
+import argparse
+import time
+import os
+import logging
+import random
+import tarfile
+
+import mxnet as mx
+from mxnet import gluon
+from mxnet import profiler
+from mxnet.gluon import nn
+from mxnet.gluon.model_zoo import vision as models
+from mxnet.gluon.data.vision import ImageFolderDataset
+from mxnet.gluon.data import DataLoader
+from mxnet.contrib.io import DataLoaderIter
+from mxnet import autograd as ag
+from mxnet.test_utils import get_mnist_iterator, get_cifar10
+from mxnet.metric import Accuracy, TopKAccuracy, CompositeEvalMetric
+import numpy as np
+
+# logging
+logging.basicConfig(level=logging.INFO)
+fh = logging.FileHandler('image-classification.log')
+logger = logging.getLogger()
+logger.addHandler(fh)
+formatter = logging.Formatter('%(message)s')
+fh.setFormatter(formatter)
+fh.setLevel(logging.DEBUG)
+logging.debug('\n%s', '-' * 100)
+formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
+fh.setFormatter(formatter)
+
+# CLI
+parser = argparse.ArgumentParser(description='Train a model for image classification.')
+parser.add_argument('--dataset', type=str, default='cifar10',
+                    help='dataset to use. options are mnist, cifar10, caltech101, imagenet and dummy.')
+parser.add_argument('--data-dir', type=str, default='',
+                  help='training directory of imagenet images, contains train/val subdirs.')
+parser.add_argument('--num-worker', '-j', dest='num_workers', default=4, type=int,
+                    help='number of workers for dataloader')
+parser.add_argument('--batch-size', type=int, default=32,
+                    help='training batch size per device (CPU/GPU).')
+parser.add_argument('--gpus', type=str, default='',
+                    help='ordinates of gpus to use, can be "0,1,2" or empty for cpu only.')
+parser.add_argument('--epochs', type=int, default=120,
+                    help='number of training epochs.')
+parser.add_argument('--lr', type=float, default=0.1,
+                    help='learning rate. default is 0.1.')
+parser.add_argument('--momentum', type=float, default=0.9,
+                    help='momentum value for optimizer, default is 0.9.')
+parser.add_argument('--wd', type=float, default=0.0001,
+                    help='weight decay rate. default is 0.0001.')
+parser.add_argument('--seed', type=int, default=123,
+                    help='random seed to use. Default=123.')
+parser.add_argument('--mode', type=str,
+                    help='mode in which to train the model. options are symbolic, imperative, hybrid')
+parser.add_argument('--model', type=str, required=True,
+                    help='type of model to use. see vision_model for options.')
+parser.add_argument('--use_thumbnail', action='store_true',
+                    help='use thumbnail or not in resnet. default is false.')
+parser.add_argument('--batch-norm', action='store_true',
+                    help='enable batch normalization or not in vgg. default is false.')
+parser.add_argument('--use-pretrained', action='store_true',
+                    help='enable using pretrained model from gluon.')
+parser.add_argument('--prefix', default='', type=str,
+                    help='path to checkpoint prefix, default is current working dir')
+parser.add_argument('--start-epoch', default=0, type=int,
+                    help='starting epoch, 0 for fresh training, > 0 to resume')
+parser.add_argument('--resume', type=str, default='',
+                    help='path to saved weight where you want resume')
+parser.add_argument('--lr-factor', default=0.1, type=float,
+                    help='learning rate decay ratio')
+parser.add_argument('--lr-steps', default='30,60,90', type=str,
+                    help='list of learning rate decay epochs as in str')
+parser.add_argument('--dtype', default='float32', type=str,
+                    help='data type, float32 or float16 if applicable')
+parser.add_argument('--save-frequency', default=10, type=int,
+                    help='epoch frequence to save model, best model will always be saved')
+parser.add_argument('--kvstore', type=str, default='device',
+                    help='kvstore to use for trainer/module.')
+parser.add_argument('--log-interval', type=int, default=50,
+                    help='Number of batches to wait before logging.')
+parser.add_argument('--profile', action='store_true',
+                    help='Option to turn on memory profiling for front-end, '\
+                         'and prints out the memory usage by python function at the end.')
+parser.add_argument('--builtin-profiler', type=int, default=0, help='Enable built-in profiler (0=off, 1=on)')
+opt = parser.parse_args()
+
+# global variables
+logger.info('Starting new image-classification task:, %s',opt)
+mx.random.seed(opt.seed)
+model_name = opt.model
+dataset_classes = {'mnist': 10, 'cifar10': 10, 'caltech101':101, 'imagenet': 1000, 'dummy': 1000}
+batch_size, dataset, classes = opt.batch_size, opt.dataset, dataset_classes[opt.dataset]
+context = [mx.gpu(int(i)) for i in opt.gpus.split(',')] if opt.gpus.strip() else [mx.cpu()]
+num_gpus = len(context)
+batch_size *= max(1, num_gpus)
+lr_steps = [int(x) for x in opt.lr_steps.split(',') if x.strip()]
+metric = CompositeEvalMetric([Accuracy(), TopKAccuracy(5)])
+kv = mx.kv.create(opt.kvstore)
+
+
+def get_cifar10_iterator(batch_size, data_shape, resize=-1, num_parts=1, part_index=0):
+    get_cifar10()
+
+    train = mx.io.ImageRecordIter(
+        path_imgrec = "data/cifar/train.rec",
+        # mean_img    = "data/cifar/mean.bin",
+        resize      = resize,
+        data_shape  = data_shape,
+        batch_size  = batch_size,
+        rand_crop   = True,
+        rand_mirror = True,
+        num_parts=num_parts,
+        part_index=part_index)
+
+    val = mx.io.ImageRecordIter(
+        path_imgrec = "data/cifar/test.rec",
+        # mean_img    = "data/cifar/mean.bin",
 
 Review comment:
   done

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@submarine.apache.org
For additional commands, e-mail: dev-help@submarine.apache.org