def test_minibatch_defined_by_labels(tmpdir): input_dim = 1000 num_output_classes = 5 def assert_data(mb_source): features_si = mb_source.stream_info('features') labels_si = mb_source.stream_info('labels') mb = mb_source.next_minibatch(2) features = mb[features_si] # 2 samples, max seq len 4, 1000 dim assert features.shape == (2, 4, input_dim) assert features.end_of_sweep assert features.num_sequences == 2 assert features.num_samples == 7 assert features.is_sparse labels = mb[labels_si] # 2 samples, max seq len 1, 5 dim assert labels.shape == (2, 1, num_output_classes) assert labels.end_of_sweep assert labels.num_sequences == 2 assert labels.num_samples == 2 assert not labels.is_sparse label_data = labels.asarray() assert np.allclose(label_data, np.asarray([ [[1., 0., 0., 0., 0.]], [[0., 1., 0., 0., 0.]] ])) mb = mb_source.next_minibatch(3) features = mb[features_si] labels = mb[labels_si] assert features.num_samples == 10 assert labels.num_samples == 3 tmpfile = _write_data(tmpdir, MBDATA_SPARSE) mb_source = MinibatchSource(CTFDeserializer(tmpfile, StreamDefs( features=StreamDef(field='x', shape=input_dim, is_sparse=True), labels=StreamDef(field='y', shape=num_output_classes, is_sparse=False, defines_mb_size=True) )), randomize=False) assert_data(mb_source) tmpfile1 = _write_data(tmpdir, MBDATA_SPARSE1, '1') tmpfile2 = _write_data(tmpdir, MBDATA_SPARSE2, '2') combined_mb_source = MinibatchSource([ CTFDeserializer(tmpfile1, StreamDefs( features=StreamDef(field='x', shape=input_dim, is_sparse=True))), CTFDeserializer(tmpfile2, StreamDefs( labels=StreamDef(field='y', shape=num_output_classes, is_sparse=False, defines_mb_size=True) ))], randomize=False) assert_data(combined_mb_source)
def test_eval_sparse_dense(tmpdir, device_id): from cntk import Axis from cntk.io import MinibatchSource, CTFDeserializer, StreamDef, StreamDefs from cntk.ops import input, times input_vocab_dim = label_vocab_dim = 69 ctf_data = '''\ 0 |S0 3:1 |# <s> |S1 3:1 |# <s> 0 |S0 4:1 |# A |S1 32:1 |# ~AH 0 |S0 5:1 |# B |S1 36:1 |# ~B 0 |S0 4:1 |# A |S1 31:1 |# ~AE 0 |S0 7:1 |# D |S1 38:1 |# ~D 0 |S0 12:1 |# I |S1 47:1 |# ~IY 0 |S0 1:1 |# </s> |S1 1:1 |# </s> 2 |S0 60:1 |# <s> |S1 3:1 |# <s> 2 |S0 61:1 |# A |S1 32:1 |# ~AH ''' ctf_file = str(tmpdir / '2seqtest.txt') with open(ctf_file, 'w') as f: f.write(ctf_data) mbs = MinibatchSource(CTFDeserializer( ctf_file, StreamDefs(features=StreamDef(field='S0', shape=input_vocab_dim, is_sparse=True), labels=StreamDef(field='S1', shape=label_vocab_dim, is_sparse=True))), randomize=False, max_samples=2) raw_input = sequence.input(shape=input_vocab_dim, sequence_axis=Axis('inputAxis'), name='raw_input', is_sparse=True) mb_valid = mbs.next_minibatch(minibatch_size_in_samples=100, input_map={raw_input: mbs.streams.features}, device=cntk_device(device_id)) z = times(raw_input, np.eye(input_vocab_dim)) e_reader = z.eval(mb_valid, device=cntk_device(device_id)) # CSR with the raw_input encoding in ctf_data one_hot_data = [[3, 4, 5, 4, 7, 12, 1], [60, 61]] data = [ csr(np.eye(input_vocab_dim, dtype=np.float32)[d]) for d in one_hot_data ] e_csr = z.eval({raw_input: data}, device=cntk_device(device_id)) assert np.all([np.allclose(a, b) for a, b in zip(e_reader, e_csr)]) # One-hot with the raw_input encoding in ctf_data data = Value.one_hot(one_hot_data, num_classes=input_vocab_dim, device=cntk_device(device_id)) e_hot = z.eval({raw_input: data}, device=cntk_device(device_id)) assert np.all([np.allclose(a, b) for a, b in zip(e_reader, e_hot)])
def test_base64_image_deserializer(tmpdir): import io, base64, uuid; from PIL import Image images, b64_images = [], [] np.random.seed(1) for i in range(10): data = np.random.randint(0, 2**8, (5,7,3)) image = Image.fromarray(data.astype('uint8'), "RGB") buf = io.BytesIO() image.save(buf, format='PNG') assert image.width == 7 and image.height == 5 b64_images.append(base64.b64encode(buf.getvalue())) images.append(np.array(image)) image_data = str(tmpdir / 'mbdata1.txt') seq_ids = [] uid = uuid.uuid1().int >> 64 with open(image_data, 'wb') as f: for i,data in enumerate(b64_images): seq_id = uid ^ i seq_id = str(seq_id).encode('ascii') seq_ids.append(seq_id) line = seq_id + b'\t' label = str(i).encode('ascii') line += label + b'\t' + data + b'\n' f.write(line) ctf_data = str(tmpdir / 'mbdata2.txt') with open(ctf_data, 'wb') as f: for i, sid in enumerate(seq_ids): line = sid + b'\t' + b'|index '+str(i).encode('ascii') + b'\n' f.write(line) transforms = [xforms.scale(width=7, height=5, channels=3)] b64_deserializer = Base64ImageDeserializer(image_data, StreamDefs( images=StreamDef(field='image', transforms=transforms), labels=StreamDef(field='label', shape=10))) ctf_deserializer = CTFDeserializer(ctf_data, StreamDefs(index=StreamDef(field='index', shape=1))) mb_source = MinibatchSource([ctf_deserializer, b64_deserializer]) assert isinstance(mb_source, MinibatchSource) for j in range(100): mb = mb_source.next_minibatch(10) index_stream = mb_source.streams['index'] index = mb[index_stream].asarray().flatten() image_stream = mb_source.streams['images'] results = mb[image_stream].asarray() for i in range(10): # original images are RBG, openCV produces BGR images, # reverse the last dimension of the original images bgrImage = images[int(index[i])][:,:,::-1] assert (bgrImage == results[i][0]).all()
def create_mb_source(map_file, image_width, image_height, num_channels, num_classes, randomize=True): transforms = [] transforms += [xforms.crop(crop_type='randomside', side_ratio=0.8)] transforms += [xforms.scale(width=image_width, height=image_height, channels=num_channels, interpolations='linear')] return MinibatchSource(ImageDeserializer(map_file, StreamDefs( features =StreamDef(field='image', transforms=transforms), labels =StreamDef(field='label', shape=num_classes))), randomize=randomize)
def create_reader(path, is_training, input_dim, label_dim): return MinibatchSource( CTFDeserializer( path, StreamDefs(features=StreamDef(field='features', shape=input_dim), labels=StreamDef(field='labels', shape=label_dim))), randomize=is_training, epoch_size=INFINITELY_REPEAT if is_training else FULL_DATA_SWEEP)
def create_reader(path, is_training, input_dim, num_label_classes): """ reads CNTK formatted file with 'labels' and 'features' """ return MinibatchSource(CTFDeserializer(path, StreamDefs( labels = StreamDef(field='labels', shape=num_label_classes), features = StreamDef(field='features', shape=input_dim) )), randomize = is_training, max_sweeps = INFINITELY_REPEAT if is_training else 1)
def create_reader(path, randomize, input_vocab_dim, label_vocab_dim, size=INFINITELY_REPEAT): if not os.path.exists(path): raise RuntimeError("File '%s' does not exist." % (path)) return MinibatchSource(CTFDeserializer(path, StreamDefs( features = StreamDef(field='S0', shape=input_vocab_dim, is_sparse=True), labels = StreamDef(field='S1', shape=label_vocab_dim, is_sparse=True) )), randomize=randomize, max_samples = size)
def create_reader_raw(path, is_training, input_dim, num_label_classes): """ Reads in the unstardized values. """ return MinibatchSource(CTFDeserializer(path, StreamDefs( labels = StreamDef(field='rawlabels', shape=num_label_classes), features = StreamDef(field='rawfeatures', shape=input_dim) )), randomize = is_training, max_sweeps = INFINITELY_REPEAT if is_training else 1)
def test_htk_deserializers(): mbsize = 640 epoch_size = 1000 * mbsize lr = [0.001] feature_dim = 33 num_classes = 132 context = 2 os.chdir(data_path) features_file = "glob_0000.scp" labels_file = "glob_0000.mlf" label_mapping_file = "state.list" fd = HTKFeatureDeserializer( StreamDefs(amazing_features=StreamDef( shape=feature_dim, context=(context, context), scp=features_file))) ld = HTKMLFDeserializer( label_mapping_file, StreamDefs( awesome_labels=StreamDef(shape=num_classes, mlf=labels_file))) reader = MinibatchSource([fd, ld]) features = C.input_variable(((2 * context + 1) * feature_dim)) labels = C.input_variable((num_classes)) model = Sequential( [For(range(3), lambda: Recurrence(LSTM(256))), Dense(num_classes)]) z = model(features) ce = C.cross_entropy_with_softmax(z, labels) errs = C.classification_error(z, labels) learner = C.adam_sgd(z.parameters, lr=C.learning_rate_schedule(lr, C.UnitType.sample, epoch_size), momentum=C.momentum_as_time_constant_schedule(1000), low_memory=True, gradient_clipping_threshold_per_sample=15, gradient_clipping_with_truncation=True) trainer = C.Trainer(z, (ce, errs), learner) input_map = { features: reader.streams.amazing_features, labels: reader.streams.awesome_labels } pp = C.ProgressPrinter(freq=0) # just run and verify it doesn't crash for i in range(3): mb_data = reader.next_minibatch(mbsize, input_map=input_map) trainer.train_minibatch(mb_data) pp.update_with_trainer(trainer, with_metric=True) assert True os.chdir(abs_path)
def test_image(): map_file = "input.txt" mean_file = "mean.txt" feature_name = "f" image_width = 100 image_height = 200 num_channels = 3 label_name = "l" num_classes = 7 transforms = [ xforms.crop(crop_type='randomside', side_ratio=0.5, jitter_type='uniratio'), xforms.scale(width=image_width, height=image_height, channels=num_channels, interpolations='linear'), xforms.mean(mean_file)] defs = StreamDefs(f=StreamDef(field='image', transforms=transforms), l=StreamDef(field='label', shape=num_classes)) image = ImageDeserializer(map_file, defs) config = to_dictionary(MinibatchSourceConfig([image], randomize=False)) assert len(config['deserializers']) == 1 d = config['deserializers'][0] assert d['type'] == 'ImageDeserializer' assert d['file'] == map_file assert set(d['input'].keys()) == {label_name, feature_name} l = d['input'][label_name] assert l['labelDim'] == num_classes f = d['input'][feature_name] assert set(f.keys()) == {'transforms'} t0, t1, t2, _ = f['transforms'] assert t0['type'] == 'Crop' assert t1['type'] == 'Scale' assert t2['type'] == 'Mean' assert t0['cropType'] == 'randomside' assert t0['sideRatio'] == 0.5 assert t0['aspectRatio'] == 1.0 assert t0['jitterType'] == 'uniratio' assert t1['width'] == image_width assert t1['height'] == image_height assert t1['channels'] == num_channels assert t1['interpolations'] == 'linear' assert t2['meanFile'] == mean_file config = to_dictionary(MinibatchSourceConfig([image, image])) assert len(config['deserializers']) == 2 config = to_dictionary(MinibatchSourceConfig([image, image, image])) assert len(config['deserializers']) == 3 # TODO depends on ImageReader.dll '''
def test_minibatch(tmpdir): mbdata = r'''0 |S0 0 |S1 0 0 |S0 1 |S1 1 0 |S0 2 0 |S0 3 |S1 3 1 |S0 4 1 |S0 5 |S1 1 1 |S0 6 |S1 2 ''' tmpfile = str(tmpdir/'mbtest.txt') with open(tmpfile, 'w') as f: f.write(mbdata) from cntk.io import CTFDeserializer, MinibatchSource, StreamDef, StreamDefs mb_source = MinibatchSource(CTFDeserializer(tmpfile, StreamDefs( features = StreamDef(field='S0', shape=1), labels = StreamDef(field='S1', shape=1)))) features_si = mb_source.stream_info('features') labels_si = mb_source.stream_info('labels') mb = mb_source.next_minibatch(1000) assert mb[features_si].num_sequences == 2 assert mb[labels_si].num_sequences == 2 features = mb[features_si] assert len(features.value) == 2 expected_features = \ [ [[0],[1],[2],[3]], [[4],[5],[6]] ] for res, exp in zip (features.value, expected_features): assert np.allclose(res, exp) assert np.allclose(features.mask, [[2, 1, 1, 1], [2, 1, 1, 0]]) labels = mb[labels_si] assert len(labels.value) == 2 expected_labels = \ [ [[0],[1],[3]], [[1],[2]] ] for res, exp in zip (labels.value, expected_labels): assert np.allclose(res, exp) assert np.allclose(labels.mask, [[2, 1, 1], [2, 1, 0]])
def create_reader(path, randomize, size=INFINITELY_REPEAT): return MinibatchSource(CTFDeserializer( path, StreamDefs(features=StreamDef(field='S0', shape=input_vocab_size, is_sparse=True), labels=StreamDef(field='S1', shape=label_vocab_size, is_sparse=True))), randomize=randomize, epoch_size=size)
def mb_source(tmpdir, fileprefix, max_samples=FULL_DATA_SWEEP, ctf=ctf_data, streams = ['S0', 'S1']): ctf_file = str(tmpdir / (fileprefix + '2seqtest.txt')) with open(ctf_file, 'w') as f: f.write(ctf) mbs = MinibatchSource(CTFDeserializer(ctf_file, StreamDefs( features=StreamDef(field=streams[0], shape=input_dim, is_sparse=True), labels=StreamDef(field=streams[1], shape=input_dim, is_sparse=True) )), randomize=False, max_samples=max_samples) return mbs
def create_reader(path, is_training): return MinibatchSource(CTFDeserializer( path, StreamDefs(features=StreamDef(field='S0', shape=input_vocab_dim, is_sparse=True), labels=StreamDef(field='S1', shape=label_vocab_dim, is_sparse=True))), randomize=is_training, max_sweeps=INFINITELY_REPEAT if is_training else 1)
def create_reader(path, is_training, input_dim, output_dim): return MinibatchSource(CTFDeserializer( path, StreamDefs(features=StreamDef(field='attribs', shape=input_dim, is_sparse=False), labels=StreamDef(field='species', shape=output_dim, is_sparse=False))), randomize=is_training, max_sweeps=INFINITELY_REPEAT if is_training else 1)
def create_reader(path): return MinibatchSource( CTFDeserializer( path, StreamDefs( query=StreamDef(field='S0', shape=input_dim, is_sparse=True), intent_unused=StreamDef( field='S1', shape=num_intents, is_sparse=True), # BUGBUG: unused, and should infer dim slot_labels=StreamDef(field='S2', shape=label_dim, is_sparse=True))))
def create_reader(path, is_training, input_dim, label_dim): """Create MinibatchSource for reaching training data from given file""" return MinibatchSource(CTFDeserializer( path, StreamDefs(features=StreamDef(field='features', shape=input_dim, is_sparse=False), labels=StreamDef(field='labels', shape=label_dim, is_sparse=False))), randomize=is_training, max_sweeps=INFINITELY_REPEAT if is_training else 1)
def create_feature_deserializer(path): transforms = [xforms.scale(width = ImageW, height = ImageH, channels = ImageC, interpolations = "linear")] deserializer = ImageDeserializer( path, StreamDefs( features = StreamDef(field = 'image', transforms = transforms), ignored = StreamDef(field = 'label', shape = 1) ) ) deserializer['grayscale'] = Grayscale return deserializer
def test_text_format(tmpdir): tmpfile = _write_data(tmpdir, MBDATA_SPARSE) input_dim = 1000 num_output_classes = 5 mb_source = MinibatchSource(CTFDeserializer( tmpfile, StreamDefs(features=StreamDef(field='x', shape=input_dim, is_sparse=True), labels=StreamDef(field='y', shape=num_output_classes, is_sparse=False))), randomize=False) assert isinstance(mb_source, MinibatchSource) features_si = mb_source.stream_info('features') labels_si = mb_source.stream_info('labels') mb = mb_source.next_minibatch(7) features = mb[features_si] # 2 samples, max seq len 4, 1000 dim assert features.shape == (2, 4, input_dim) assert features.end_of_sweep assert features.num_sequences == 2 assert features.num_samples == 7 assert features.is_sparse labels = mb[labels_si] # 2 samples, max seq len 1, 5 dim assert labels.shape == (2, 1, num_output_classes) assert labels.end_of_sweep assert labels.num_sequences == 2 assert labels.num_samples == 2 assert not labels.is_sparse label_data = labels.asarray() assert np.allclose( label_data, np.asarray([[[1., 0., 0., 0., 0.]], [[0., 1., 0., 0., 0.]]])) mb = mb_source.next_minibatch(1) features = mb[features_si] labels = mb[labels_si] assert not features.end_of_sweep assert not labels.end_of_sweep assert features.num_samples < 7 assert labels.num_samples == 1
def create_mb_source(features_file, labels_file, label_mapping_filem, total_number_of_samples): for file_name in [features_file, labels_file, label_mapping_file]: if not os.path.exists(file_name): raise RuntimeError("File '%s' does not exist. Please check that datadir argument is set correctly." % (file_name)) fd = HTKFeatureDeserializer(StreamDefs( amazing_features = StreamDef(shape=feature_dim, context=(context,context), scp=features_file))) ld = HTKMLFDeserializer(label_mapping_file, StreamDefs( awesome_labels = StreamDef(shape=num_classes, mlf=labels_file))) # Enabling BPTT with truncated_length > 0 return MinibatchSource([fd,ld], truncation_length=250, epoch_size=total_number_of_samples)
def cbf_reader(path, is_training, max_samples): """ Returns a MinibatchSource for data at the given path :param path: Path to a CBF file :param is_training: Set to true if reader is for training set, else false :param max_samples: Max no. of samples to read """ deserializer = CBFDeserializer(path, StreamDefs( label=StreamDef(field='label', shape=num_classes, is_sparse=True), front=StreamDef(field='pixels', shape=num_channels * frame_height * frame_width, is_sparse=False), )) return MinibatchSource(deserializer, randomize=is_training, max_samples=max_samples)
def test_text_format(tmpdir): from cntk.io import CTFDeserializer, MinibatchSource, StreamDef, StreamDefs mbdata = r'''0 |x 560:1 |y 1 0 0 0 0 0 |x 0:1 0 |x 0:1 1 |x 560:1 |y 0 1 0 0 0 1 |x 0:1 1 |x 0:1 1 |x 424:1 ''' tmpfile = str(tmpdir/'mbdata.txt') with open(tmpfile, 'w') as f: f.write(mbdata) input_dim = 1000 num_output_classes = 5 mb_source = MinibatchSource(CTFDeserializer(tmpfile, StreamDefs( features = StreamDef(field='x', shape=input_dim, is_sparse=True), labels = StreamDef(field='y', shape=num_output_classes, is_sparse=False) ))) assert isinstance(mb_source, MinibatchSource) features_si = mb_source.stream_info('features') labels_si = mb_source.stream_info('labels') mb = mb_source.next_minibatch(7) features = mb[features_si] # 2 samples, max seq len 4, 1000 dim assert features.shape == (2, 4, input_dim) assert features.is_sparse # TODO features is sparse and cannot be accessed right now: # *** RuntimeError: DataBuffer/WritableDataBuffer methods can only be called for NDArrayiew objects with dense storage format # 2 samples, max seq len 4, 1000 dim #assert features.data().shape().dimensions() == (2, 4, input_dim) #assert features.data().is_sparse() labels = mb[labels_si] # 2 samples, max seq len 1, 5 dim assert labels.shape == (2, 1, num_output_classes) assert not labels.is_sparse label_data = np.asarray(labels) assert np.allclose(label_data, np.asarray([ [[ 1., 0., 0., 0., 0.]], [[ 0., 1., 0., 0., 0.]] ]))
def create_reader(path, is_training): return MinibatchSource( CTFDeserializer( path, StreamDefs( query=StreamDef(field='S0', shape=vocab_size, is_sparse=True), intent_labels=StreamDef( field='S1', shape=num_intents, is_sparse=True ), # (used for intent classification variant) slot_labels=StreamDef(field='S2', shape=num_labels, is_sparse=True))), randomize=is_training, max_sweeps=INFINITELY_REPEAT if is_training else 1)
def test_image_with_crop_range(): map_file = "input.txt" feature_name = "f" image_width = 100 image_height = 200 num_channels = 3 label_name = "l" num_classes = 7 transforms = [ xforms.crop(crop_type='randomside', crop_size=(512, 424), side_ratio=(0.2, 0.5), area_ratio=(0.1, 0.75), aspect_ratio=(0.3, 0.8), jitter_type='uniratio') ] defs = StreamDefs(f=StreamDef(field='image', transforms=transforms), l=StreamDef(field='label', shape=num_classes)) image = ImageDeserializer(map_file, defs) config = to_dictionary(MinibatchSourceConfig([image], randomize=False)) assert len(config['deserializers']) == 1 d = config['deserializers'][0] assert d['type'] == 'ImageDeserializer' assert d['file'] == map_file assert set(d['input'].keys()) == {label_name, feature_name} l = d['input'][label_name] assert l['labelDim'] == num_classes f = d['input'][feature_name] assert set(f.keys()) == {'transforms'} t0, _ = f['transforms'] assert t0['type'] == 'Crop' assert t0['cropType'] == 'randomside' assert t0['cropSize'] == '512:424' assert t0['sideRatio'] == '0.2:0.5' assert t0['aspectRatio'] == '0.3:0.8' assert t0['areaRatio'] == '0.1:0.75' assert t0['jitterType'] == 'uniratio' config = to_dictionary(MinibatchSourceConfig([image, image])) assert len(config['deserializers']) == 2 config = to_dictionary(MinibatchSourceConfig([image, image, image])) assert len(config['deserializers']) == 3
def test_prefetch_with_unpacking(tmpdir): data = r'''0 |S0 1 1 1 1 |S1 1000 1 |S0 2 2 2 2 |S1 100 2 |S0 3 3 3 3 |S1 100 3 |S0 1 1 1 1 |S1 10 4 |S0 2 2 2 2 |S1 1 5 |S0 3 3 3 3 |S1 2000 6 |S0 1 1 1 1 |S1 200 7 |S0 2 2 2 2 |S1 200 8 |S0 3 3 3 3 |S1 20 9 |S0 1 1 1 1 |S1 2 ''' import time tmpfile = _write_data(tmpdir, data) input_dim = 4 num_output_classes = 1 mb_source = MinibatchSource(CTFDeserializer( tmpfile, StreamDefs(features=StreamDef(field='S0', shape=input_dim, is_sparse=False), labels=StreamDef(field='S1', shape=num_output_classes, is_sparse=False))), randomize=False, max_samples=FULL_DATA_SWEEP) input_map = { 'S0': mb_source.streams.features, 'S1': mb_source.streams.labels } empty = False mb_size = 3 # On the last minibatch there will be resize called, # due to 10%3 = 1 sample in the minibatch while not empty: mb = mb_source.next_minibatch(mb_size, input_map=input_map) time.sleep(1) # make sure the prefetch kicks in if mb: # Force unpacking to check that we do # not break prefetch actual_size = mb['S0'].shape[0] assert (mb['S0'].asarray() == np.array( [[[1, 1, 1, 1]], [[2, 2, 2, 2]], [[3, 3, 3, 3]]], dtype=np.float32)[0:actual_size]).all() else: empty = True
def test_crop_dimensionality(tmpdir): import io; from PIL import Image np.random.seed(1) file_mapping_path = str(tmpdir / 'file_mapping.txt') with open(file_mapping_path, 'w') as file_mapping: for i in range(5): data = np.random.randint(0, 2**8, (20, 40, 3)) image = Image.fromarray(data.astype('uint8'), "RGB") buf = io.BytesIO() image.save(buf, format='PNG') assert image.width == 40 and image.height == 20 label = str(i) # save to mapping + png file file_name = label + '.png' with open(str(tmpdir/file_name), 'wb') as f: f.write(buf.getvalue()) file_mapping.write('.../%s\t%s\n' % (file_name, label)) transforms1 = [ xforms.scale(width=40, height=20, channels=3), xforms.crop(crop_type='randomside', crop_size=(20, 10), side_ratio=(0.2, 0.5), jitter_type='uniratio')] transforms2 = [ xforms.crop(crop_type='randomside', crop_size=(20, 10), side_ratio=(0.2, 0.5), jitter_type='uniratio')] d1 = ImageDeserializer(file_mapping_path, StreamDefs( images1=StreamDef(field='image', transforms=transforms1), labels1=StreamDef(field='label', shape=10))) d2 = ImageDeserializer(file_mapping_path, StreamDefs( images2=StreamDef(field='image', transforms=transforms2), labels2=StreamDef(field='label', shape=10))) mbs = MinibatchSource([d1, d2]) for j in range(5): mb = mbs.next_minibatch(1) images1 = mb[mbs.streams.images1].asarray() images2 = mb[mbs.streams.images2].asarray() assert images1.shape == (1, 1, 3, 10, 20) assert (images1 == images2).all()
def create_mb_source(img_height, img_width, img_channels, n_classes, n_rois, data_path, data_set): rois_dim = 4 * n_rois label_dim = n_classes * n_rois path = os.path.normpath(os.path.join(abs_path, data_path)) if data_set == 'test': map_file = os.path.join(path, test_map_filename) else: map_file = os.path.join(path, train_map_filename) roi_file = os.path.join(path, data_set + rois_filename_postfix) label_file = os.path.join(path, data_set + roilabels_filename_postfix) if not os.path.exists(map_file) or not os.path.exists( roi_file) or not os.path.exists(label_file): raise RuntimeError( "File '%s', '%s' or '%s' does not exist. " "Please run install_data_and_model.py from Examples/Image/Detection/FastRCNN to fetch them" % (map_file, roi_file, label_file)) # read images transforms = [ scale(width=img_width, height=img_height, channels=img_channels, scale_mode="pad", pad_value=114, interpolations='linear') ] image_source = ImageDeserializer( map_file, StreamDefs(features=StreamDef(field='image', transforms=transforms))) # read rois and labels roi_source = CTFDeserializer( roi_file, StreamDefs(rois=StreamDef( field=roi_stream_name, shape=rois_dim, is_sparse=False))) label_source = CTFDeserializer( label_file, StreamDefs(roiLabels=StreamDef( field=label_stream_name, shape=label_dim, is_sparse=False))) # define a composite reader return MinibatchSource([image_source, roi_source, label_source], max_samples=sys.maxsize, randomize=data_set == "train")
def test_base64_is_equal_image(tmpdir): import io, base64 from PIL import Image np.random.seed(1) file_mapping_path = str(tmpdir / 'file_mapping.txt') base64_mapping_path = str(tmpdir / 'base64_mapping.txt') with open(file_mapping_path, 'w') as file_mapping: with open(base64_mapping_path, 'w') as base64_mapping: for i in range(10): data = np.random.randint(0, 2**8, (5, 7, 3)) image = Image.fromarray(data.astype('uint8'), "RGB") buf = io.BytesIO() image.save(buf, format='PNG') assert image.width == 7 and image.height == 5 label = str(i) # save to base 64 mapping file encoded = base64.b64encode(buf.getvalue()).decode('ascii') base64_mapping.write('%s\t%s\n' % (label, encoded)) # save to mapping + png file file_name = label + '.png' with open(str(tmpdir / file_name), 'wb') as f: f.write(buf.getvalue()) file_mapping.write('.../%s\t%s\n' % (file_name, label)) transforms = [xforms.scale(width=7, height=5, channels=3)] b64_deserializer = Base64ImageDeserializer( base64_mapping_path, StreamDefs(images1=StreamDef(field='image', transforms=transforms), labels1=StreamDef(field='label', shape=10))) file_image_deserializer = ImageDeserializer( file_mapping_path, StreamDefs(images2=StreamDef(field='image', transforms=transforms), labels2=StreamDef(field='label', shape=10))) mb_source = MinibatchSource([b64_deserializer, file_image_deserializer]) for j in range(20): mb = mb_source.next_minibatch(1) images1_stream = mb_source.streams['images1'] images1 = mb[images1_stream].asarray() images2_stream = mb_source.streams['images2'] images2 = mb[images2_stream].asarray() assert (images1 == images2).all()
def test_MinibatchData_and_Value_as_input(tmpdir): mbdata = r'''0 |S0 100''' tmpfile = str(tmpdir / 'mbtest.txt') with open(tmpfile, 'w') as f: f.write(mbdata) defs = StreamDefs(f1=StreamDef(field='S0', shape=1)) mb_source = MinibatchSource(CTFDeserializer(tmpfile, defs), randomize=False) f1_si = mb_source.stream_info('f1') mb = mb_source.next_minibatch(1) f1 = input(shape=(1, ), needs_gradient=True, name='f') res = f1 * 2 assert res.eval({f1: mb[f1_si]}) == [[200]] # Test MinibatchData assert res.eval(mb[f1_si]) == [[200]] # Test Value assert res.eval(mb[f1_si].data) == [[200]] # Test NumPy (converted back from MinibatchData) assert res.eval(mb[f1_si].asarray()) == [[200]] # Test Value assert res.eval(mb[f1_si].data) == [[200]]
def mb_source(tmpdir, fileprefix, epoch_size=FULL_DATA_SWEEP): ctf_file = str(tmpdir / (fileprefix + '2seqtest.txt')) with open(ctf_file, 'w') as f: f.write(ctf_data) mbs = MinibatchSource(CTFDeserializer( ctf_file, StreamDefs(features=StreamDef(field='S0', shape=input_dim, is_sparse=True), labels=StreamDef(field='S1', shape=input_dim, is_sparse=True))), randomize=False, epoch_size=epoch_size) return mbs