本文整理匯總了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())
示例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
示例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
示例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
示例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
示例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)
示例7: setUp
# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def setUp(self):
K.clear_session()
示例8: tearDown
# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def tearDown(self):
K.clear_session()
示例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
示例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')
示例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')
示例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()
示例13: setUp
# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def setUp(self) -> None:
K.clear_session()
示例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)
示例15: tearDown
# 需要導入模塊: from tensorflow.keras import backend [as 別名]
# 或者: from tensorflow.keras.backend import clear_session [as 別名]
def tearDown(self) -> None:
K.clear_session()