當前位置: 首頁>>代碼示例>>Python>>正文


Python models.load_model方法代碼示例

本文整理匯總了Python中tensorflow.keras.models.load_model方法的典型用法代碼示例。如果您正苦於以下問題:Python models.load_model方法的具體用法?Python models.load_model怎麽用?Python models.load_model使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在tensorflow.keras.models的用法示例。


在下文中一共展示了models.load_model方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def __init__(self):
        config = configparser.ConfigParser()
        config.read('./config/config.ini')

        self.log_Image = ''
        self.LogNames = ''


        if config.has_option('Analog_Counter', 'LogImageLocation'):
            self.log_Image = config['Analog_Counter']['LogImageLocation']
            if config.has_option('Analog_Counter', 'LogNames'):
                zw_LogNames = config.get('Analog_Counter', 'LogNames').split(',')
                self.LogNames = []
                for nm in zw_LogNames:
                      self.LogNames.append(nm.strip())
            else:
                self.LogNames = ''
        else:
            self.log_Image = ''

        self.model_file = config['Analog_Counter']['Modelfile']

        self.CheckAndLoadDefaultConfig()

        self.model = load_model(self.model_file) 
開發者ID:jomjol,項目名稱:water-meter-system-complete,代碼行數:27,代碼來源:ReadAnalogNeedleClass.py

示例2: _load_model

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def _load_model(self, name: str, reload: bool = False) -> Model:
        if name in self.models and not reload:
            return self.models[name]

        model_dir = os.path.join(self._models_dir, name)
        assert os.path.isdir(model_dir), 'The model {} does not exist'.format(name)
        model = load_model(model_dir)
        model.input_labels = []
        model.output_labels = []

        labels_file = os.path.join(model_dir, 'labels.json')
        if os.path.isfile(labels_file):
            with open(labels_file, 'r') as f:
                labels = json.load(f)
            if 'input' in labels:
                model.input_labels = labels['input']
            if 'output' in labels:
                model.output_labels = labels['output']

        return model 
開發者ID:BlackLight,項目名稱:platypush,代碼行數:22,代碼來源:__init__.py

示例3: load_disc_gen

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def load_disc_gen():
    """ load models for training. Separate from 'load_model'.
    Returns Discriminator, Generator"""
    home_dir = get_directory()
    generators = glob.glob(os.path.join(home_dir, "models/checkpoints/generator-*.h5"))
    discriminators = glob.glob(
        os.path.join(home_dir, "models/checkpoints/discriminator-*.h5")
    )
    try:
        gen_model_file = max(generators, key=os.path.getctime)
        gen_model = load_model(gen_model_file)
    except ValueError:
        gen_model = generator()
    try:
        disc_model_file = max(discriminators, key=os.path.getctime)
        disc_model = load_model(disc_model_file)
    except ValueError:
        disc_model = discriminator()

    return disc_model, gen_model 
開發者ID:intel,項目名稱:stacks-usecase,代碼行數:22,代碼來源:main.py

示例4: infer

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def infer(img):
    """inference function, accepts an abstract image file return generated image"""
    home_dir = get_directory()
    # load model
    backend.clear_session()
    gen_model = load_model(home_dir + "/models/generator_model.h5", compile=False)
    img = np.array(Image.open(img))
    img = norm_data([img])
    s_time = time.time()
    result = gen_model.predict(img[0].reshape(1, 256, 256, 3))
    f_time = time.time()
    logger.info(
        "\033[92m"
        + "[INFO] "
        + "\033[0m"
        + "Inference done in: {:2.3f} seconds".format(f_time - s_time)
    )
    # transform result from normalized to absolute values and convert to image object
    result = Image.fromarray(reverse_norm(result[0]), "RGB")
    # for debugging, uncomment the line below to inspect the generated image locally
    # result.save("generted_img.jpg", "JPEG")
    # convert image to bytes object to send it to the client
    binary_buffer = io.BytesIO()
    result.save(binary_buffer, format="JPEG")
    return b2a_base64(binary_buffer.getvalue()) 
開發者ID:intel,項目名稱:stacks-usecase,代碼行數:27,代碼來源:infer.py

