def test_model1(self): model1 = Sequential(self.s, model_table='Simple_CNN1') model1.add(InputLayer(3, 224, 224)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Dense(16)) model1.add(OutputLayer(act='softmax', n=2)) if self.data_dir is None: unittest.TestCase.skipTest(self, "DLPY_DATA_DIR is not set in the environment variables") caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load') self.s.table.loadtable(caslib=caslib, casout={'name': 'eee', 'replace': True}, path=path) r = model1.fit(data='eee', inputs='_image_', target='_label_', lr=0.001) if r.severity > 0: for msg in r.messages: print(msg) self.assertTrue(r.severity <= 1) if (caslib is not None) and tmp_caslib: self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)
def test_model23(self): try: import onnx except: unittest.TestCase.skipTest(self, "onnx not found in the libraries") model1 = Sequential(self.s, model_table='Simple_CNN1') model1.add(InputLayer(3, 224, 224)) model1.add(Conv2d(8, 7, act='identity', include_bias=False)) model1.add(BN(act='relu')) model1.add(Pooling(2)) model1.add(Conv2d(8, 7, act='identity', include_bias=False)) model1.add(BN(act='relu')) model1.add(Pooling(2)) model1.add(Dense(2)) model1.add(OutputLayer(act='softmax', n=2)) if self.data_dir is None: unittest.TestCase.skipTest(self, "DLPY_DATA_DIR is not set in the environment variables") caslib, path = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load') self.s.table.loadtable(caslib=caslib, casout={'name': 'eee', 'replace': True}, path=path) r = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=1) self.assertTrue(r.severity == 0) model1.deploy(self.data_dir, output_format='onnx')
def test_CyclicLR(self): model1 = Sequential(self.s, model_table = 'Simple_CNN1') model1.add(InputLayer(3, 224, 224)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Dense(16)) model1.add(OutputLayer(act = 'softmax', n = 2)) if self.data_dir is None: unittest.TestCase.skipTest(self, "DLPY_DATA_DIR is not set in the environment variables") caslib, path, tmp_caslib = caslibify(self.s, path = self.data_dir + 'images.sashdat', task = 'load') self.s.table.loadtable(caslib = caslib, casout = {'name': 'eee', 'replace': True}, path = path) lrs = CyclicLR(self.s, 'eee', 4, 1.0, 0.0000001, 0.01) solver = VanillaSolver(lr_scheduler=lrs) self.assertTrue(self.sample_syntax['CyclicLR'] == solver) optimizer = Optimizer(algorithm = solver, log_level = 3, max_epochs = 4, mini_batch_size = 2) r = model1.fit(data = 'eee', inputs = '_image_', target = '_label_', optimizer = optimizer, n_threads=2) if r.severity > 0: for msg in r.messages: print(msg) self.assertTrue(r.severity <= 1)
def test_model18(self): model1 = Sequential(self.s, model_table='Simple_CNN1') model1.add(InputLayer(3, 224, 224)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Dense(16)) model1.add(OutputLayer(act='softmax', n=2)) if self.data_dir is None: unittest.TestCase.skipTest( self, "DLPY_DATA_DIR is not set in the environment variables") caslib, path = caslibify(self.s, path=self.data_dir + 'images.sashdat', task='load') self.s.table.loadtable(caslib=caslib, casout={ 'name': 'eee', 'replace': True }, path=path) r = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=1) self.assertTrue(r.severity == 0) model1.save_weights_csv(self.data_dir)
def test_model22(self): model1 = Sequential(self.s, model_table='Simple_CNN1') model1.add(InputLayer(3, 224, 224)) model1.add(Conv2d(8, 7)) pool1 = Pooling(2) model1.add(pool1) conv1 = Conv2d(1, 1, act='identity', src_layers=[pool1]) model1.add(conv1) model1.add(Res(act='relu', src_layers=[conv1, pool1])) model1.add(Pooling(2)) model1.add(Dense(2)) model1.add(OutputLayer(act='softmax', n=2)) if self.data_dir is None: unittest.TestCase.skipTest(self, "DLPY_DATA_DIR is not set in the environment variables") caslib, path = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load') self.s.table.loadtable(caslib=caslib, casout={'name': 'eee', 'replace': True}, path=path) r = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=1) self.assertTrue(r.severity == 0) model1.deploy(self.data_dir, output_format='onnx')
def test_model12(self): model1 = Sequential(self.s, model_table='Simple_CNN1') model1.add(InputLayer(3, 224, 224)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Dense(16)) model1.add(OutputLayer(act='softmax', n=2)) if self.data_dir is None: unittest.TestCase.skipTest(self, "DLPY_DATA_DIR is not set in the environment variables") caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load') self.s.table.loadtable(caslib=caslib, casout={'name': 'eee', 'replace': True}, path=path) r = model1.fit(data='eee', inputs='_image_', target='_label_', save_best_weights=True) self.assertTrue(r.severity == 0) r1 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=3) self.assertTrue(r1.severity == 0) r2 = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=2, save_best_weights=True) self.assertTrue(r2.severity == 0) r3 = model1.predict(data='eee', use_best_weights=True) self.assertTrue(r3.severity == 0) if (caslib is not None) and tmp_caslib: self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)
def test_model15(self): # test RECTIFIER activation for concat layer try: import onnx except: unittest.TestCase.skipTest(self, "onnx not found in the libraries") model1 = Sequential(self.s, model_table='Simple_CNN1') model1.add(InputLayer(3, 224, 224)) model1.add(Conv2d(8, 7)) pool1 = Pooling(2) model1.add(pool1) conv1 = Conv2d(1, 7, src_layers=[pool1]) conv2 = Conv2d(1, 7, src_layers=[pool1]) model1.add(conv1) model1.add(conv2) model1.add(Concat(act='RECTIFIER', src_layers=[conv1, conv2])) model1.add(Pooling(2)) model1.add(Dense(2)) model1.add(OutputLayer(act='softmax', n=2)) if self.data_dir is None: unittest.TestCase.skipTest( self, "DLPY_DATA_DIR is not set in the environment variables") caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir + 'images.sashdat', task='load') self.s.table.loadtable(caslib=caslib, casout={ 'name': 'eee', 'replace': True }, path=path) r = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=1) self.assertTrue(r.severity == 0) import tempfile tmp_dir_to_dump = tempfile.gettempdir() model1.deploy(tmp_dir_to_dump, output_format='onnx') import os os.remove(os.path.join(tmp_dir_to_dump, "Simple_CNN1.onnx")) if (caslib is not None) and tmp_caslib: self.s.retrieve('table.dropcaslib', message_level='error', caslib=caslib)
def test_model13(self): # test dropout try: import onnx except: unittest.TestCase.skipTest(self, "onnx not found in the libraries") model1 = Sequential(self.s, model_table='Simple_CNN1') model1.add(InputLayer(3, 224, 224)) model1.add( Conv2d(8, 7, act='IDENTITY', dropout=0.5, include_bias=False)) model1.add(BN(act='relu')) model1.add(Pooling(2, pool='MEAN', dropout=0.5)) model1.add( Conv2d(8, 7, act='IDENTITY', dropout=0.5, include_bias=False)) model1.add(BN(act='relu')) model1.add(Pooling(2, pool='MEAN', dropout=0.5)) model1.add(Conv2d(8, 7, act='identity', include_bias=False)) model1.add(BN(act='relu')) model1.add(Dense(16, act='IDENTITY', dropout=0.1)) model1.add(OutputLayer(act='softmax', n=2)) if self.data_dir is None: unittest.TestCase.skipTest( self, "DLPY_DATA_DIR is not set in the environment variables") caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir + 'images.sashdat', task='load') self.s.table.loadtable(caslib=caslib, casout={ 'name': 'eee', 'replace': True }, path=path) r = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=2) self.assertTrue(r.severity == 0) import tempfile tmp_dir_to_dump = tempfile.gettempdir() model1.deploy(tmp_dir_to_dump, output_format='onnx') import os os.remove(os.path.join(tmp_dir_to_dump, "Simple_CNN1.onnx")) if (caslib is not None) and tmp_caslib: self.s.retrieve('table.dropcaslib', message_level='error', caslib=caslib)
def test_stride(self): model = Sequential(self.s, model_table = 'Simple_CNN_3classes_cropped') model.add(InputLayer(1, width = 36, height = 144, #offsets = myimage.channel_means, name = 'input1', random_mutation = 'random', random_flip = 'HV')) model.add(Conv2d(64, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(64, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(64, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Pooling(height = 2, width = 2, stride_vertical = 2, stride_horizontal = 1, pool = 'max')) # 72, 36 model.add(Conv2d(128, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(128, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(128, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Pooling(height = 2, width = 2, stride_vertical = 2, stride_horizontal = 1, pool = 'max')) # 36*36 model.add(Conv2d(256, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(256, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(256, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Pooling(2, pool = 'max')) # 18 * 18 model.add(Conv2d(512, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(512, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(512, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Pooling(2, pool = 'max')) # 9 * 9 model.add(Conv2d(1024, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(1024, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Conv2d(1024, 3, 3, include_bias = False, act = 'identity')) model.add(BN(act = 'relu')) model.add(Pooling(9)) model.add(Dense(256, dropout = 0.5)) model.add(OutputLayer(act = 'softmax', n = 3, name = 'output1')) self.assertEqual(model.summary['Output Size'].values[-3], (1, 1, 1024)) model.print_summary() # 2d print summary numerical check self.assertEqual(model.summary.iloc[1, -1], 2985984)
def test_plot_ticks(self): model1 = Sequential(self.s, model_table='Simple_CNN1') model1.add(InputLayer(3, 224, 224)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(Dense(16)) model1.add(OutputLayer(act='softmax', n=2)) if self.data_dir is None: unittest.TestCase.skipTest(self, "DLPY_DATA_DIR is not set in the environment variables") caslib, path, tmp_caslib = caslibify(self.s, path=self.data_dir+'images.sashdat', task='load') self.s.table.loadtable(caslib=caslib, casout={'name': 'eee', 'replace': True}, path=path) r = model1.fit(data='eee', inputs='_image_', target='_label_', lr=0.001, max_epochs=5) # Test default tick_frequency value of 1 ax = model1.plot_training_history() self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs) # Test even tick_frequency = 2 ax = model1.plot_training_history(tick_frequency=tick_frequency) self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs // tick_frequency + 1) # Test odd tick_frequency = 3 ax = model1.plot_training_history(tick_frequency=tick_frequency) self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs // tick_frequency + 1) # Test max tick_frequency = model1.n_epochs ax = model1.plot_training_history(tick_frequency=tick_frequency) self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs // tick_frequency + 1) # Test 0 tick_frequency = 0 ax = model1.plot_training_history(tick_frequency=tick_frequency) self.assertEqual(len(ax.xaxis.majorTicks), model1.n_epochs) if (caslib is not None) and tmp_caslib: self.s.retrieve('table.dropcaslib', message_level = 'error', caslib = caslib)
def test_pool_layer2(self): dict1 = Pooling(name='pool2', width=3, height=2, src_layers=[Conv2d(n_filters=3, name='conv')]).to_model_params() self.assertTrue(self.sample_syntax['pool2'] == dict1)
def test_detection_layer1(self): dict1 = Detection(name='detection', predictions_per_grid=7, iou_threshold=0.2, detection_threshold=0.2, src_layers=[Pooling(name='pool')]).to_model_params() self.assertTrue(self.sample_syntax['detection1'] == dict1)
def test_build_gan_model_4(self): if self.server_dir is None: unittest.TestCase.skipTest(self, "DLPY_DATA_DIR_SERVER is not set in the environment variables") discriminator = Sequential(self.s) discriminator.add(InputLayer(1, 28, 28)) discriminator.add(Conv2d(3, 3)) discriminator.add(Pooling(2)) discriminator.add(Conv2d(3, 3)) discriminator.add(Pooling(2)) discriminator.add(Dense(16)) discriminator.add(OutputLayer(n=1)) generator = Sequential(self.s) generator.add(InputLayer(1, 100, 1)) generator.add(Dense(256, act='relu')) generator.add(Dense(512, act='relu')) generator.add(Dense(1024, act='relu')) generator.add(Dense(28 * 28, act='tanh')) generator.add(OutputLayer(act='softmax', n=2)) encoder = Sequential(self.s) encoder.add(InputLayer(100, 1, 1)) encoder.add(Dense(256, act='relu')) encoder.add(Dense(512, act='relu')) encoder.add(Dense(1024, act='relu')) encoder.add(Dense(100, act='tanh')) encoder.add(OutputLayer(act='softmax', n=2)) gan_model = GANModel(generator, discriminator, encoder) res = gan_model.models['generator'].print_summary() print(res) res = gan_model.models['discriminator'].print_summary() print(res) from dlpy.model import Optimizer, MomentumSolver, AdamSolver solver = AdamSolver(lr_scheduler=StepLR(learning_rate=0.0001, step_size=4), clip_grad_max=100, clip_grad_min=-100) optimizer = Optimizer(algorithm=solver, mini_batch_size=8, log_level=2, max_epochs=4, reg_l2=0.0001) res = gan_model.fit(optimizer, optimizer, self.server_dir + 'mnist_validate', n_samples_generator=32, n_samples_discriminator=32, max_iter=2, n_threads=1, damping_factor=0.5) print(res)
def test_dense_layer2(self): dict1 = Dense(name='dense', n=10000, init='xavier', dropout=0.2, include_bias=False, src_layers=[Pooling(name='pool')]).to_model_params() self.assertTrue(self.sample_syntax['fc2'] == dict1)
def test_model_crnn_bug(self): model = Sequential(self.s, model_table='crnn') model.add(InputLayer(3,256,16)) model.add(Reshape(height=16,width=256,depth=3)) model.add(Conv2d(64,3,3,stride=1,padding=1)) # size = 16x256x64 model.add(Pooling(2,2,2)) # size = 8x128x64 model.add(Conv2d(128,3,3,stride=1,padding=1)) # size = 8x128x128 model.add(Pooling(2,2,2)) # size = 4x64x128 model.add(Conv2d(256,3,3,stride=1,padding=1,act='IDENTITY')) # size = 4x64x256 model.add(BN(act='RELU')) # size = 4x64x256 model.add(Conv2d(256,3,3,stride=1,padding=1)) # size = 4x64x256 model.add(Pooling(1,2,stride_horizontal=1, stride_vertical=2)) #, padding=1)) # size = 2x64x256 #model.add(Pooling(1,2,stride=2,stride_horizontal=1, stride_vertical=2,)) # size = 2x64x256 model.add(Conv2d(512,3,3,stride=1,padding=1, act='IDENTITY')) # size = 2x64x512 model.add(BN(act='RELU')) model.add(Conv2d(512,3,3,stride=1,padding=1)) # size = 2x64x512 model.add(Pooling(1,2,stride_horizontal=1, stride_vertical=2)) #, padding=1)) # size = 1x64x512 #model.add(Pooling(1,2,stride=2,stride_horizontal=1, stride_vertical=2,)) # size = 1x64x512 model.add(Conv2d(512,3,3,stride=1,padding=1, act='IDENTITY')) # size = 1x64x512 model.add(BN(act='RELU')) model.add(Reshape(order='DWH',width=64, height=512, depth=1)) model.add(Recurrent(512,output_type='SAMELENGTH')) model.add(OutputLayer(error='CTC')) model.print_summary()
def test_model13a(self): model = Sequential(self.s, model_table='simple_cnn') model.add(InputLayer(3, 224, 224)) model.add(Conv2d(2, 3)) model.add(Pooling(2)) model.add(Dense(4)) model.add(OutputLayer(n=2)) if self.data_dir is None: unittest.TestCase.skipTest(self, "DLPY_DATA_DIR is not set in the environment variables") model.save_to_table(self.data_dir)
def test_imagescaler2(self): # test export model with imagescaler try: import onnx except: unittest.TestCase.skipTest(self, 'onnx not found') if self.data_dir_local is None: unittest.TestCase.skipTest( self, 'DLPY_DATA_DIR_LOCAL is not set in ' 'the environment variables') model1 = Sequential(self.s, model_table='imagescaler2') model1.add( InputLayer(n_channels=3, width=224, height=224, scale=1 / 255., offsets=[0.1, 0.2, 0.3])) model1.add(Conv2d(8, 7)) model1.add(Pooling(2)) model1.add(OutputLayer(act='softmax', n=2)) caslib, path = caslibify(self.s, path=self.data_dir + 'images.sashdat', task='load') self.s.table.loadtable(caslib=caslib, casout={ 'name': 'eee', 'replace': True }, path=path) r = model1.fit(data='eee', inputs='_image_', target='_label_', max_epochs=1) self.assertTrue(r.severity == 0) from dlpy.model_conversion.write_onnx_model import sas_to_onnx onnx_model = sas_to_onnx(model1.layers, self.s.CASTable('imagescaler2'), self.s.CASTable('imagescaler2_weights')) self.assertAlmostEqual(onnx_model.graph.node[0].attribute[0].floats[0], 0.1) self.assertAlmostEqual(onnx_model.graph.node[0].attribute[0].floats[1], 0.2) self.assertAlmostEqual(onnx_model.graph.node[0].attribute[0].floats[2], 0.3) self.assertAlmostEqual(onnx_model.graph.node[0].attribute[1].f, 1 / 255.)
def downsampling_bottleneck(x, in_depth, out_depth, projection_ratio=4): ''' Defines the down-sampling bottleneck of ENet Parameters ---------- x : class:`Layer' Previous layer to this block in_depth : int Depth of the layer fed into this block out_depth : int Depth of the output layer of this block projection_ratio : int, optional Used to calculate the reduced_depth for intermediate convolution layers Default: 4 Returns ------- :class:`Res` ''' reduced_depth = int(in_depth // projection_ratio) conv1 = Conv2d(reduced_depth, 3, stride=2, padding=1, act='identity', include_bias=False)(x) bn1 = BN(act='relu')(conv1) conv2 = Conv2d(reduced_depth, 3, stride=1, act='identity', include_bias=False)(bn1) bn2 = BN(act='relu')(conv2) conv3 = Conv2d(out_depth, 1, stride=1, act='identity', include_bias=False)(bn2) bn3 = BN(act='relu')(conv3) pool1 = Pooling(2, stride=2)(x) conv4 = Conv2d(out_depth, 1, stride=1, act='identity', include_bias=False)(pool1) bn4 = BN(act='relu')(conv4) res = Res()([bn3, bn4]) return res
def setUp(self): swat.reset_option() swat.options.cas.print_messages = False swat.options.interactive_mode = False self.s = swat.CAS(HOST, PORT, USER, PASSWD, protocol=PROTOCOL) if type(self).server_type is None: # Set once per class and have every test use it. No need to change between tests. type(self).server_type = tm.get_cas_host_type(self.s) self.srcLib = tm.get_casout_lib(self.server_type) # Define the model model = Sequential(self.s, model_table='test_model') model.add(InputLayer(3, 224, 224, offsets=(0, 0, 0))) model.add(Conv2d(8, 7)) model.add(Pooling(2)) model.add(Conv2d(8, 7)) model.add(Pooling(2)) model.add(Dense(16)) model.add(OutputLayer(act='softmax', n=2)) self.model = model
def initial_block(inp): ''' Defines the initial block of ENet Parameters ---------- inp : class:`InputLayer` Input layer Returns ------- :class:`Concat` ''' x = Conv2d(13, 3, stride=2, padding=1, act='identity', include_bias=False)(inp) x_bn = BN(act='relu')(x) y = Pooling(2)(inp) merge = Concat()([x_bn, y]) return merge
def onnx_extract_globalpool(graph, node, layers): ''' Construct global pool layer from ONNX op Parameters ---------- graph : ONNX GraphProto Specifies a GraphProto object. node : ONNX NodeProto Specifies a NodeProto object. layers : list of Layers Specifies the existing layers of a model. Returns ------- :class:`Pooling` ''' previous = onnx_find_previous_compute_layer(graph, node) if not previous: src_names = [find_input_layer_name(graph)] else: src_names = [p.name for p in previous] src = [get_dlpy_layer(layers, i) for i in src_names] # check the shape of the input to pool op _, C, height, width = onnx_get_shape(graph, node.input[0]) return Pooling(width=width, height=height, stride=1, name=node.name, padding=0, pool='AVERAGE', src_layers=src)
def test_scale_layer1(self): dict1 = Scale(name='scale', src_layers=[Pooling(name='pool')]).to_model_params() self.assertTrue(self.sample_syntax['scale1'] == dict1)
def test_output_layer1(self): dict1 = OutputLayer(name='output', n=100, src_layers=[Pooling(name='pool') ]).to_model_params() self.assertTrue(self.sample_syntax['output1'] == dict1)
def test_pool_layer4(self): if not __dev__: with self.assertRaises(DLPyError): Pooling(not_a_parameter=1)
def test_dense_layer1(self): dict1 = Dense(name='dense', n=10, src_layers=[Pooling(name='pool')]).to_model_params() self.assertTrue(self.sample_syntax['fc1'] == dict1)
def onnx_extract_pool(graph, node, layers, pool='MAX'): ''' Construct pool layer from ONNX op Parameters ---------- graph : ONNX GraphProto Specifies a GraphProto object. node : ONNX NodeProto Specifies a NodeProto object. layers : list of Layers Specifies the existing layers of a model. pool : str, optional Specifies the type of pooling. Default: MAX Returns ------- :class:`Pooling` ''' previous = onnx_find_previous_compute_layer(graph, node) if not previous: src_names = [find_input_layer_name(graph)] else: src_names = [p.name for p in previous] src = [get_dlpy_layer(layers, i) for i in src_names] height = None padding = None padding_height = None padding_width = None stride = None stride_horizontal = None stride_vertical = None width = None # if padding is not present, default to 0 is_padding = False for attr in node.attribute: if attr.name == 'kernel_shape': height, width = attr.ints elif attr.name == 'strides': stride_vertical, stride_horizontal = attr.ints # only specify one of stride and stride_horizontal if stride_horizontal == stride_vertical: stride = stride_horizontal stride_horizontal = None stride_vertical = None elif attr.name == 'auto_pad': is_padding = True attr_s = attr.s.decode('utf8') if attr_s == 'SAME_UPPER' or attr_s == 'SAME_LOWER': continue elif attr_s == 'NOTSET': continue else: # 'VALID' padding = 0 elif attr.name == 'pads': is_padding = True padding_height, padding_width, p_h2, p_w2 = attr.ints if padding_height != p_h2 or padding_width != p_w2: print('WARNING: Unequal padding not supported for ' + node.name + ' Setting auto padding instead.') if padding_height == 0 and p_h2 != 0: padding_height = None else: padding_height = max(padding_height, p_h2) if padding_width == 0 and p_w2 != 0: padding_width = None else: padding_width = max(padding_width, p_w2) if not is_padding: padding = 0 return Pooling(width=width, height=height, stride=stride, name=node.name, stride_horizontal=stride_horizontal, stride_vertical=stride_vertical, padding=padding, padding_width=padding_width, padding_height=padding_height, pool=pool, src_layers=src)
def VGG19(conn, model_table='VGG19', n_classes=1000, n_channels=3, width=224, height=224, scale=1, random_flip=None, random_crop=None, offsets=(103.939, 116.779, 123.68), pre_trained_weights=False, pre_trained_weights_file=None, include_top=False, random_mutation=None): ''' Generates a deep learning model with the VGG19 architecture. Parameters ---------- conn : CAS Specifies the CAS connection object. model_table : string, optional Specifies the name of CAS table to store the model. n_classes : int, optional Specifies the number of classes. If None is assigned, the model will automatically detect the number of classes based on the training set. Default: 1000 n_channels : int, optional Specifies the number of the channels (i.e., depth) of the input layer. Default: 3 width : int, optional Specifies the width of the input layer. Default: 224 height : int, optional Specifies the height of the input layer. Default: 224 scale : double, optional Specifies a scaling factor to be applied to each pixel intensity values. Default: 1 random_flip : string, optional Specifies how to flip the data in the input layer when image data is used. Approximately half of the input data is subject to flipping. Valid Values: 'h', 'hv', 'v', 'none' random_crop : string, optional Specifies how to crop the data in the input layer when image data is used. Images are cropped to the values that are specified in the width and height parameters. Only the images with one or both dimensions that are larger than those sizes are cropped. Valid Values: 'none', 'unique', 'randomresized', 'resizethencrop' offsets : double or iter-of-doubles, optional Specifies an offset for each channel in the input data. The final input data is set after applying scaling and subtracting the specified offsets. Default: (103.939, 116.779, 123.68) pre_trained_weights : bool, optional Specifies whether to use the pre-trained weights trained on the ImageNet data set. Default: False pre_trained_weights_file : string, optional Specifies the file name for the pre-trained weights. Must be a fully qualified file name of SAS-compatible file (e.g., *.caffemodel.h5) Note: Required when pre_trained_weights=True. include_top : bool, optional Specifies whether to include pre-trained weights of the top layers (i.e., the FC layers). Default: False random_mutation : string, optional Specifies how to apply data augmentations/mutations to the data in the input layer. Valid Values: 'none', 'random' Returns ------- :class:`Sequential` If `pre_trained_weights` is False :class:`Model` If `pre_trained_weights` is True References ---------- https://arxiv.org/pdf/1409.1556.pdf ''' conn.retrieve('loadactionset', _messagelevel='error', actionset='deeplearn') # get all the parms passed in parameters = locals() if not pre_trained_weights: model = Sequential(conn=conn, model_table=model_table) # get the input parameters input_parameters = get_layer_options(input_layer_options, parameters) model.add(InputLayer(**input_parameters)) model.add(Conv2d(n_filters=64, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=64, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Conv2d(n_filters=128, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=128, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Conv2d(n_filters=256, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=256, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=256, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=256, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Dense(n=4096, dropout=0.5)) model.add(Dense(n=4096, dropout=0.5)) model.add(OutputLayer(n=n_classes)) return model else: if pre_trained_weights_file is None: raise DLPyError( '\nThe pre-trained weights file is not specified.\n' 'Please follow the steps below to attach the pre-trained weights:\n' '1. Go to the website https://support.sas.com/documentation/prod-p/vdmml/zip/ ' 'and download the associated weight file.\n' '2. Upload the *.h5 file to ' 'a server side directory which the CAS session has access to.\n' '3. Specify the pre_trained_weights_file using the fully qualified server side path.' ) model_cas = model_vgg19.VGG19_Model(s=conn, model_table=model_table, n_channels=n_channels, width=width, height=height, random_crop=random_crop, offsets=offsets, random_flip=random_flip, random_mutation=random_mutation) if include_top: if n_classes != 1000: warnings.warn( 'If include_top = True, n_classes will be set to 1000.', RuntimeWarning) model = Model.from_table(model_cas) model.load_weights(path=pre_trained_weights_file, labels=True) return model else: model = Model.from_table(model_cas, display_note=False) model.load_weights(path=pre_trained_weights_file) weight_table_options = model.model_weights.to_table_params() weight_table_options.update(dict(where='_LayerID_<22')) model._retrieve_('table.partition', table=weight_table_options, casout=dict( replace=True, **model.model_weights.to_table_params())) model._retrieve_('deeplearn.removelayer', model=model_table, name='fc8') model._retrieve_('deeplearn.addlayer', model=model_table, name='fc8', layer=dict(type='output', n=n_classes, act='softmax'), srcLayers=['fc7']) model = Model.from_table(conn.CASTable(model_table)) return model
def VGG11(conn, model_table='VGG11', n_classes=1000, n_channels=3, width=224, height=224, scale=1, random_flip=None, random_crop=None, offsets=(103.939, 116.779, 123.68), random_mutation=None): ''' Generates a deep learning model with the VGG11 architecture. Parameters ---------- conn : CAS Specifies the CAS connection object. model_table : string, optional Specifies the name of CAS table to store the model. n_classes : int, optional Specifies the number of classes. If None is assigned, the model will automatically detect the number of classes based on the training set. Default: 1000 n_channels : int, optional Specifies the number of the channels (i.e., depth) of the input layer. Default: 3 width : int, optional Specifies the width of the input layer. Default: 224 height : int, optional Specifies the height of the input layer. Default: 224 scale : double, optional Specifies a scaling factor to be applied to each pixel intensity values. Default: 1 random_flip : string, optional Specifies how to flip the data in the input layer when image data is used. Approximately half of the input data is subject to flipping. Valid Values: 'h', 'hv', 'v', 'none' random_crop : string, optional Specifies how to crop the data in the input layer when image data is used. Images are cropped to the values that are specified in the width and height parameters. Only the images with one or both dimensions that are larger than those sizes are cropped. Valid Values: 'none', 'unique', 'randomresized', 'resizethencrop' offsets : double or iter-of-doubles, optional Specifies an offset for each channel in the input data. The final input data is set after applying scaling and subtracting the specified offsets. Default: (103.939, 116.779, 123.68) random_mutation : string, optional Specifies how to apply data augmentations/mutations to the data in the input layer. Valid Values: 'none', 'random' Returns ------- :class:`Sequential` References ---------- https://arxiv.org/pdf/1409.1556.pdf ''' conn.retrieve('loadactionset', _messagelevel='error', actionset='deeplearn') # get all the parms passed in parameters = locals() model = Sequential(conn=conn, model_table=model_table) # get the input parameters input_parameters = get_layer_options(input_layer_options, parameters) model.add(InputLayer(**input_parameters)) model.add(Conv2d(n_filters=64, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Conv2d(n_filters=128, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Conv2d(n_filters=256, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=256, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Conv2d(n_filters=512, width=3, height=3, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) model.add(Dense(n=4096, dropout=0.5)) model.add(Dense(n=4096, dropout=0.5)) model.add(OutputLayer(n=n_classes)) return model
def YoloV1(conn, model_table='YoloV1', n_channels=3, width=448, height=448, scale=1.0 / 255, random_mutation=None, act='leaky', dropout=0, act_detection='AUTO', softmax_for_class_prob=True, coord_type='YOLO', max_label_per_image=30, max_boxes=30, n_classes=20, predictions_per_grid=2, do_sqrt=True, grid_number=7, coord_scale=None, object_scale=None, prediction_not_a_object_scale=None, class_scale=None, detection_threshold=None, iou_threshold=None, random_boxes=False, random_flip=None, random_crop=None): ''' Generates a deep learning model with the Yolo V1 architecture. Parameters ---------- conn : CAS Specifies the connection of the CAS connection. model_table : string, optional Specifies the name of CAS table to store the model. n_channels : int, optional Specifies the number of the channels (i.e., depth) of the input layer. Default: 3 width : int, optional Specifies the width of the input layer. Default: 448 height : int, optional Specifies the height of the input layer. Default: 448 scale : double, optional Specifies a scaling factor to be applied to each pixel intensity values. Default: 1.0 / 255 random_mutation : string, optional Specifies how to apply data augmentations/mutations to the data in the input layer. Valid Values: 'none', 'random' act: String, optional Specifies the activation function to be used in the convolutional layer layers and the final convolution layer. Default: 'leaky' dropout: double, optional Specifies the drop out rate. Default: 0 act_detection : string, optional Specifies the activation function for the detection layer. Valid Values: AUTO, IDENTITY, LOGISTIC, SIGMOID, TANH, RECTIFIER, RELU, SOFPLUS, ELU, LEAKY, FCMP Default: AUTO softmax_for_class_prob : bool, optional Specifies whether to perform Softmax on class probability per predicted object. Default: True coord_type : string, optional Specifies the format of how to represent bounding boxes. For example, a bounding box can be represented with the x and y locations of the top-left point as well as width and height of the rectangle. This format is the 'rect' format. We also support coco and yolo formats. Valid Values: 'rect', 'yolo', 'coco' Default: 'yolo' max_label_per_image : int, optional Specifies the maximum number of labels per image in the training. Default: 30 max_boxes : int, optional Specifies the maximum number of overall predictions allowed in the detection layer. Default: 30 n_classes : int, optional Specifies the number of classes. If None is assigned, the model will automatically detect the number of classes based on the training set. Default: 20 predictions_per_grid : int, optional Specifies the amount of predictions will be done per grid. Default: 2 do_sqrt : bool, optional Specifies whether to apply the SQRT function to width and height of the object for the cost function. Default: True grid_number : int, optional Specifies the amount of cells to be analyzed for an image. For example, if the value is 5, then the image will be divided into a 5 x 5 grid. Default: 7 coord_scale : float, optional Specifies the weight for the cost function in the detection layer, when objects exist in the grid. object_scale : float, optional Specifies the weight for object detected for the cost function in the detection layer. prediction_not_a_object_scale : float, optional Specifies the weight for the cost function in the detection layer, when objects do not exist in the grid. class_scale : float, optional Specifies the weight for the class of object detected for the cost function in the detection layer. detection_threshold : float, optional Specifies the threshold for object detection. iou_threshold : float, optional Specifies the IOU Threshold of maximum suppression in object detection. random_boxes : bool, optional Randomizing boxes when loading the bounding box information. Default: False random_flip : string, optional Specifies how to flip the data in the input layer when image data is used. Approximately half of the input data is subject to flipping. Valid Values: 'h', 'hv', 'v', 'none' random_crop : string, optional Specifies how to crop the data in the input layer when image data is used. Images are cropped to the values that are specified in the width and height parameters. Only the images with one or both dimensions that are larger than those sizes are cropped. Valid Values: 'none', 'unique', 'randomresized', 'resizethencrop' Returns ------- :class:`Sequential` References ---------- https://arxiv.org/pdf/1506.02640.pdf ''' model = Sequential(conn=conn, model_table=model_table) parameters = locals() input_parameters = get_layer_options(input_layer_options, parameters) model.add(InputLayer(**input_parameters)) # conv1 448 model.add(Conv2d(32, width=3, act=act, include_bias=False, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv2 224 model.add(Conv2d(64, width=3, act=act, include_bias=False, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv3 112 model.add(Conv2d(128, width=3, act=act, include_bias=False, stride=1)) # conv4 112 model.add(Conv2d(64, width=1, act=act, include_bias=False, stride=1)) # conv5 112 model.add(Conv2d(128, width=3, act=act, include_bias=False, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv6 56 model.add(Conv2d(256, width=3, act=act, include_bias=False, stride=1)) # conv7 56 model.add(Conv2d(128, width=1, act=act, include_bias=False, stride=1)) # conv8 56 model.add(Conv2d(256, width=3, act=act, include_bias=False, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv9 28 model.add(Conv2d(512, width=3, act=act, include_bias=False, stride=1)) # conv10 28 model.add(Conv2d(256, width=1, act=act, include_bias=False, stride=1)) # conv11 28 model.add(Conv2d(512, width=3, act=act, include_bias=False, stride=1)) # conv12 28 model.add(Conv2d(256, width=1, act=act, include_bias=False, stride=1)) # conv13 28 model.add(Conv2d(512, width=3, act=act, include_bias=False, stride=1)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv14 14 model.add(Conv2d(1024, width=3, act=act, include_bias=False, stride=1)) # conv15 14 model.add(Conv2d(512, width=1, act=act, include_bias=False, stride=1)) # conv16 14 model.add(Conv2d(1024, width=3, act=act, include_bias=False, stride=1)) # conv17 14 model.add(Conv2d(512, width=1, act=act, include_bias=False, stride=1)) # conv18 14 model.add(Conv2d(1024, width=3, act=act, include_bias=False, stride=1)) # conv19 14 model.add(Conv2d(1024, width=3, act=act, include_bias=False, stride=1)) # conv20 7 model.add(Conv2d(1024, width=3, act=act, include_bias=False, stride=2)) # conv21 7 model.add(Conv2d(1024, width=3, act=act, include_bias=False, stride=1)) # conv22 7 model.add(Conv2d(1024, width=3, act=act, include_bias=False, stride=1)) # conv23 7 model.add( Conv2d(256, width=3, act=act, include_bias=False, stride=1, dropout=dropout)) model.add( Dense(n=(n_classes + (5 * predictions_per_grid)) * grid_number * grid_number, act='identity')) model.add( Detection(act=act_detection, detection_model_type='yolov1', softmax_for_class_prob=softmax_for_class_prob, coord_type=coord_type, class_number=n_classes, grid_number=grid_number, predictions_per_grid=predictions_per_grid, do_sqrt=do_sqrt, coord_scale=coord_scale, object_scale=object_scale, prediction_not_a_object_scale=prediction_not_a_object_scale, class_scale=class_scale, detection_threshold=detection_threshold, iou_threshold=iou_threshold, random_boxes=random_boxes, max_label_per_image=max_label_per_image, max_boxes=max_boxes)) return model
def Tiny_YoloV2(conn, anchors, model_table='Tiny-Yolov2', n_channels=3, width=416, height=416, scale=1.0 / 255, random_mutation=None, act='leaky', act_detection='AUTO', softmax_for_class_prob=True, coord_type='YOLO', max_label_per_image=30, max_boxes=30, n_classes=20, predictions_per_grid=5, do_sqrt=True, grid_number=13, coord_scale=None, object_scale=None, prediction_not_a_object_scale=None, class_scale=None, detection_threshold=None, iou_threshold=None, random_boxes=False, match_anchor_size=None, num_to_force_coord=None, random_flip=None, random_crop=None): ''' Generate a deep learning model with the Tiny Yolov2 architecture. Tiny Yolov2 is a very small model of Yolov2, so that it includes fewer numbers of convolutional layer and batch normalization layer. Parameters ---------- conn : CAS Specifies the connection of the CAS connection. anchors : list Specifies the anchor box values. model_table : string, optional Specifies the name of CAS table to store the model. n_channels : int, optional Specifies the number of the channels (i.e., depth) of the input layer. Default: 3 width : int, optional Specifies the width of the input layer. Default: 416 height : int, optional Specifies the height of the input layer. Default: 416 scale : double, optional Specifies a scaling factor to be applied to each pixel intensity values. Default: 1.0 / 255 random_mutation : string, optional Specifies how to apply data augmentations/mutations to the data in the input layer. Valid Values: 'none', 'random' act : string, optional Specifies the activation function for the batch normalization layers. Default: 'leaky' act_detection : string, optional Specifies the activation function for the detection layer. Valid Values: AUTO, IDENTITY, LOGISTIC, SIGMOID, TANH, RECTIFIER, RELU, SOFPLUS, ELU, LEAKY, FCMP Default: AUTO softmax_for_class_prob : bool, optional Specifies whether to perform Softmax on class probability per predicted object. Default: True coord_type : string, optional Specifies the format of how to represent bounding boxes. For example, a bounding box can be represented with the x and y locations of the top-left point as well as width and height of the rectangle. This format is the 'rect' format. We also support coco and yolo formats. Valid Values: 'rect', 'yolo', 'coco' Default: 'yolo' max_label_per_image : int, optional Specifies the maximum number of labels per image in the training. Default: 30 max_boxes : int, optional Specifies the maximum number of overall predictions allowed in the detection layer. Default: 30 n_classes : int, optional Specifies the number of classes. If None is assigned, the model will automatically detect the number of classes based on the training set. Default: 20 predictions_per_grid : int, optional Specifies the amount of predictions will be done per grid. Default: 5 do_sqrt : bool, optional Specifies whether to apply the SQRT function to width and height of the object for the cost function. Default: True grid_number : int, optional Specifies the amount of cells to be analyzed for an image. For example, if the value is 5, then the image will be divided into a 5 x 5 grid. Default: 13 coord_scale : float, optional Specifies the weight for the cost function in the detection layer, when objects exist in the grid. object_scale : float, optional Specifies the weight for object detected for the cost function in the detection layer. prediction_not_a_object_scale : float, optional Specifies the weight for the cost function in the detection layer, when objects do not exist in the grid. class_scale : float, optional Specifies the weight for the class of object detected for the cost function in the detection layer. detection_threshold : float, optional Specifies the threshold for object detection. iou_threshold : float, optional Specifies the IOU Threshold of maximum suppression in object detection. random_boxes : bool, optional Randomizing boxes when loading the bounding box information. Default: False match_anchor_size : bool, optional Whether to force the predicted box match the anchor boxes in sizes for all predictions num_to_force_coord : int, optional The number of leading chunk of images in training when the algorithm forces predicted objects in each grid to be equal to the anchor box sizes, and located at the grid center random_flip : string, optional Specifies how to flip the data in the input layer when image data is used. Approximately half of the input data is subject to flipping. Valid Values: 'h', 'hv', 'v', 'none' random_crop : string, optional Specifies how to crop the data in the input layer when image data is used. Images are cropped to the values that are specified in the width and height parameters. Only the images with one or both dimensions that are larger than those sizes are cropped. Valid Values: 'none', 'unique', 'randomresized', 'resizethencrop' Returns ------- :class:`Sequential` References ---------- https://arxiv.org/pdf/1612.08242.pdf ''' model = Sequential(conn=conn, model_table=model_table) parameters = locals() input_parameters = get_layer_options(input_layer_options, parameters) model.add(InputLayer(**input_parameters)) # conv1 416 448 model.add( Conv2d(n_filters=16, width=3, act='identity', include_bias=False, stride=1)) model.add(BN(act=act)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv2 208 224 model.add( Conv2d(n_filters=32, width=3, act='identity', include_bias=False, stride=1)) model.add(BN(act=act)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv3 104 112 model.add( Conv2d(n_filters=64, width=3, act='identity', include_bias=False, stride=1)) model.add(BN(act=act)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv4 52 56 model.add( Conv2d(n_filters=128, width=3, act='identity', include_bias=False, stride=1)) model.add(BN(act=act)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv5 26 28 model.add( Conv2d(n_filters=256, width=3, act='identity', include_bias=False, stride=1)) model.add(BN(act=act)) model.add(Pooling(width=2, height=2, stride=2, pool='max')) # conv6 13 14 model.add( Conv2d(n_filters=512, width=3, act='identity', include_bias=False, stride=1)) model.add(BN(act=act)) model.add(Pooling(width=2, height=2, stride=1, pool='max')) # conv7 13 model.add( Conv2d(n_filters=1024, width=3, act='identity', include_bias=False, stride=1)) model.add(BN(act=act)) # conv8 13 model.add( Conv2d(n_filters=512, width=3, act='identity', include_bias=False, stride=1)) model.add(BN(act=act)) model.add( Conv2d((n_classes + 5) * predictions_per_grid, width=1, act='identity', include_bias=False, stride=1)) model.add( Detection(act=act_detection, detection_model_type='yolov2', anchors=anchors, softmax_for_class_prob=softmax_for_class_prob, coord_type=coord_type, class_number=n_classes, grid_number=grid_number, predictions_per_grid=predictions_per_grid, do_sqrt=do_sqrt, coord_scale=coord_scale, object_scale=object_scale, prediction_not_a_object_scale=prediction_not_a_object_scale, class_scale=class_scale, detection_threshold=detection_threshold, iou_threshold=iou_threshold, random_boxes=random_boxes, max_label_per_image=max_label_per_image, max_boxes=max_boxes, match_anchor_size=match_anchor_size, num_to_force_coord=num_to_force_coord)) return model