def get_model_alexnet(classes_num, ctx):
    pretrained_net = models.alexnet(pretrained=True)
    # print(pretrained_net)

    finetune_net = models.alexnet(classes=classes_num)          # 输出为classes_num个类
    finetune_net.features = pretrained_net.features             # 特征设置为inceptionv3的特征
    finetune_net.output.initialize(init.Xavier(), ctx=ctx)      # 对输出层做初始化
    finetune_net.collect_params().reset_ctx(ctx)                # 设置CPU或GPU
    finetune_net.hybridize()                                    # gluon特征,运算转成符号运算,提高运行速度
    return finetune_net
示例#2
0
  return train_transform, val_transform


def get_imagenet_iterator(root, batch_size, num_workers, data_shape=224, dtype='float32'):
  """Dataset loader with preprocessing."""
  train_dir = os.path.join(root, 'train')
  train_transform, val_transform = get_imagenet_transforms(data_shape, dtype)
  logging.info("Loading image folder %s, this may take a bit long...", train_dir)
  train_dataset = ImageFolderDataset(train_dir, transform=train_transform)
  train_data = DataLoader(train_dataset, batch_size, shuffle=True,
                          last_batch='discard', num_workers=num_workers)
  
  val_dir = os.path.join(root, 'val')
  if not os.path.isdir(os.path.expanduser(os.path.join(root, 'val', 'n01440764'))):
    user_warning = 'Make sure validation images are stored in one subdir per category, a helper script is available at https://git.io/vNQv1'
    raise ValueError(user_warning)
  
  logging.info("Loading image folder %s, this may take a bit long...", val_dir)
  val_dataset = ImageFolderDataset(val_dir, transform=val_transform)
  val_data = DataLoader(val_dataset, batch_size, last_batch='keep', num_workers=num_workers)
  return DataLoaderIter(train_data, dtype), DataLoaderIter(val_data, dtype)


resnet18 = vision.resnet18_v1(pretrained=True)
alexnet = vision.alexnet(pretrained=True)
inception = vision.inception_v3(pretrained=True)
#squeezenet = vision.squeezenet1_0()
#densenet = vision.densenet_161()

get_imagenet_iterator("c:\\data\\images", batch_size, num_workers, data_shape=224, dtype='float32'):
示例#3
0
import mxnet as mx
import time
import gluoncv

from mxnet import nd, autograd
from mxnet import gluon
from mxnet.gluon import nn

inputShape = (1, 3, 224, 224)

from mxnet.gluon.model_zoo import vision

alexnet = vision.alexnet()
inception = vision.inception_v3()

resnet18v1 = vision.resnet18_v1()
resnet18v2 = vision.resnet18_v2()
squeezenet = vision.squeezenet1_0()
densenet = vision.densenet121()
mobilenet = vision.mobilenet0_5()

############### 그래프 ###############
import gluoncv
gluoncv.utils.viz.plot_network(resnet18v1, shape=inputShape)
#####################################
示例#4
0
                                                  transform=transformer),
    batch_size=batch_size,
    shuffle=False,
    last_batch='discard')

for d, l in train_data:
    break

print(d.shape, l.shape)

### graph
from gluoncv.utils import viz
viz.plot_image(d[63][2])  # index 0 is image, 1 is label

from mxnet.gluon.model_zoo import vision
net = vision.alexnet(classes=10, pretrained=False, ctx=ctx)

net = gluon.nn.Sequential()
# 은닉층1 (채널=96, 커널=11, 패딩=1, 스트라이드=4, 활성화함수=relu)
# maxpooling(사이즈=3, 스트라이드2)
# 입력사이즈 (224, 224), 출력사이즈 (27, 27)
net.add(
    gluon.nn.Conv2D(96,
                    kernel_size=11,
                    padding=1,
                    strides=4,
                    activation='relu'))
net.add(gluon.nn.MaxPool2D(pool_size=3, strides=2))

# 은닉층2 (채널=256, 커널=5, 패딩=2, 스트라이드=1, 활성화함수=relu)
# maxpooling(사이즈=3, 스트라이드=2)
示例#5
0
def alexnetmxnetload():
    net = vision.alexnet(pretrained=True)
    net.hybridize()
    return net
示例#6
0
from mxnet.gluon.model_zoo import vision as models
from mxnet import image
from mxnet import nd


def transform(data):
    data = data.transpose((2, 0, 1)).expand_dims(axis=0)
    rgb_mean = nd.array([0.485, 0.456, 0.406]).reshape((1, 3, 1, 1))
    rgb_std = nd.array([0.229, 0.224, 0.225]).reshape((1, 3, 1, 1))
    return (data.astype('float32') / 255 - rgb_mean) / rgb_std


with open('./label.txt', 'r') as f:
    text_labels = [''.join(l.split("'")[1]) for l in f]

net = models.alexnet(pretrained=True)

image_list = os.listdir('./samples')
for image_name in image_list:
    image_path = os.path.join('./samples', image_name)
    print(image_path)
    x = image.imread(image_path)
    x = image.resize_short(x, 256)
    x, _ = image.center_crop(x, (224, 224))

    prob = net(transform(x)).softmax()
    idx = prob.topk(k=1)[0]
    for i in idx:
        i = int(i.asscalar())
        print('With prob = %.5f, it contains %s' %
              (prob[0, i].asscalar(), text_labels[i]))
from mxnet import gluon
from mxnet import ndarray as nd
from tqdm import tqdm
from mxnet import autograd
from mxnet.gluon.model_zoo import vision as models
import time
import h5py
import os

# In[2]:

ctx = mx.gpu()

# In[3]:

models.alexnet(pretrained=True, ctx=ctx)
net_functions = [
    models.alexnet, models.densenet121, models.densenet161, models.densenet169,
    models.densenet201, models.inception_v3, models.resnet18_v2,
    models.resnet34_v2, models.resnet50_v1, models.vgg11_bn, models.vgg13_bn,
    models.vgg16_bn, models.vgg19_bn
]

# In[4]:

net_dict = {}
for net_function in net_functions:
    pretrained_net = net_function(pretrained=True, ctx=ctx)
    finetune_net = net_function(classes=120, ctx=ctx)
    finetune_net.features = pretrained_net.features
    finetune_net.classifier.initialize(init.Xavier())