示例5: load_unet

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def load_unet(checkpoint=False):
    """
    Return  unet model. Only for use in local training.
    checkpoint: True to return the latest ckeckpoint in models/,
        False to return a model named 'unet.h5' in models/
    """
    home_dir = get_directory()
    unet_names = glob.glob(os.path.join(home_dir, "models/checkpoints/unet-*.h5"))
    if checkpoint:
        try:
            unet_file = max(unet_names, key=os.path.getctime)
            unet_model = load_model(unet_file)
        except ValueError:
            print("Could not load checkpoint. Returning new model instead.")
            unet_model = unet_model()
    else:
        try:
            unet_model = load_model(os.path.join(home_dir, "models/unet.h5"))
        except ValueError:
            print("Could not load from 'models/unet.h5'. Returning new model instead.")
            unet_model = unet_model()
    return unet_model 
開發者ID:intel,項目名稱:stacks-usecase,代碼行數:24,代碼來源:helper.py

示例6: from_file

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def from_file(cls, filename: str) -> 'GraphModel':
        """
        Class method to load model from
            filename for keras model
            filename.json for additional converters

        Args:
            filename: (str) model file name

        Returns
            GraphModel
        """
        configs = loadfn(filename + '.json')
        from tensorflow.keras.models import load_model
        from megnet.layers import _CUSTOM_OBJECTS
        model = load_model(filename, custom_objects=_CUSTOM_OBJECTS)
        configs.update({'model': model})
        return GraphModel(**configs) 
開發者ID:materialsvirtuallab,項目名稱:megnet,代碼行數:20,代碼來源:base.py

示例7: validate_yolo_model

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def validate_yolo_model(model_path, image_file, anchors, class_names, model_image_size, loop_count):

    custom_object_dict = get_custom_objects()
    model = load_model(model_path, compile=False, custom_objects=custom_object_dict)

    img = Image.open(image_file)
    image = np.array(img, dtype='uint8')
    image_data = preprocess_image(img, model_image_size)
    #origin image shape, in (height, width) format
    image_shape = tuple(reversed(img.size))

    # predict once first to bypass the model building time
    model.predict([image_data])

    start = time.time()
    for i in range(loop_count):
        prediction = model.predict([image_data])
    end = time.time()
    print("Average Inference time: {:.8f}ms".format((end - start) * 1000 /loop_count))
    if type(prediction) is not list:
        prediction = [prediction]

    prediction.sort(key=lambda x: len(x[0]))
    handle_prediction(prediction, image_file, image, image_shape, anchors, class_names, model_image_size)
    return 
開發者ID:david8862,項目名稱:keras-YOLOv3-model-set,代碼行數:27,代碼來源:validate_yolo.py

示例8: onnx_convert_with_savedmodel

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def onnx_convert_with_savedmodel(keras_model_file, output_file, op_set):
    # only available for TF 2.x
    if not tf.__version__.startswith('2'):
        raise ValueError('savedmodel convert only support in TF 2.x env')

    custom_object_dict = get_custom_objects()
    model = load_model(keras_model_file, custom_objects=custom_object_dict)

    # export to saved model
    model.save('tmp_savedmodel', save_format='tf')

    # use tf2onnx to convert to onnx model
    cmd = 'python -m tf2onnx.convert --saved-model tmp_savedmodel --output {} --opset {}'.format(output_file, op_set)
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()

    # clean saved model
    shutil.rmtree('tmp_savedmodel') 
開發者ID:david8862,項目名稱:keras-YOLOv3-model-set,代碼行數:20,代碼來源:keras_to_onnx.py

示例9: predict

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def predict(self, input_table_file, generic_opinion_terms):
        """Predict classification class according to model.

        Args:
           input_table_file: feature(X) and labels(Y) table file
           generic_opinion_terms: generic opinion terms file name

        Returns:
            final_concat_opinion_lex: reranked_lex conctenated with generic lex
        """
        x, terms, polarities = self.load_terms_and_generate_features(input_table_file)

        model = load_model(self.rerank_model_path)
        reranked_lexicon = model.predict(x, verbose=0)

        reranked_lex = {}
        for i, prediction in enumerate(reranked_lexicon):
            if not np.isnan(prediction[0]) and prediction[0] > self.PREDICTION_THRESHOLD:
                reranked_lex[terms[i]] = (prediction[0], polarities[terms[i]])

        final_concat_opinion_lex = self._generate_concat_reranked_lex(
            reranked_lex, generic_opinion_terms
        )
        return final_concat_opinion_lex 
開發者ID:NervanaSystems,項目名稱:nlp-architect,代碼行數:26,代碼來源:rerank_terms.py

示例10: __setstate__

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def __setstate__(self, state):
        if "model" in state:
            with h5py.File(state["model"], compression="lzf", mode="r") as h5:
                state["model"] = load_model(h5, compile=False)
            if "history" in state:
                state["model"].__dict__["history"] = state.pop("history")
        self.__dict__ = state
        return self 
