def main(args): eddl.download_mnist() num_classes = 10 in_ = eddl.Input([784]) layer = in_ layer = eddl.Reshape(layer, [1, 28, 28]) layer = eddl.RandomCropScale(layer, [0.9, 1.0]) layer = eddl.Reshape(layer, [-1]) layer = eddl.ReLu( eddl.GaussianNoise( eddl.BatchNormalization(eddl.Dense(layer, 1024), True), 0.3)) layer = eddl.ReLu( eddl.GaussianNoise( eddl.BatchNormalization(eddl.Dense(layer, 1024), True), 0.3)) layer = eddl.ReLu( eddl.GaussianNoise( eddl.BatchNormalization(eddl.Dense(layer, 1024), True), 0.3)) out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.sgd(0.01, 0.9), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("mnist_trX.bin") y_train = Tensor.load("mnist_trY.bin") x_test = Tensor.load("mnist_tsX.bin") y_test = Tensor.load("mnist_tsY.bin") if args.small: x_train = x_train.select([":6000"]) y_train = y_train.select([":6000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) x_train.div_(255.0) x_test.div_(255.0) eddl.fit(net, [x_train], [y_train], args.batch_size, args.epochs) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) # LR annealing if args.epochs < 4: return eddl.setlr(net, [0.005, 0.9]) eddl.fit(net, [x_train], [y_train], args.batch_size, args.epochs // 2) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) eddl.setlr(net, [0.001, 0.9]) eddl.fit(net, [x_train], [y_train], args.batch_size, args.epochs // 2) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) eddl.setlr(net, [0.0001, 0.9]) eddl.fit(net, [x_train], [y_train], args.batch_size, args.epochs // 4) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): if not os.path.isfile(args.input): raise RuntimeError("input file '%s' not found" % args.input) eddl.download_mnist() print("importing net from", args.input) net = eddl.import_net_from_onnx_file(args.input) print("input.shape:", net.layers[0].input.shape) print("output size =", len(net.lout)) eddl.build( net, eddl.rmsprop(0.01), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem), False # do not initialize weights to random values ) net.resize(args.batch_size) # resize manually since we don't use "fit" eddl.summary(net) x_test = Tensor.load("mnist_tsX.bin") y_test = Tensor.load("mnist_tsY.bin") x_test.div_(255.0) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def load_cifar(path=None, download=False): if path is None: path = "./" if download: eddl.download_cifar10() print(path) try: x_train = Tensor.load(path + "/cifar_trX.bin") y_train = Tensor.load(path + "/cifar_trY.bin") except: print( "Fail to load the train set, make sure you supply the correct path" ) exit() try: x_test = Tensor.load(path + "/cifar_tsX.bin") y_test = Tensor.load(path + "/cifar_tsY.bin") except: print( "Fail to load the test set, make sure you supply the correct path") exit() x_train.div_(255.0) x_test.div_(255.0) return (x_train, y_train), (x_test, y_test)
def main(args): eddl.download_cifar10() num_classes = 10 in_ = eddl.Input([3, 32, 32]) layer = in_ layer = eddl.RandomCropScale(layer, [0.8, 1.0]) layer = eddl.RandomHorizontalFlip(layer) layer = eddl.ReLu(BG(eddl.Conv(layer, 64, [3, 3], [1, 1], "same", False))) layer = eddl.Pad(layer, [0, 1, 1, 0]) for i in range(3): layer = ResBlock(layer, 64, 0, i == 0) for i in range(4): layer = ResBlock(layer, 128, i == 0) for i in range(6): layer = ResBlock(layer, 256, i == 0) for i in range(3): layer = ResBlock(layer, 512, i == 0) layer = eddl.MaxPool(layer, [4, 4]) layer = eddl.Reshape(layer, [-1]) out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.sgd(0.001, 0.9), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(net) eddl.plot(net, "model.pdf", "TB") x_train = Tensor.load("cifar_trX.bin") y_train = Tensor.load("cifar_trY.bin") x_train.div_(255.0) x_test = Tensor.load("cifar_tsX.bin") y_test = Tensor.load("cifar_tsY.bin") x_test.div_(255.0) if args.small: # this is slow, make it really small x_train = x_train.select([":500"]) y_train = y_train.select([":500"]) x_test = x_test.select([":100"]) y_test = y_test.select([":100"]) lr = 0.01 for j in range(3): lr /= 10.0 eddl.setlr(net, [lr, 0.9]) for i in range(args.epochs): eddl.fit(net, [x_train], [y_train], args.batch_size, 1) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): eddl.download_cifar10() num_classes = 10 in_ = eddl.Input([3, 32, 32]) layer = in_ layer = eddl.MaxPool(eddl.ReLu(Normalization( eddl.Conv(layer, 32, [3, 3], [1, 1]) )), [2, 2]) layer = eddl.MaxPool(eddl.ReLu(Normalization( eddl.Conv(layer, 64, [3, 3], [1, 1]) )), [2, 2]) layer = eddl.MaxPool(eddl.ReLu(Normalization( eddl.Conv(layer, 128, [3, 3], [1, 1]) )), [2, 2]) layer = eddl.MaxPool(eddl.ReLu(Normalization( eddl.Conv(layer, 256, [3, 3], [1, 1]) )), [2, 2]) layer = eddl.GlobalMaxPool(layer) layer = eddl.Flatten(layer) layer = eddl.Activation(eddl.Dense(layer, 128), "relu") out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.adam(0.001), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("cifar_trX.bin") y_train = Tensor.load("cifar_trY.bin") x_train.div_(255.0) x_test = Tensor.load("cifar_tsX.bin") y_test = Tensor.load("cifar_tsY.bin") x_test.div_(255.0) if args.small: x_train = x_train.select([":5000"]) y_train = y_train.select([":5000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) for i in range(args.epochs): eddl.fit(net, [x_train], [y_train], args.batch_size, 1) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): eddl.download_cifar10() num_classes = 10 in_ = eddl.Input([3, 32, 32]) layer = in_ layer = eddl.RandomCropScale(layer, [0.8, 1.0]) layer = eddl.RandomFlip(layer, 1) layer = eddl.ReLu(BG(eddl.Conv(layer, 64, [3, 3], [1, 1]))) layer = eddl.Pad(layer, [0, 1, 1, 0]) layer = ResBlock(layer, 64, 2, True) layer = ResBlock(layer, 64, 2, False) layer = ResBlock(layer, 128, 2, True) layer = ResBlock(layer, 128, 2, False) layer = ResBlock(layer, 256, 2, True) layer = ResBlock(layer, 256, 2, False) layer = ResBlock(layer, 256, 2, True) layer = ResBlock(layer, 256, 2, False) layer = eddl.Reshape(layer, [-1]) layer = eddl.ReLu(BG(eddl.Dense(layer, 512))) out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.sgd(0.01, 0.9), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(net) eddl.plot(net, "model.pdf", "TB") x_train = Tensor.load("cifar_trX.bin") y_train = Tensor.load("cifar_trY.bin") x_train.div_(255.0) x_test = Tensor.load("cifar_tsX.bin") y_test = Tensor.load("cifar_tsY.bin") x_test.div_(255.0) if args.small: x_train = x_train.select([":5000"]) y_train = y_train.select([":5000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) for i in range(args.epochs): eddl.fit(net, [x_train], [y_train], args.batch_size, 1) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): eddl.download_cifar10() num_classes = 10 in_ = eddl.Input([3, 32, 32]) layer = in_ layer = eddl.RandomCropScale(layer, [0.8, 1.0]) layer = eddl.RandomFlip(layer, 1) layer = eddl.RandomCutout(layer, [0.1, 0.3], [0.1, 0.3]) layer = eddl.MaxPool(Block3_2(layer, 64)) layer = eddl.MaxPool(Block3_2(layer, 128)) layer = eddl.MaxPool(Block1(Block3_2(layer, 256), 256)) layer = eddl.MaxPool(Block1(Block3_2(layer, 512), 512)) layer = eddl.MaxPool(Block1(Block3_2(layer, 512), 512)) layer = eddl.Reshape(layer, [-1]) layer = eddl.Activation(eddl.Dense(layer, 512), "relu") out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.sgd(0.001, 0.9), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.setlogfile(net, "vgg16") eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("cifar_trX.bin") y_train = Tensor.load("cifar_trY.bin") x_train.div_(255.0) x_test = Tensor.load("cifar_tsX.bin") y_test = Tensor.load("cifar_tsY.bin") x_test.div_(255.0) if args.small: x_train = x_train.select([":5000"]) y_train = y_train.select([":5000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) for i in range(args.epochs): eddl.fit(net, [x_train], [y_train], args.batch_size, 1) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): eddl.download_mnist() num_classes = 10 in_ = eddl.Input([784]) layer = in_ layer = eddl.Reshape(layer, [1, 784]) # image as a 1D signal with depth 1 layer = eddl.MaxPool1D(eddl.ReLu(eddl.Conv1D(layer, 16, [3], [1])), [4], [4]) layer = eddl.MaxPool1D( eddl.ReLu(eddl.Conv1D(layer, 32, [3], [1])), [4], [4], ) layer = eddl.MaxPool1D( eddl.ReLu(eddl.Conv1D(layer, 64, [3], [1])), [4], [4], ) layer = eddl.MaxPool1D( eddl.ReLu(eddl.Conv1D(layer, 64, [3], [1])), [4], [4], ) layer = eddl.Reshape(layer, [-1]) out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.rmsprop(0.01), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(net) x_train = Tensor.load("mnist_trX.bin") y_train = Tensor.load("mnist_trY.bin") x_test = Tensor.load("mnist_tsX.bin") y_test = Tensor.load("mnist_tsY.bin") if args.small: x_train = x_train.select([":6000"]) y_train = y_train.select([":6000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) x_train.div_(255.0) x_test.div_(255.0) eddl.fit(net, [x_train], [y_train], args.batch_size, args.epochs) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): eddl.download_mnist() num_classes = 10 in_ = eddl.Input([784]) layer = in_ layer = eddl.Activation(eddl.Dense(layer, 1024), "relu") layer = eddl.Activation(eddl.Dense(layer, 1024), "relu") layer = eddl.Activation(eddl.Dense(layer, 1024), "relu") out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) acc = CategoricalAccuracy() net.build( eddl.sgd(0.01, 0.9), [eddl.getLoss("soft_cross_entropy")], [acc], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("mnist_trX.bin") y_train = Tensor.load("mnist_trY.bin") x_test = Tensor.load("mnist_tsX.bin") # y_test = Tensor.load("mnist_tsY.bin") x_train.div_(255.0) x_test.div_(255.0) num_samples = x_train.shape[0] num_batches = num_samples // args.batch_size test_samples = x_test.shape[0] test_batches = test_samples // args.batch_size eddl.set_mode(net, TRMODE) for i in range(args.epochs): for j in range(num_batches): print("Epoch %d/%d (batch %d/%d)" % (i + 1, args.epochs, j + 1, num_batches)) indices = np.random.randint(0, num_samples, args.batch_size) eddl.train_batch(net, [x_train], [y_train], indices) for j in range(test_batches): print("Epoch %d/%d (batch %d/%d)" % (i + 1, args.epochs, j + 1, test_batches)) indices = np.random.randint(0, num_samples, args.batch_size) eddl.eval_batch(net, [x_train], [y_train], indices) print("All done")
def main(args): eddl.download_mnist() num_classes = 10 in_ = eddl.Input([28]) layer = in_ layer = eddl.LeakyReLu(eddl.Dense(layer, 32)) layer = eddl.L2(eddl.LSTM(layer, 128), 0.001) ls = layer out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.rmsprop(0.001), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("mnist_trX.bin") y_train = Tensor.load("mnist_trY.bin") x_test = Tensor.load("mnist_tsX.bin") y_test = Tensor.load("mnist_tsY.bin") if args.small: x_train = x_train.select([":6000"]) y_train = y_train.select([":6000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) x_train.reshape_([x_train.shape[0], 28, 28]) x_test.reshape_([x_test.shape[0], 28, 28]) y_train.reshape_([y_train.shape[0], 1, 10]) y_test.reshape_([y_test.shape[0], 1, 10]) x_train.div_(255.0) x_test.div_(255.0) for i in range(args.epochs): eddl.fit(net, [x_train], [y_train], args.batch_size, 1) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) ls_in = eddl.getInput(ls) ls_in.info() ls_out = eddl.getOutput(ls) ls_out.info() print("All done")
def main(args): eddl.download_mnist() num_classes = 10 in_ = eddl.Input([784]) layer = in_ layer = eddl.Reshape(layer, [-1]) layer = eddl.ReLu(eddl.Dense(layer, 1024)) layer = eddl.BatchNormalization(layer, True) layer = eddl.ReLu(eddl.Dense(layer, 1024)) layer = eddl.BatchNormalization(layer, True) layer = eddl.ReLu(eddl.Dense(layer, 1024)) layer = eddl.BatchNormalization(layer, True) out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.rmsprop(0.01), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem), True # initialize weights to random values ) eddl.summary(net) x_train = Tensor.load("mnist_trX.bin") y_train = Tensor.load("mnist_trY.bin") x_test = Tensor.load("mnist_tsX.bin") y_test = Tensor.load("mnist_tsY.bin") if args.small: x_train = x_train.select([":6000"]) y_train = y_train.select([":6000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) x_train.div_(255.0) x_test.div_(255.0) eddl.fit(net, [x_train], [y_train], args.batch_size, args.epochs) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) eddl.save_net_to_onnx_file(net, args.output) print("saved net to", args.output) print("All done")
def main(args): if not os.path.isfile(args.input): raise RuntimeError("input file '%s' not found" % args.input) eddl.download_mnist() net = eddl.import_net_from_onnx_file(args.input) eddl.build( net, eddl.rmsprop(0.01), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem), False # do not initialize weights to random values ) net.resize(args.batch_size) # resize manually since we don't use "fit" eddl.summary(net) x_test = Tensor.load("mnist_tsX.bin") x_test.div_(255.0) sys.stderr.write("forward...\n") eddl.forward(net, [x_test]) sys.stderr.write("forward done\n") sys.stderr.write("lout: %r\n" % (net.lout, )) out = eddl.getOut(net) sys.stderr.write("getOut done\n") sys.stderr.write("out: %r\n" % (out, )) print("All done")
def main(args): eddl.download_mnist() in_ = eddl.Input([784]) layer = in_ layer = eddl.Activation(eddl.Dense(layer, 256), "relu") layer = eddl.Activation(eddl.Dense(layer, 128), "relu") layer = eddl.Activation(eddl.Dense(layer, 64), "relu") layer = eddl.Activation(eddl.Dense(layer, 128), "relu") layer = eddl.Activation(eddl.Dense(layer, 256), "relu") out = eddl.Dense(layer, 784) net = eddl.Model([in_], [out]) eddl.build( net, eddl.sgd(0.001, 0.9), ["mean_squared_error"], ["mean_squared_error"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("mnist_trX.bin") if args.small: x_train = x_train.select([":6000"]) x_train.div_(255.0) eddl.fit(net, [x_train], [x_train], args.batch_size, args.epochs) tout = eddl.predict(net, [x_train]) tout[0].info() print("All done")
def main(args): in_channels = 3 in_height = 224 in_width = 224 print("Importing ONNX model") net = eddl.import_net_from_onnx_file(args.model_fn, [in_channels, in_height, in_width]) # Add a softmax layer to get probabilities directly from the model input_ = net.lin[0] # getLayer(net,"input_layer_name") output = net.lout[0] # getLayer(net,"output_layer_name") new_output = eddl.Softmax(output) net = eddl.Model([input_], [new_output]) eddl.build( net, eddl.adam(0.001), # not used for prediction ["softmax_cross_entropy"], # not used for prediction ["categorical_accuracy"], # not used for prediction eddl.CS_GPU() if args.gpu else eddl.CS_CPU(), False # Disable model initialization, we want to use the ONNX weights ) eddl.summary(net) image = Tensor.load(args.img_fn) image_preprocessed = preprocess_input_resnet34(image, [in_height, in_width]) outputs = eddl.predict(net, [image_preprocessed]) print("Reading class names...") with open(args.classes_fn, "rt") as f: class_names = [_.strip() for _ in f] print("Top 5 predictions:") print(eddl.get_topk_predictions(outputs[0], class_names, 5))
def main(args): eddl.download_mnist() in_ = eddl.Input([784]) layer = in_ layer = eddl.Activation(eddl.Dense(layer, 256), "relu") layer = eddl.Activation(eddl.Dense(layer, 128), "relu") layer = eddl.Activation(eddl.Dense(layer, 64), "relu") layer = eddl.Activation(eddl.Dense(layer, 128), "relu") layer = eddl.Activation(eddl.Dense(layer, 256), "relu") out = eddl.Dense(layer, 784) net = eddl.Model([in_], [out]) mse_loss = MSELoss() mse_metric = MSEMetric() net.build( eddl.sgd(0.001, 0.9), [mse_loss], [mse_metric], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("mnist_trX.bin") x_train.div_(255.0) eddl.fit(net, [x_train], [x_train], args.batch_size, args.epochs) print("All done")
def main(args): eddl.download_imdb_2000() epochs = 2 if args.small else 10 length = 250 embdim = 33 vocsize = 2000 in_ = eddl.Input([1]) # 1 word layer = in_ layer = eddl.RandomUniform(eddl.Embedding(layer, vocsize, 1, embdim), -0.05, 0.05) layer = eddl.GRU(layer, 37) layer = eddl.ReLu(eddl.Dense(layer, 256)) out = eddl.Sigmoid(eddl.Dense(layer, 1)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.adam(0.001), ["cross_entropy"], ["binary_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(net) x_train = Tensor.load("imdb_2000_trX.bin") y_train = Tensor.load("imdb_2000_trY.bin") x_test = Tensor.load("imdb_2000_tsX.bin") y_test = Tensor.load("imdb_2000_tsY.bin") # batch x timesteps x input_dim x_train.reshape_([x_train.shape[0], length, 1]) x_test.reshape_([x_test.shape[0], length, 1]) y_train.reshape_([y_train.shape[0], 1, 1]) y_test.reshape_([y_test.shape[0], 1, 1]) if args.small: x_train = x_train.select([":64", ":", ":"]) y_train = y_train.select([":64", ":", ":"]) x_test = x_test.select([":64", ":", ":"]) y_test = y_test.select([":64", ":", ":"]) for i in range(epochs): eddl.fit(net, [x_train], [y_train], args.batch_size, 1) eddl.evaluate(net, [x_test], [y_test]) print("All done")
def main(args): eddl.download_mnist() num_classes = 10 in_ = eddl.Input([784]) layer = in_ layer = eddl.BatchNormalization( eddl.Activation(eddl.L2(eddl.Dense(layer, 1024), 0.0001), "relu"), True ) layer = eddl.BatchNormalization( eddl.Activation(eddl.L2(eddl.Dense(layer, 1024), 0.0001), "relu"), True ) layer = eddl.BatchNormalization( eddl.Activation(eddl.L2(eddl.Dense(layer, 1024), 0.0001), "relu"), True ) out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) acc = CategoricalAccuracy() net.build( eddl.sgd(0.01, 0.9), [eddl.getLoss("soft_cross_entropy")], [acc], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("mnist_trX.bin") y_train = Tensor.load("mnist_trY.bin") x_test = Tensor.load("mnist_tsX.bin") y_test = Tensor.load("mnist_tsY.bin") x_train.div_(255.0) x_test.div_(255.0) eddl.fit(net, [x_train], [y_train], args.batch_size, args.epochs) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): eddl.download_mnist() num_classes = 10 in_ = eddl.Input([784]) layer = in_ layer = eddl.ReLu(eddl.L2(eddl.Dense(layer, 1024), 0.0001)) layer = eddl.ReLu(eddl.L1(eddl.Dense(layer, 1024), 0.0001)) layer = eddl.ReLu(eddl.L1L2(eddl.Dense(layer, 1024), 0.00001, 0.0001)) out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.sgd(0.01, 0.9), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("mnist_trX.bin") y_train = Tensor.load("mnist_trY.bin") x_test = Tensor.load("mnist_tsX.bin") y_test = Tensor.load("mnist_tsY.bin") if args.small: x_train = x_train.select([":6000"]) y_train = y_train.select([":6000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) x_train.div_(255.0) x_test.div_(255.0) eddl.fit(net, [x_train], [y_train], args.batch_size, args.epochs) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): eddl.download_mnist() in_ = eddl.Input([784]) target = eddl.Reshape(in_, [1, 28, 28]) layer = in_ layer = eddl.Reshape(layer, [1, 28, 28]) layer = eddl.ReLu(eddl.Conv(layer, 8, [3, 3])) layer = eddl.ReLu(eddl.Conv(layer, 16, [3, 3])) layer = eddl.ReLu(eddl.Conv(layer, 8, [3, 3])) out = eddl.Sigmoid(eddl.Conv(layer, 1, [3, 3])) net = eddl.Model([in_], []) eddl.build( net, eddl.adam(0.001), [], [], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(net) x_train = Tensor.load("mnist_trX.bin") if args.small: x_train = x_train.select([":6000"]) x_train.div_(255.0) mse = eddl.newloss(mse_loss, [out, target], "mse_loss") dicei = eddl.newloss(dice_loss_img, [out, target], "dice_loss_img") dicep = eddl.newloss(dice_loss_pixel, [out, target], "dice_loss_pixel") batch = Tensor([args.batch_size, 784]) num_batches = x_train.shape[0] // args.batch_size for i in range(args.epochs): print("Epoch %d/%d (%d batches)" % (i + 1, args.epochs, num_batches)) diceploss = 0.0 diceiloss = 0.0 mseloss = 0 for j in range(num_batches): print("Batch %d " % j, end="", flush=True) eddl.next_batch([x_train], [batch]) eddl.zeroGrads(net) eddl.forward(net, [batch]) diceploss += eddl.compute_loss(dicep) / args.batch_size print("diceploss = %.6f " % (diceploss / (j + 1)), end="") diceiloss += eddl.compute_loss(dicei) / args.batch_size print("diceiloss = %.6f " % (diceiloss / (j + 1)), end="") mseloss += eddl.compute_loss(mse) / args.batch_size print("mseloss = %.6f\r" % (mseloss / (j + 1)), end="") eddl.optimize(dicep) eddl.update(net) print() print("All done")
def main(args): eddl.download_cifar10() num_classes = 10 in_ = eddl.Input([3, 32, 32]) layer = in_ layer = eddl.RandomHorizontalFlip(layer) layer = eddl.RandomCropScale(layer, [0.8, 1.0]) layer = eddl.RandomCutout(layer, [0.1, 0.5], [0.1, 0.5]) layer = eddl.MaxPool(eddl.ReLu(eddl.BatchNormalization( eddl.HeUniform(eddl.Conv(layer, 32, [3, 3], [1, 1], "same", False)), True)), [2, 2]) layer = eddl.MaxPool(eddl.ReLu(eddl.BatchNormalization( eddl.HeUniform(eddl.Conv(layer, 64, [3, 3], [1, 1], "same", False)), True)), [2, 2]) layer = eddl.MaxPool(eddl.ReLu(eddl.BatchNormalization( eddl.HeUniform(eddl.Conv(layer, 128, [3, 3], [1, 1], "same", False)), True)), [2, 2]) layer = eddl.MaxPool(eddl.ReLu(eddl.BatchNormalization( eddl.HeUniform(eddl.Conv(layer, 256, [3, 3], [1, 1], "same", False)), True)), [2, 2]) layer = eddl.Reshape(layer, [-1]) layer = eddl.Activation(eddl.BatchNormalization( eddl.Dense(layer, 128), True ), "relu") out = eddl.Softmax(eddl.BatchNormalization( eddl.Dense(layer, num_classes), True )) net = eddl.Model([in_], [out]) eddl.build( net, eddl.adam(0.001), ["softmax_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(net) eddl.plot(net, "model.pdf") x_train = Tensor.load("cifar_trX.bin") y_train = Tensor.load("cifar_trY.bin") x_train.div_(255.0) x_test = Tensor.load("cifar_tsX.bin") y_test = Tensor.load("cifar_tsY.bin") x_test.div_(255.0) if args.small: x_train = x_train.select([":5000"]) y_train = y_train.select([":5000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) for i in range(args.epochs): eddl.fit(net, [x_train], [y_train], args.batch_size, 1) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) eddl.setlr(net, [0.0001]) for i in range(args.epochs): eddl.fit(net, [x_train], [y_train], args.batch_size, 1) eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): eddl.download_mnist() num_classes = 10 in_ = eddl.Input([784]) layer = in_ layer = eddl.Reshape(layer, [-1]) layer = eddl.ReLu(eddl.Dense(layer, 1024)) layer = eddl.ReLu(eddl.Dense(layer, 1024)) layer = eddl.ReLu(eddl.Dense(layer, 1024)) out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.rmsprop(0.01), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem), True # initialize weights to random values ) serialized_net = eddl.serialize_net_to_onnx_string(net, False) eddl.summary(net) x_train = Tensor.load("mnist_trX.bin") y_train = Tensor.load("mnist_trY.bin") x_test = Tensor.load("mnist_tsX.bin") y_test = Tensor.load("mnist_tsY.bin") if args.small: x_train = x_train.select([":6000"]) y_train = y_train.select([":6000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) x_train.div_(255.0) x_test.div_(255.0) eddl.fit(net, [x_train], [y_train], args.batch_size, args.epochs) print("evaluating before import") eddl.evaluate(net, [x_test], [y_test], bs=args.batch_size) imported_net = eddl.import_net_from_onnx_string(serialized_net) eddl.build( imported_net, eddl.rmsprop(0.01), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem), False # do not initialize weights to random values ) eddl.summary(imported_net) print("net layers:", len(net.layers)) print("imported_net layers:", len(imported_net.layers)) print("evaluating imported net") eddl.evaluate(imported_net, [x_test], [y_test], bs=args.batch_size) print("All done")
def main(args): eddl.download_eutrans() epochs = 1 if args.small else 5 ilength = 30 olength = 30 invs = 687 outvs = 514 embedding = 64 # Encoder in_ = eddl.Input([1]) # 1 word layer = in_ lE = eddl.RandomUniform( eddl.Embedding(layer, invs, 1, embedding, True), -0.05, 0.05 ) enc = eddl.LSTM(lE, 128, True) cps = eddl.GetStates(enc) # Decoder ldin = eddl.Input([outvs]) ld = eddl.ReduceArgMax(ldin, [0]) ld = eddl.RandomUniform( eddl.Embedding(ld, outvs, 1, embedding), -0.05, 0.05 ) layer = eddl.LSTM([ld, cps], 128) out = eddl.Softmax(eddl.Dense(layer, outvs)) eddl.setDecoder(ldin) net = eddl.Model([in_], [out]) # Build model eddl.build( net, eddl.adam(0.01), ["softmax_cross_entropy"], ["accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(net) # Load dataset x_train = Tensor.load("eutrans_trX.bin") y_train = Tensor.load("eutrans_trY.bin") y_train = Tensor.onehot(y_train, outvs) # batch x timesteps x input_dim x_train.reshape_([x_train.shape[0], ilength, 1]) # batch x timesteps x ouput_dim y_train.reshape_([y_train.shape[0], olength, outvs]) x_test = Tensor.load("eutrans_tsX.bin") y_test = Tensor.load("eutrans_tsY.bin") y_test = Tensor.onehot(y_test, outvs) # batch x timesteps x input_dim x_test.reshape_([x_test.shape[0], ilength, 1]) # batch x timesteps x ouput_dim y_test.reshape_([y_test.shape[0], olength, outvs]) if args.small: sel = [f":{3 * args.batch_size}", ":", ":"] x_train = x_train.select(sel) y_train = y_train.select(sel) x_test = x_test.select(sel) y_test = y_test.select(sel) # Train model ybatch = Tensor([args.batch_size, olength, outvs]) eddl.next_batch([y_train], [ybatch]) for i in range(epochs): eddl.fit(net, [x_train], [y_train], args.batch_size, 1) print("All done")
def main(args): eddl.download_flickr() epochs = 2 if args.small else 50 olength = 20 outvs = 2000 embdim = 32 # True: remove last layers and set new top = flatten # new input_size: [3, 256, 256] (from [224, 224, 3]) net = eddl.download_resnet18(True, [3, 256, 256]) lreshape = eddl.getLayer(net, "top") # create a new model from input output image_in = eddl.getLayer(net, "input") # Decoder ldecin = eddl.Input([outvs]) ldec = eddl.ReduceArgMax(ldecin, [0]) ldec = eddl.RandomUniform(eddl.Embedding(ldec, outvs, 1, embdim, True), -0.05, 0.05) ldec = eddl.Concat([ldec, lreshape]) layer = eddl.LSTM(ldec, 512, True) out = eddl.Softmax(eddl.Dense(layer, outvs)) eddl.setDecoder(ldecin) net = eddl.Model([image_in], [out]) # Build model eddl.build( net, eddl.adam(0.01), ["softmax_cross_entropy"], ["accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(net) # Load dataset x_train = Tensor.load("flickr_trX.bin", "bin") y_train = Tensor.load("flickr_trY.bin", "bin") if args.small: x_train = x_train.select([f"0:{2 * args.batch_size}", ":", ":", ":"]) y_train = y_train.select([f"0:{2 * args.batch_size}", ":"]) xtrain = Tensor.permute(x_train, [0, 3, 1, 2]) y_train = Tensor.onehot(y_train, outvs) # batch x timesteps x input_dim y_train.reshape_([y_train.shape[0], olength, outvs]) eddl.fit(net, [xtrain], [y_train], args.batch_size, epochs) eddl.save(net, "img2text.bin", "bin") print("\n === INFERENCE ===\n") # Get all the reshapes of the images. Only use the CNN timage = Tensor([x_train.shape[0], 512]) # images reshape cnn = eddl.Model([image_in], [lreshape]) eddl.build( cnn, eddl.adam(0.001), # not relevant ["mse"], # not relevant ["mse"], # not relevant eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(cnn) # forward images xbatch = Tensor([args.batch_size, 3, 256, 256]) # numbatches = x_train.shape[0] / args.batch_size j = 0 eddl.next_batch([x_train], [xbatch]) eddl.forward(cnn, [xbatch]) ybatch = eddl.getOutput(lreshape) sample = str(j * args.batch_size) + ":" + str((j + 1) * args.batch_size) timage.set_select([sample, ":"], ybatch) # Create Decoder non recurrent for n-best ldecin = eddl.Input([outvs]) image = eddl.Input([512]) lstate = eddl.States([2, 512]) ldec = eddl.ReduceArgMax(ldecin, [0]) ldec = eddl.RandomUniform(eddl.Embedding(ldec, outvs, 1, embdim), -0.05, 0.05) ldec = eddl.Concat([ldec, image]) lstm = eddl.LSTM([ldec, lstate], 512, True) lstm.isrecurrent = False # Important out = eddl.Softmax(eddl.Dense(lstm, outvs)) decoder = eddl.Model([ldecin, image, lstate], [out]) eddl.build( decoder, eddl.adam(0.001), # not relevant ["softmax_cross_entropy"], # not relevant ["accuracy"], # not relevant eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(decoder) # Copy params from trained net eddl.copyParam(eddl.getLayer(net, "LSTM1"), eddl.getLayer(decoder, "LSTM2")) eddl.copyParam(eddl.getLayer(net, "dense1"), eddl.getLayer(decoder, "dense2")) eddl.copyParam(eddl.getLayer(net, "embedding1"), eddl.getLayer(decoder, "embedding2")) # N-best for sample s s = 1 if args.small else 100 # sample 100 # three input tensors with batch_size = 1 (one sentence) treshape = timage.select([str(s), ":"]) text = y_train.select([str(s), ":", ":"]) # 1 x olength x outvs for j in range(olength): print(f"Word: {j}") word = None if j == 0: word = Tensor.zeros([1, outvs]) else: word = text.select(["0", str(j - 1), ":"]) word.reshape_([1, outvs]) # batch = 1 treshape.reshape_([1, 512]) # batch = 1 state = Tensor.zeros([1, 2, 512]) # batch = 1 input_ = [word, treshape, state] eddl.forward(decoder, input_) # outword = eddl.getOutput(out) vstates = eddl.getStates(lstm) for i in range(len(vstates)): vstates[i].reshape_([1, 1, 512]) state.set_select([":", str(i), ":"], vstates[i]) print("All done")
def main(args): eddl.download_mnist() num_classes = 10 in_ = eddl.Input([784]) layer = in_ layer = eddl.ReLu(eddl.Dense(layer, 1024)) layer = eddl.ReLu(eddl.Dense(layer, 1024)) layer = eddl.ReLu(eddl.Dense(layer, 1024)) out = eddl.Softmax(eddl.Dense(layer, num_classes)) net = eddl.Model([in_], [out]) eddl.build( net, eddl.sgd(0.001, 0.9), ["softmax_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem)) eddl.summary(net) eddl.plot(net, "model.pdf") eddl.setlogfile(net, "mnist") x_train = Tensor.load("mnist_trX.bin") y_train = Tensor.load("mnist_trY.bin") x_test = Tensor.load("mnist_tsX.bin") y_test = Tensor.load("mnist_tsY.bin") if args.small: x_train = x_train.select([":6000"]) y_train = y_train.select([":6000"]) x_test = x_test.select([":1000"]) y_test = y_test.select([":1000"]) x_train.div_(255.0) x_test.div_(255.0) s = x_train.shape num_batches = s[0] // args.batch_size for i in range(args.epochs): eddl.reset_loss(net) print("Epoch %d/%d (%d batches)" % (i + 1, args.epochs, num_batches)) for j in range(num_batches): indices = np.random.randint(0, s[0], args.batch_size) eddl.train_batch(net, [x_train], [y_train], indices) losses1 = eddl.get_losses(net) metrics1 = eddl.get_metrics(net) for l, m in zip(losses1, metrics1): print("Loss: %.6f\tMetric: %.6f" % (l, m)) s = x_test.shape num_batches = s[0] // args.batch_size for j in range(num_batches): indices = np.arange(j * args.batch_size, j * args.batch_size + args.batch_size) eddl.eval_batch(net, [x_test], [y_test], indices) losses2 = eddl.get_losses(net) metrics2 = eddl.get_metrics(net) for l, m in zip(losses2, metrics2): print("Loss: %.6f\tMetric: %.6f" % (l, m)) last_batch_size = s[0] % args.batch_size if last_batch_size: indices = np.arange(j * args.batch_size, j * args.batch_size + args.batch_size) eddl.eval_batch(net, [x_test], [y_test], indices) losses3 = eddl.get_losses(net) metrics3 = eddl.get_metrics(net) for l, m in zip(losses3, metrics3): print("Loss: %.6f\tMetric: %.6f" % (l, m)) print("All done")
if (bn): l = eddl.BatchNormalization(l, 0.99, 0.001, True, "") l = eddl.ReLu(l) out = eddl.Softmax(initializer(eddl.Dense(l, num_classes))) net = eddl.Model([inp], [out]) eddl.plot(net, "model.pdf") eddl.build(net, eddl.adam(0.00001), ["soft_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU() if gpu else eddl.CS_CPU()) eddl.summary(net) x_train = Tensor.load("cifar_trX.bin") y_train = Tensor.load("cifar_trY.bin") x_train.div_(255) x_test = Tensor.load("cifar_tsX.bin") y_test = Tensor.load("cifar_tsY.bin") x_test.div_(255) from time import time import numpy as np tiempos = [] for i in range(epochs): s = time() print(i) res = eddl.fit(net, [x_train], [y_train], batch_size, 1) tiempos.append(time() - s)
def main(args): freeze_epochs = 2 unfreeze_epochs = 5 num_classes = 10 # 10 labels in cifar10 eddl.download_cifar10() eddl.download_model("resnet18.onnx", "re7jodd12srksd7") net = eddl.import_net_from_onnx_file("resnet18.onnx", [3, 32, 32], DEV_CPU) names = [_.name for _ in net.layers] # Remove dense output layer eddl.removeLayer(net, "resnetv15_dense0_fwd") # Get last layer to connect the new dense layer = eddl.getLayer(net, "flatten_170") out = eddl.Softmax(eddl.Dense(layer, num_classes, True, "new_dense")) # Get input layer in_ = eddl.getLayer(net, "data") # Create a new model net = eddl.Model([in_], [out]) eddl.build( net, eddl.adam(0.0001), ["softmax_cross_entropy"], ["categorical_accuracy"], eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem), False # do not initialize weights to random values ) eddl.summary(net) # Force initialization of new layers eddl.initializeLayer(net, "new_dense") x_train = Tensor.load("cifar_trX.bin") y_train = Tensor.load("cifar_trY.bin") x_test = Tensor.load("cifar_tsX.bin") y_test = Tensor.load("cifar_tsY.bin") if args.small: sel = [f":{2 * args.batch_size}"] x_train = x_train.select(sel) y_train = y_train.select(sel) x_test = x_test.select(sel) y_test = y_test.select(sel) x_train.div_(255.0) x_test.div_(255.0) # Freeze pretrained weights for n in names: eddl.setTrainable(net, n, False) # Train new layers eddl.fit(net, [x_train], [y_train], args.batch_size, freeze_epochs) # Unfreeze weights for n in names: eddl.setTrainable(net, n, True) # Train all layers eddl.fit(net, [x_train], [y_train], args.batch_size, unfreeze_epochs) # Evaluate eddl.evaluate(net, [x_test], [y_test], args.batch_size) print("All done")
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os from urllib.request import urlretrieve import numpy as np from pyeddl.tensor import Tensor # Convert array to tensor and save to "bin" format a = np.arange(6).reshape([2, 3]).astype(np.float32) print(a) t = Tensor.fromarray(a) t.save("./a.bin", "bin") t1 = Tensor.load("a.bin", "bin") a1 = t1.getdata() print(a1) print() # Read numpy data and convert to tensors FNAME = "mnist.npz" LOC = "https://storage.googleapis.com/tensorflow/tf-keras-datasets" if not os.path.exists(FNAME): fname, _ = urlretrieve("%s/%s" % (LOC, FNAME), FNAME) print("Downloaded", fname) print("loading", FNAME) with np.load(FNAME) as f: x_train, y_train = f['x_train'], f['y_train'] x_test, y_test = f['x_test'], f['y_test']
def main(args): eddl.download_drive() in_1 = eddl.Input([3, 584, 584]) in_2 = eddl.Input([1, 584, 584]) layer = eddl.Concat([in_1, in_2]) layer = eddl.RandomCropScale(layer, [0.9, 1.0]) layer = eddl.CenteredCrop(layer, [512, 512]) img = eddl.Select(layer, ["0:3"]) mask = eddl.Select(layer, ["3"]) # DA net danet = eddl.Model([in_1, in_2], []) eddl.build(danet) if args.gpu: eddl.toGPU(danet, mem="low_mem") eddl.summary(danet) # SegNet in_ = eddl.Input([3, 512, 512]) out = eddl.Sigmoid(UNetWithPadding(in_)) segnet = eddl.Model([in_], [out]) eddl.build( segnet, eddl.adam(0.00001), # Optimizer ["mse"], # Losses ["mse"], # Metrics eddl.CS_GPU(mem=args.mem) if args.gpu else eddl.CS_CPU(mem=args.mem) ) eddl.summary(segnet) print("Reading training data") # x_train_f = Tensor.fromarray(np.load("drive_trX.npy").astype(np.float32)) x_train_f = Tensor.load("drive_trX.bin") x_train = x_train_f.permute([0, 3, 1, 2]) x_train.info() x_train.div_(255.0) print("Reading test data") # y_train = Tensor.fromarray(np.load("drive_trY.npy").astype(np.float32)) y_train = Tensor.load("drive_trY.bin") y_train.info() y_train.reshape_([20, 1, 584, 584]) y_train.div_(255.0) xbatch = Tensor([args.batch_size, 3, 584, 584]) ybatch = Tensor([args.batch_size, 1, 584, 584]) print("Starting training") for i in range(args.epochs): print("\nEpoch %d/%d" % (i + 1, args.epochs)) eddl.reset_loss(segnet) for j in range(args.num_batches): eddl.next_batch([x_train, y_train], [xbatch, ybatch]) # DA net eddl.forward(danet, [xbatch, ybatch]) xbatch_da = eddl.getOutput(img) ybatch_da = eddl.getOutput(mask) # SegNet eddl.train_batch(segnet, [xbatch_da], [ybatch_da]) eddl.print_loss(segnet, j) if i == args.epochs - 1: yout = eddl.getOutput(out).select(["0"]) yout.save("./out_%d.jpg" % j) print() print("All done")