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


Python backend.clear_session方法代碼示例

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


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

示例1: infer

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [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

示例2: train

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def train(lambd, sigma, n_centers, trial):
    K.clear_session()
    (X_train, y_train), (X_test, y_test) = inbalanced_cifar(200)

    model = create_models(sigma, n_centers)
    model.compile("adam", affinity_loss(lambd), [acc])
    tf.logging.set_verbosity(tf.logging.FATAL) # ログを埋めないようにする

    tpu_grpc_url = "grpc://"+os.environ["COLAB_TPU_ADDR"]
    tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(tpu_grpc_url)
    strategy = keras_support.TPUDistributionStrategy(tpu_cluster_resolver)
    model = tf.contrib.tpu.keras_to_tpu_model(model, strategy=strategy)

    scheduler = LearningRateScheduler(step_decay)
    f1 = F1Callback(model, X_test, y_test, trial)

    history = model.fit(X_train, y_train, callbacks=[scheduler, f1],
                        batch_size=640, epochs=100, verbose=0).history

    max_f1 = max(f1.f1_log)
    print(f"lambda:{lambd:.04}, sigma:{sigma:.04} n_centers:{n_centers} / f1 = {max_f1:.04}")
    return max_f1 
開發者ID:koshian2,項目名稱:affinity-loss,代碼行數:24,代碼來源:cnn_cifar_optuna_affinity.py

示例3: get_yolo2_inference_model

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def get_yolo2_inference_model(model_type, anchors, num_classes, weights_path=None, input_shape=None, confidence=0.1):
    '''create the inference model, for YOLOv2'''
    #K.clear_session() # get a new session
    num_anchors = len(anchors)

    image_shape = Input(shape=(2,), dtype='int64', name='image_shape')

    model_body, _ = get_yolo2_model(model_type, num_anchors, num_classes, input_shape=input_shape)
    print('Create YOLOv2 {} model with {} anchors and {} classes.'.format(model_type, num_anchors, num_classes))

    if weights_path:
        model_body.load_weights(weights_path, by_name=False)#, skip_mismatch=True)
        print('Load weights {}.'.format(weights_path))

    boxes, scores, classes = Lambda(batched_yolo2_postprocess, name='yolo2_postprocess',
            arguments={'anchors': anchors, 'num_classes': num_classes, 'confidence': confidence})(
        [model_body.output, image_shape])

    model = Model([model_body.input, image_shape], [boxes, scores, classes])

    return model 
開發者ID:david8862,項目名稱:keras-YOLOv3-model-set,代碼行數:23,代碼來源:model.py

示例4: ReadoutSingleImage

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def ReadoutSingleImage(self, image):
        test_image = image.resize((32, 32), Image.NEAREST)
        test_image.save('./image_tmp/resize.jpg', "JPEG")
        test_image = np.array(test_image, dtype="float32")
        img = np.reshape(test_image,[1,32,32,3])
        classes = self.model.predict(img)
        out_sin = classes[0][0]
        out_cos = classes[0][1]
        K.clear_session()
        result =  np.arctan2(out_sin, out_cos)/(2*math.pi) % 1
        result = result * 10
        return result 
開發者ID:jomjol,項目名稱:water-meter-system-complete,代碼行數:14,代碼來源:ReadAnalogNeedleClass.py

示例5: ReadoutSingleImage

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def ReadoutSingleImage(self, image):
        test_image = image.resize((20, 32), Image.NEAREST)
        test_image.save('./image_tmp/resize.jpg', "JPEG")
        test_image = np.array(test_image, dtype="float32")
        img = np.reshape(test_image,[1,32,20,3])
        result = self.model.predict_classes(img)
        K.clear_session()
        if result == 10:
            result = "NaN"
        else:
            result = result[0]
        return result 
開發者ID:jomjol,項目名稱:water-meter-system-complete,代碼行數:14,代碼來源:ReadDigitalDigitClass.py

示例6: tearDown

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def tearDown(self):
        global _GLOBAL_FILENAME

        tf.reset_default_graph()
        K.clear_session()

        logging.debug("Cleaning file: %s", _GLOBAL_FILENAME)
        os.remove(_GLOBAL_FILENAME)

        logging.getLogger().setLevel(self.previous_logging_level) 
開發者ID:tf-encrypted,項目名稱:tf-encrypted,代碼行數:12,代碼來源:convert_test.py

示例7: setUp

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def setUp(self):
        K.clear_session() 
開發者ID:tf-encrypted,項目名稱:tf-encrypted,代碼行數:4,代碼來源:private_model_test.py

示例8: tearDown

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def tearDown(self):
        K.clear_session() 
開發者ID:tf-encrypted,項目名稱:tf-encrypted,代碼行數:4,代碼來源:private_model_test.py

示例9: keras_test

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def keras_test(func):
    """Function wrapper to clean up after TensorFlow tests.
    # Arguments
        func: test function to clean up after.
    # Returns
        A function wrapping the input function.
    """
    @six.wraps(func)
    def wrapper(*args, **kwargs):
        output = func(*args, **kwargs)
        K.clear_session()
        return output
    return wrapper 
開發者ID:carlomazzaferro,項目名稱:kryptoflow,代碼行數:15,代碼來源:test_keras_model_io.py

示例10: test_loader

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def test_loader(keras_model, project_manager):
    skl = KerasModel(artifact=keras_model)
    skl.store(name='nn')
    K.clear_session()
    reloaded = skl.load(name='nn')
    assert isinstance(reloaded, KerasBaseModel)

    for root, dirs, files in os.walk(project_manager.CONFIG['saved-models']):
        for f in files:
            os.unlink(os.path.join(root, f))
        for d in dirs:
            shutil.rmtree(os.path.join(root, d))

    with open(os.path.join(project_manager.CONFIG['saved-models'], '.gitkeep'), 'w') as gitkeep:
        gitkeep.write('empty') 
開發者ID:carlomazzaferro,項目名稱:kryptoflow,代碼行數:17,代碼來源:test_keras_model_io.py

示例11: test_trainable_model_from_file

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def test_trainable_model_from_file(keras_model, project_manager):
    skl = KerasModel(artifact=keras_model)
    skl.store(name='nn')

    K.clear_session()
    trainable = TrainableModel.from_file(run_number=1, name='nn', model_type='keras')
    assert isinstance(trainable.model, KerasBaseModel)
    for root, dirs, files in os.walk(project_manager.CONFIG['saved-models']):
        for f in files:
            os.unlink(os.path.join(root, f))
        for d in dirs:
            shutil.rmtree(os.path.join(root, d))

    with open(os.path.join(project_manager.CONFIG['saved-models'], '.gitkeep'), 'w') as gitkeep:
        gitkeep.write('empty') 
開發者ID:carlomazzaferro,項目名稱:kryptoflow,代碼行數:17,代碼來源:test_keras_model_io.py

示例12: clear_session_after_test

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def clear_session_after_test():
    """Test wrapper to clean up after TensorFlow and CNTK tests.

    This wrapper runs for all the tests in the keras test suite.
    """
    yield
    if K.backend() == 'tensorflow' or K.backend() == 'cntk':
        K.clear_session() 
開發者ID:beringresearch,項目名稱:ivis,代碼行數:10,代碼來源:conftest.py

示例13: setUp

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def setUp(self) -> None:
        K.clear_session() 
開發者ID:philipperemy,項目名稱:keract,代碼行數:4,代碼來源:display_activations_test.py

示例14: tearDown

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def tearDown(self) -> None:
        K.clear_session()
        for image in glob('*.png'):
            os.remove(image) 
開發者ID:philipperemy,項目名稱:keract,代碼行數:6,代碼來源:display_activations_test.py

示例15: tearDown

# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def tearDown(self) -> None:
        K.clear_session() 
開發者ID:philipperemy,項目名稱:keract,代碼行數:4,代碼來源:get_activations_test.py


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