開發者ID:equinor,項目名稱:gordo,代碼行數:10,代碼來源:models.py

示例11: _load_model_by_path

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def _load_model_by_path(self, model_path, weights_only=True):
        try:
            if weights_only:
                model = self._build_model()
                model.load_weights(model_path)
            else:
                model = load_model(model_path)
        except FileNotFoundError:
            model = None
        return model 
開發者ID:msgi,項目名稱:nlp-journey,代碼行數:12,代碼來源:siamese_similarity.py

示例12: __init__

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def __init__(self, model_path,
                 config_path,
                 train=False,
                 train_file_path=None,
                 vector_path=None):
        self.model_path = model_path
        self.config_path = config_path
        if not train:
            assert config_path is not None, 'The config path cannot be None.'
            config = load_config(self.config_path)
            if not config:
                (self.word_index, self.max_len, self.embeddings) = config
                self.model = load_model(self.model_path, self.build_model())
            if not self.model:
                print('The model cannot be loaded:', self.model_path)
        else:
            self.vector_path = vector_path
            self.train_file_path = train_file_path
            self.x_train, self.y_train, self.x_test, self.y_test, self.word_index, self.max_index = self.load_data()
            self.max_len = self.x_train.shape[1]
            config = load_config(self.config_path)
            if not config:
                self.embeddings = load_bin_word2vec(self.word_index, self.vector_path, self.max_index)
                save_config((self.word_index, self.max_len, self.embeddings), self.config_path)
            else:
                (_, _, self.embeddings) = config
            self.model = self.train()
            save_model(self.model, self.model_path)

    # 全連接的一個簡單的網絡, 僅用來作為基類測試代碼通過,速度快, 但是分類效果特別差 
開發者ID:msgi,項目名稱:nlp-journey,代碼行數:32,代碼來源:deep_classifier.py

示例13: run

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def run(self):
        if self.args.type == "ml":
            X = make_dataset_ml(self.args)
            pipe = load(self.args.model)
            pred = get_genres(pipe.predict(X)[0], self.genres)
            print("{} is a {} song".format(self.args.song, pred))

        else:
            X = make_dataset_dl(self.args)
            model = load_model(self.args.model)

            preds = model.predict(X)
            votes = majority_voting(preds, self.genres)
            print("{} is a {} song".format(self.args.song, votes[0][0]))
            print("most likely genres are: {}".format(votes[:3])) 
開發者ID:Hguimaraes,項目名稱:gtzan.keras,代碼行數:17,代碼來源:__init__.py

示例14: load_network

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def load_network(self, path, name=None, ext="h5"):
        # nothing has changed
        path_model, path_target_model = self._get_path_model(path, name)
        self.model = load_model('{}.{}'.format(path_model, ext))
        self.target_model = load_model('{}.{}'.format(path_target_model, ext))
        print("Succesfully loaded network.") 
開發者ID:rte-france,項目名稱:Grid2Op,代碼行數:8,代碼來源:ml_agent.py

示例15: __init__

# 需要導入模塊: from tensorflow.keras import models [as 別名]
# 或者: from tensorflow.keras.models import load_model [as 別名]
def __init__(self):
        config = configparser.ConfigParser()
        config.read('./config/config.ini')

        self.log_Image = ''
        self.LogNames = ''

        self.model_file = config['Digital_Digit']['Modelfile']
        if config.has_option('Digital_Digit', 'LogImageLocation'):
            self.log_Image = config['Digital_Digit']['LogImageLocation']
        self.CheckAndLoadDefaultConfig()

        if config.has_option('Digital_Digit', 'LogImageLocation'):
            if (os.path.exists(self.log_Image)):
                for i in range(10):
                    pfad = self.log_Image + '/' + str(i)
                    if not os.path.exists(pfad):
                        os.makedirs(pfad)
                pfad = self.log_Image + '/NaN'
                if not os.path.exists(pfad):
                    os.makedirs(pfad)

            if config.has_option('Digital_Digit', 'LogNames'):
                zw_LogNames = config.get('Digital_Digit', 'LogNames').split(',')
                self.LogNames = []
                for nm in zw_LogNames:
                      self.LogNames.append(nm.strip())
            else:
                self.LogNames = ''
        else:
            self.log_Image = ''

        self.model_file = config['Digital_Digit']['Modelfile']
        self.model = load_model(self.model_file) 
開發者ID:jomjol,項目名稱:water-meter-system-complete,代碼行數:36,代碼來源:ReadDigitalDigitClass.py


注:本文中的tensorflow.keras.models.load_model方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。