def test_22(self): layers = [ InputLayer(3, 4), Conv2d(8, 7), BN(), Dense(n=32), OutputLayer() ] Sequential(self.s, layers=layers, model_table='table22')
def test_mix_cnn_rnn_network(self): from dlpy.applications import ResNet50_Caffe from dlpy import Sequential from dlpy.blocks import Bidirectional # the case is to test if CNN and RNN model can be connect using functional api # the model_type is expected to be RNN in 19w47. # CNN model = ResNet50_Caffe(self.s) cnn_head = model.to_functional_model(stop_layers=model.layers[-1]) # RNN model_rnn = Sequential(conn=self.s, model_table='rnn') model_rnn.add(Bidirectional(n=100, n_blocks=2)) model_rnn.add(OutputLayer('fixed')) f_rnn = model_rnn.to_functional_model() # connecting inp = Input(**cnn_head.layers[0].config) x = cnn_head(inp) y = f_rnn(x) cnn_rnn = Model(self.s, inp, y) cnn_rnn.compile() # check type self.assertTrue(cnn_rnn.model_type == 'RNN') self.assertTrue(cnn_rnn.layers[-1].name == 'fixed') f_rnn = model_rnn.to_functional_model() # connecting inp = Input(**cnn_head.layers[0].config) x = cnn_head(inp) y = f_rnn(x) cnn_rnn = Model(self.s, inp, y) cnn_rnn.compile() # it should be fixed if I create f_rnn again. self.assertTrue(cnn_rnn.layers[-1].name == 'fixed') inp = Input(**cnn_head.layers[0].config) x = cnn_head(inp) y = f_rnn(x) cnn_rnn = Model(self.s, inp, y) cnn_rnn.compile() # it should be fixed if I create f_rnn again. self.assertTrue(cnn_rnn.layers[-1].name == 'fixed_2')
def SequenceLabeling(conn, model_table='sequence_labeling_model', neurons=10, n_blocks=3, rnn_type='gru'): ''' Generates a sequence labeling model. Parameters ---------- conn : CAS Specifies the CAS connection object. model_table : string, optional Specifies the name of CAS table to store the model. neurons : int, optional Specifies the number of neurons to be in each layer. Default: 10 n_blocks : int, optional Specifies the number of bidirectional blocks to be added to the model. Default: 3 rnn_type : string, optional Specifies the type of the rnn layer. Default: GRU Valid Values: RNN, LSTM, GRU Returns ------- :class:`Sequential` ''' conn.retrieve('loadactionset', _messagelevel='error', actionset='deeplearn') if n_blocks >= 1: model = Sequential(conn=conn, model_table=model_table) model.add( Bidirectional(n=neurons, n_blocks=n_blocks, rnn_type=rnn_type, name='bi_' + rnn_type + '_layer_')) model.add(OutputLayer()) else: raise DLPyError( 'The number of blocks for a sequence labeling model should be at least 1.' ) return model
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 test_2(self): layers = [InputLayer(), Dense(n=32), OutputLayer()] Sequential(self.s, layers=layers, model_table='table2')
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_new_bidirectional3(self): model = Sequential(self.s, model_table='new_table3') model.add(Bidirectional(n=[10, 20, 30], n_blocks=3)) model.add(OutputLayer()) model.print_summary()
def test_1(self): with self.assertRaises(DLPyError): Sequential(self.s, layers='', model_table='table1')
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_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_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_model_forecast3(self): import datetime try: import pandas as pd except: unittest.TestCase.skipTest(self, "pandas not found in the libraries") import numpy as np filename1 = os.path.join(os.path.dirname(__file__), 'datasources', 'timeseries_exp1.csv') importoptions1 = dict(filetype='delimited', delimiter=',') if self.data_dir is None: unittest.TestCase.skipTest(self, "DLPY_DATA_DIR is not set in the environment variables") self.table3 = TimeseriesTable.from_localfile(self.s, filename1, importoptions=importoptions1) self.table3.timeseries_formatting(timeid='datetime', timeseries=['series', 'covar'], timeid_informat='ANYDTDTM19.', timeid_format='DATETIME19.') self.table3.timeseries_accumlation(acc_interval='day', groupby=['id1var', 'id2var']) self.table3.prepare_subsequences(seq_len=2, target='series', predictor_timeseries=['series', 'covar'], missing_handling='drop') valid_start = datetime.date(2015, 1, 4) test_start = datetime.date(2015, 1, 7) traintbl, validtbl, testtbl = self.table3.timeseries_partition( validation_start=valid_start, testing_start=test_start) sascode = ''' data {}; set {}; drop series_lag1; run; '''.format(validtbl.name, validtbl.name) self.s.retrieve('dataStep.runCode', _messagelevel='error', code=sascode) sascode = ''' data {}; set {}; drop series_lag1; run; '''.format(testtbl.name, testtbl.name) self.s.retrieve('dataStep.runCode', _messagelevel='error', code=sascode) model1 = Sequential(self.s, model_table='lstm_rnn') model1.add(InputLayer(std='STD')) model1.add(Recurrent(rnn_type='LSTM', output_type='encoding', n=15, reversed_=False)) model1.add(OutputLayer(act='IDENTITY')) optimizer = Optimizer(algorithm=AdamSolver(learning_rate=0.01), mini_batch_size=32, seed=1234, max_epochs=10) seq_spec = Sequence(**traintbl.sequence_opt) result = model1.fit(traintbl, optimizer=optimizer, sequence=seq_spec, **traintbl.inputs_target) self.assertTrue(result.severity == 0) resulttbl1 = model1.forecast(validtbl, horizon=1) self.assertTrue(isinstance(resulttbl1, CASTable)) self.assertTrue(resulttbl1.shape[0]==15) local_resulttbl1 = resulttbl1.to_frame() unique_time = local_resulttbl1.datetime.unique() self.assertTrue(len(unique_time)==1) self.assertTrue(pd.Timestamp(unique_time[0])==datetime.datetime(2015,1,4)) resulttbl2 = model1.forecast(validtbl, horizon=3) self.assertTrue(isinstance(resulttbl2, CASTable)) self.assertTrue(resulttbl2.shape[0]==45) local_resulttbl2 = resulttbl2.to_frame() local_resulttbl2.sort_values(by=['id1var', 'id2var', 'datetime'], inplace=True) unique_time = local_resulttbl2.datetime.unique() self.assertTrue(len(unique_time)==3) for i in range(3): self.assertTrue(pd.Timestamp(unique_time[i])==datetime.datetime(2015,1,4+i)) series_lag1 = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), 'series_lag1'].values series_lag2 = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), 'series_lag2'].values DL_Pred = local_resulttbl2.loc[(local_resulttbl2.id1var==1) & (local_resulttbl2.id2var==1), '_DL_Pred_'].values self.assertTrue(np.array_equal(series_lag1[1:3], DL_Pred[0:2])) self.assertTrue(series_lag2[2]==DL_Pred[0]) with self.assertRaises(RuntimeError): resulttbl3 = model1.forecast(testtbl, horizon=3)
def test_model16(self): model = Sequential(self.s, model_table='Simple_CNN') model.add(layer=InputLayer(n_channels=1, height=10, width=10)) model.add(layer=Keypoints(n=10)) self.assertTrue(model.summary.loc[1, 'Number of Parameters'] == (1000, 10))
def test_model14(self): model = Sequential(self.s, model_table='Simple_CNN') model.add(layer=InputLayer(n_channels=1, height=10, width=10)) model.add(layer=OutputLayer()) model.summary
def test_model13b(self): model = Sequential(self.s, model_table='simple_cnn') model.add(layer=InputLayer(n_channels=1, height=10, width=10)) model.add(layer=OutputLayer(n=10, full_connect=False)) self.assertTrue(model.summary.loc[1, 'Number of Parameters'] == (0, 0)) model1 = Sequential(self.s, model_table='simple_cnn') model1.add(layer=InputLayer(n_channels=1, height=10, width=10)) model1.add(layer=OutputLayer(n=10, full_connect=True)) self.assertTrue(model1.summary.loc[1, 'Number of Parameters'] == (1000, 10)) model2 = Sequential(self.s, model_table='Simple_CNN') model2.add(layer=InputLayer(n_channels=1, height=10, width=10)) model2.add(layer=OutputLayer(n=10, full_connect=True, include_bias=False)) self.assertTrue(model2.summary.loc[1, 'Number of Parameters'] == (1000, 0)) model3 = Sequential(self.s, model_table='Simple_CNN') model3.add(layer=InputLayer(n_channels=1, height=10, width=10)) model3.add(layer=Conv2d(4, 3)) model3.add(layer=OutputLayer(n=10)) self.assertTrue(model3.summary.loc[2, 'Number of Parameters'] == (4000, 10)) model4 = Sequential(self.s, model_table='Simple_CNN') model4.add(layer=InputLayer(n_channels=1, height=10, width=10)) model4.add(layer=Conv2d(4, 3)) model4.add(layer=OutputLayer(n=10, full_connect=False)) self.assertTrue(model4.summary.loc[2, 'Number of Parameters'] == (0, 0))
def test_simple_cnn_seq2(self): model1 = Sequential(self.s, model_table='table8') 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)) model1.print_summary()
def test_conv1d_model(self): # a model from https://blog.goodaudience.com/introduction-to-1d-convolutional-neural-networks-in-keras-for-time-sequences-3a7ff801a2cf Conv1D = Conv1d MaxPooling1D=Pooling model_m = Sequential(self.s) model_m.add(InputLayer(width=80*3, height=1, n_channels=1)) model_m.add(Conv1D(100, 10, act='relu')) model_m.add(Conv1D(100, 10, act='relu')) model_m.add(MaxPooling1D(3)) model_m.add(Conv1D(160, 10, act='relu')) model_m.add(Conv1D(160, 10, act='relu')) model_m.add(GlobalAveragePooling1D(dropout=0.5)) model_m.add(OutputLayer(n=6, act='softmax')) # use assertEqual to check whether the layer output size matches the expected value for MaxPooling1D self.assertEqual(model_m.layers[3].output_size, (1, 80, 100)) model_m.print_summary() # 1d print summary numerical check self.assertEqual(model_m.summary.iloc[1, -1], 240000)
def test_new_bidirectional1(self): model = Sequential(self.s, model_table='new_table1') model.add(Bidirectional(n=10)) model.add(OutputLayer()) model.print_summary()
def test_sequential_conversion(self): from dlpy.sequential import Sequential model1 = Sequential(self.s) 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)) func_model = model1.to_functional_model() func_model.compile() func_model.print_summary()
def test_new_bidirectional6(self): model = Sequential(self.s, model_table='new_table5') model.add(InputLayer()) r1 = Recurrent(n=10, name='rec1') model.add(r1) model.add(Bidirectional(n=20, src_layers=[r1])) model.add(Recurrent(n=10)) model.add(OutputLayer()) model.print_summary()
def test_3(self): model1 = Sequential(self.s, model_table='table3') model1.add(InputLayer(3, 224, 224)) model1.add(Conv2d(8, 7)) model1.pop()
def test_11(self): with self.assertRaises(DLPyError): model1 = Sequential(self.s, model_table='table11') model1.add(Conv2d(8, 7)) model1.compile()
def test_5(self): with self.assertRaises(DLPyError): model1 = Sequential(self.s, model_table='table5') model1.compile()
def test_stop_layers(self): from dlpy.sequential import Sequential model1 = Sequential(self.s) 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)) inputlayer = model1.layers[0] inp = Input(**inputlayer.config) func_model = model1.to_functional_model( stop_layers=[model1.layers[-1]]) x = func_model(inp) out = Keypoints(n=10)(x) func_model_keypoints = Model(self.s, inp, out) func_model_keypoints.compile() func_model_keypoints.print_summary()
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_4(self): model1 = Sequential(self.s, model_table='table4') model1.add(Conv2d(8, 7)) model1.add(InputLayer(3, 224, 224)) model1.switch(0, 1)
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
def test_6(self): model1 = Sequential(self.s, model_table='table6') model1.add(Bidirectional(n=10, n_blocks=3)) model1.add(OutputLayer())
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