예제 #1
0
def _load_model(folder, model, weights_only=True):
    latest = os.path.join(folder, "latest")
    if model is None and weights_only:
        with open(os.path.join(folder, 'model.yaml'), 'r') as yaml_file:
            loaded_model_yaml = yaml_file.read()
        model = model_from_yaml(loaded_model_yaml, custom_objects={'tf': tf})
        print('Model loaded from %s' % os.path.join(folder, 'model.yaml'))
    if os.path.isfile(latest):
        with open(latest, 'r') as f:
            filename = f.readlines()[0]
        epoch = filename.split('_')[1]
        # If model and weights were stored separately
        if weights_only:
            try:
                model.load_weights(os.path.join(folder, '%s.h5' % filename))
            except:
                print('Single gpu loading failed, try with multi-gpu loading...')
                from tensorflow.python.keras.utils import multi_gpu_model
                multi_model = multi_gpu_model(model, gpus=len(os.environ["CUDA_VISIBLE_DEVICES"].split(',')) - 1)
                multi_model.load_weights(os.path.join(folder, '%s.h5' % filename))
                model = multi_model.layers[-2]
            print('Weights loaded from %s' % os.path.join(folder, '%s.h5' % filename))
        elif not weights_only:
            model = load_model(os.path.join(folder, '%s.h5' % filename), compile=False)
            print('Model loaded from %s' % os.path.join(folder, '%s.h5' % filename))
        return model, int(epoch)
    return model, 0
예제 #2
0
def load_model(input_model_path, input_json_path=None, input_yaml_path=None):
    if not Path(input_model_path).exists():
        raise FileNotFoundError(
            'Model file `{}` does not exist.'.format(input_model_path))
    try:
        model = keras.models.load_model(input_model_path)
        if FLAGS.is_tiny:
            model = tiny_yolo_body(Input(shape=(None, None, 3)), 3,
                                   FLAGS.num_class)
        else:
            model = yolo_body(Input(shape=(None, None, 3)), 3, FLAGS.num_class)

        model.load_weights('input_model_path')
        return model
    except FileNotFoundError as err:
        logging.error('Input mode file (%s) does not exist.',
                      FLAGS.input_model)
        raise err
    except ValueError as wrong_file_err:
        if input_json_path:
            if not Path(input_json_path).exists():
                raise FileNotFoundError(
                    'Model description json file `{}` does not exist.'.format(
                        input_json_path))
            try:
                model = model_from_json(open(str(input_json_path)).read())
                model.load_weights(input_model_path)
                return model
            except Exception as err:
                logging.error("Couldn't load model from json.")
                raise err
        elif input_yaml_path:
            if not Path(input_yaml_path).exists():
                raise FileNotFoundError(
                    'Model description yaml file `{}` does not exist.'.format(
                        input_yaml_path))
            try:
                model = model_from_yaml(open(str(input_yaml_path)).read())
                model.load_weights(input_model_path)
                return model
            except Exception as err:
                logging.error("Couldn't load model from yaml.")
                raise err
        else:
            logging.error(
                'Input file specified only holds the weights, and not '
                'the model definition. Save the model using '
                'model.save(filename.h5) which will contain the network '
                'architecture as well as its weights. '
                'If the model is saved using the '
                'model.save_weights(filename) function, either '
                'input_model_json or input_model_yaml flags should be set to '
                'to import the network architecture prior to loading the '
                'weights. \n'
                'Check the keras documentation for more details '
                '(https://keras.io/getting-started/faq/)')
            raise wrong_file_err
예제 #3
0
 def load_generator(self, path_yaml, path_weight):
     # load YAML and create model
     yaml_file = open(path_yaml, 'r')
     loaded_model_yaml = yaml_file.read()
     yaml_file.close()
     loaded_model = model_from_yaml(loaded_model_yaml)
     # load weights into new model
     loaded_model.load_weights(path_weight)
     print("Loaded model from disk")
     return loaded_model
예제 #4
0
파일: main.py 프로젝트: A1-PONATA/public
    def load_model(path):
        yamlPath = path[0]
        h5Path = path[1]
        yaml_file1 = open(yamlPath, 'r')
        loaded_model_yaml = yaml_file1.read()
        yaml_file1.close()
        model = model_from_yaml(loaded_model_yaml)

        # load weights into new model
        model.load_weights(h5Path)
        model._make_predict_function()

        return model
예제 #5
0
    def __init__(self, descriptor='jtvae'):
        self.descriptor = descriptor
        self.loaded_model = None
        self.model = None

        if self.descriptor == 'ecfp_autoencoder':
            yaml_file = open('Models/autoencoder_optedilmemis.yaml', 'r')
            loaded_model_yaml = yaml_file.read()
            yaml_file.close()
            self.loaded_model = model_from_yaml(loaded_model_yaml)
            # load weights into new model
            self.loaded_model.load_weights(
                "Models/autoencoder_optedilmemis.h5")

        elif self.descriptor == 'jtvae':
            lg = rdkit.RDLogger.logger()
            lg.setLevel(rdkit.RDLogger.CRITICAL)

            # Jupyter notebookta hata verdiği için parser kapatıldı.
            # parser = OptionParser()
            # parser.add_option("-t", "--test", dest="test_path")
            # parser.add_option("-v", "--vocab", dest="vocab_path")
            # parser.add_option("-m", "--model", dest="model_path")
            # parser.add_option("-w", "--hidden", dest="hidden_size", default=450)
            # parser.add_option("-l", "--latent", dest="latent_size", default=56)
            # parser.add_option("-d", "--depth", dest="depth", default=3)
            # parser.add_option("-e", "--stereo", dest="stereo", default=1)
            # opts, args = parser.parse_args()

            vocab = [
                x.strip("\r\n ")
                for x in open("unique_canonical_train_vocab.txt")
            ]
            vocab = Vocab(vocab)

            hidden_size = 450
            latent_size = 56
            depth = 3
            stereo = True

            model = JTNNVAE(vocab,
                            hidden_size,
                            latent_size,
                            depth,
                            stereo=stereo)
            model.load_state_dict(torch.load("Models/model.iter-9-6000"))
            # opts.model_path #MPNVAE-h450-L56-d3-beta0.001/model.iter-4

            self.model = model.cuda()
예제 #6
0
        q = queue.Queue(BUF_SIZE)
        ir = queue.Queue(BUF_SIZE)

        kit = ServoKit(channels=16)
        #gamepad =InputDevice('/dev/input/event4')

        # target = ['Forward', 'Right', 'Left']
        # labels ={'Forward':0, 'Right':1, 'Left':2}

        # Initialize Donkey car,..
        kit.continuous_servo[0].throttle = 0
        kit.servo[1].angle = 107

        # Initialize Model...
        yaml_file = open(
            '/home/ponata/A1-PONATA/Hayoung/lane_model_test/lane_model_v2.yaml',
            'r')
        loaded_model_yaml = yaml_file.read()
        yaml_file.close()
        lane_model = model_from_yaml(loaded_model_yaml)

        # load weights into new model
        lane_model.load_weights(
            "/home/ponata/A1-PONATA/Hayoung/lane_model_test/lane_model_v2.h5")
        lane_model._make_predict_function()

        print("Initail Settings are done.\n")

        # START THREAD
        while True:
            main()
        output_row[labels.index(docs_y[x])] = 1

        training.append(bag)
        output.append(output_row)

    training = numpy.array(training)
    output = numpy.array(output)

    with open("chatbot.pickle", "wb") as file:
        pickle.dump((words, labels, training, output), file)

try:
    yaml_file = open('chatbotmodel.yaml', 'r')
    loaded_model_yaml = yaml_file.read()
    yaml_file.close()
    myChatModel = model_from_yaml(loaded_model_yaml)
    myChatModel.load_weights("chatbotmodel.h5")
    print("Loaded model from disk")

except:
    # Make our neural network
    myChatModel = Sequential()
    myChatModel.add(Dense(8, input_shape=[len(words)], activation='relu'))
    myChatModel.add(Dense(len(labels), activation='softmax'))

    # optimize the model
    myChatModel.compile(loss='categorical_crossentropy',
                        optimizer='adam',
                        metrics=['accuracy'])

    # train the model
from tensorflow.python.keras.models import Model, model_from_yaml
from tensorflow.python.keras.layers import Input
from tensorflow.python.keras.datasets import mnist

import matplotlib.pyplot as plt
import sys

encoding_dim = 32

if len(sys.argv) < 2:
    print("Error: No model file provided")
    exit()

model_name = sys.argv[1]
h_model_yaml = open(model_name + ".yaml", "r")
autoencoder = model_from_yaml(h_model_yaml.read())
h_model_yaml.close()
autoencoder.load_weights(model_name + ".h5")

print("No.of layers: %d" % len(autoencoder.layers))

# Encoder
encoder = Model(autoencoder.layers[0].input, autoencoder.layers[1].output)
# # Decoder
encoded_input = Input(shape=(encoding_dim, ))
decoder_layer = autoencoder.layers[-1]
decoder = Model(encoded_input, decoder_layer(encoded_input))

autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

(x_train, _), (x_test, _) = mnist.load_data()