本文整理汇总了Python中tensorflow.python.keras.models.Model方法的典型用法代码示例。如果您正苦于以下问题:Python models.Model方法的具体用法?Python models.Model怎么用?Python models.Model使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.python.keras.models
的用法示例。
在下文中一共展示了models.Model方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_model
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def create_model(node_size, hidden_size=[256, 128], l1=1e-5, l2=1e-4):
A = Input(shape=(node_size,))
L = Input(shape=(None,))
fc = A
for i in range(len(hidden_size)):
if i == len(hidden_size) - 1:
fc = Dense(hidden_size[i], activation='relu',
kernel_regularizer=l1_l2(l1, l2), name='1st')(fc)
else:
fc = Dense(hidden_size[i], activation='relu',
kernel_regularizer=l1_l2(l1, l2))(fc)
Y = fc
for i in reversed(range(len(hidden_size) - 1)):
fc = Dense(hidden_size[i], activation='relu',
kernel_regularizer=l1_l2(l1, l2))(fc)
A_ = Dense(node_size, 'relu', name='2nd')(fc)
model = Model(inputs=[A, L], outputs=[A_, Y])
emb = Model(inputs=A, outputs=Y)
return model, emb
示例2: _build_model
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def _build_model(embedding_weights, char_bidirectional=False, concat_bidirectional=True):
word_emb_input, word_emb_output, char_emb_input, char_emb_output = _build_embeddings(embedding_weights, char_bidirectional)
# concatenate word embedding and character embedding
x = concatenate([word_emb_output, char_emb_output])
x = Dropout(dropout)(x)
# construct LSTM layers. Option to use 1 Bidirectonal layer, or one forward and one backward LSTM layer.
# Empirical results appear better with bidirectional LSTM here, hence it is the default.
if concat_bidirectional:
x = Bidirectional(LSTM(hidden_size_lstm, return_sequences=True))(x)
else:
fw_LSTM_2 = LSTM(hidden_size_lstm, return_sequences=True)(x)
bw_LSTM_2 = LSTM(hidden_size_lstm, return_sequences=True, go_backwards=True)(fw_LSTM_2)
x = concatenate([fw_LSTM_2, bw_LSTM_2])
x = Dropout(dropout)(x)
scores = Dense(n_labels)(x)
# Activation Function
x = Activation("softmax", name='predict_output')(scores)
# create model
model = Model([word_emb_input, char_emb_input], x)
return model
# === Build model ===
示例3: load_model_and_replace_output
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def load_model_and_replace_output(model_old, model_new, new_output_layer):
""" Load a model and replace the last layer """
new_input = model_old.input
# get old model output before last layer
old_output = model_old.layers[-2].output
# create a new output layer
new_output = (new_output_layer)(old_output)
# combine old model with new output layer
new_model = Model(inputs=new_input,
outputs=new_output)
logging.info("Replacing output layer of model")
# print layers of old model
for layer, i in zip(new_model.layers, range(0, len(new_model.layers))):
logging.info("Old model - layer %s: %s" % (i, layer.name))
return new_model
示例4: GCN
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def GCN(adj_dim,feature_dim,n_hidden, num_class, num_layers=2,activation=tf.nn.relu,dropout_rate=0.5, l2_reg=0, feature_less=True, ):
Adj = Input(shape=(None,), sparse=True)
if feature_less:
X_in = Input(shape=(1,), )
emb = Embedding(adj_dim, feature_dim,
embeddings_initializer=Identity(1.0), trainable=False)
X_emb = emb(X_in)
h = Reshape([X_emb.shape[-1]])(X_emb)
else:
X_in = Input(shape=(feature_dim,), )
h = X_in
for i in range(num_layers):
if i == num_layers - 1:
activation = tf.nn.softmax
n_hidden = num_class
h = GraphConvolution(n_hidden, activation=activation, dropout_rate=dropout_rate, l2_reg=l2_reg)([h,Adj])
output = h
model = Model(inputs=[X_in,Adj], outputs=output)
return model
示例5: __init__
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def __init__(self, actions):
'''
Utility Model class to construct child models provided with an action list.
# Args:
actions: list of [input; action] pairs that define the cell.
'''
super(ModelGenerator, self).__init__()
self.B = len(actions) // 4
self.action_list = np.split(np.array(actions), len(actions) // 2)
self.global_counter = 0
self.cell_1 = self.build_cell(self.B, self.action_list, filters=32, stride=(2, 2))
self.cell_2 = self.build_cell(self.B, self.action_list, filters=64, stride=(2, 2))
self.gap = GlobalAveragePooling2D()
self.logits = Dense(10, activation='softmax') # only logits
示例6: create_model
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def create_model(numNodes, embedding_size, order='second'):
v_i = Input(shape=(1,))
v_j = Input(shape=(1,))
first_emb = Embedding(numNodes, embedding_size, name='first_emb')
second_emb = Embedding(numNodes, embedding_size, name='second_emb')
context_emb = Embedding(numNodes, embedding_size, name='context_emb')
v_i_emb = first_emb(v_i)
v_j_emb = first_emb(v_j)
v_i_emb_second = second_emb(v_i)
v_j_context_emb = context_emb(v_j)
first = Lambda(lambda x: tf.reduce_sum(
x[0]*x[1], axis=-1, keep_dims=False), name='first_order')([v_i_emb, v_j_emb])
second = Lambda(lambda x: tf.reduce_sum(
x[0]*x[1], axis=-1, keep_dims=False), name='second_order')([v_i_emb_second, v_j_context_emb])
if order == 'first':
output_list = [first]
elif order == 'second':
output_list = [second]
else:
output_list = [first, second]
model = Model(inputs=[v_i, v_j], outputs=output_list)
return model, {'first': first_emb, 'second': second_emb}
示例7: save_model_to_tensorflow
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def save_model_to_tensorflow(self, new_model_folder, new_model_name=""):
"""
'save_model_to_tensorflow' function allows you to save your loaded Keras (.h5) model and save it to the Tensorflow (.pb) model format.
- new_model_folder (required), the path to the folder you want the converted Tensorflow model to be saved
- new_model_name (required), the desired filename for your converted Tensorflow model e.g 'my_new_model.pb'
:param new_model_folder:
:param new_model_name:
:return:
"""
if(self.__modelLoaded == True):
out_prefix = "output_"
output_dir = new_model_folder
if os.path.exists(output_dir) == False:
os.mkdir(output_dir)
model_name = os.path.join(output_dir, new_model_name)
keras_model = self.__model_collection[0]
out_nodes = []
for i in range(len(keras_model.outputs)):
out_nodes.append(out_prefix + str(i + 1))
tf.identity(keras_model.output[i], out_prefix + str(i + 1))
sess = K.get_session()
from tensorflow.python.framework import graph_util, graph_io
init_graph = sess.graph.as_graph_def()
main_graph = graph_util.convert_variables_to_constants(sess, init_graph, out_nodes)
graph_io.write_graph(main_graph, output_dir, name=model_name, as_text=False)
print("Tensorflow Model Saved")
示例8: save_model
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def save_model(
size_height=448,
size_width=448,
no_class=200
):
'''Save Bilinear CNN to current directory.
The model will be saved as `model.json`.
Args:
size_height: default 448.
size_width: default 448.
no_class: number of prediction classes.
Returns:
Bilinear CNN model.
'''
model = buil_bcnn(
size_height=size_height,
size_width=size_width,
no_class=no_class)
# Save model json
model_json = model.to_json()
with open('./model.json', 'w') as f:
f.write(model_json)
print('Model is saved to ./model.json')
return True
示例9: export_model
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def export_model(self):
with tempfile.TemporaryDirectory() as tmp_path:
# try:
# # LOGGER.info("Model saved with model.save method.")
# tf.keras.models.save_model(self._model, filepath=tmp_path, save_format="tf")
# except NotImplementedError:
# import warnings
# warnings.warn('Saving the model as SavedModel is still in experimental stages. '
# 'trying tf.keras.experimental.export_saved_model...')
tf.keras.experimental.export_saved_model(self._model, saved_model_path=tmp_path)
model_bytes = zip_dir_as_bytes(tmp_path)
return model_bytes
示例10: export_model
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def export_model(self):
with tempfile.TemporaryDirectory() as tmp_path:
# Comment this block because tf 1.15 is not supporting Keras Customized Layer
# try:
# # LOGGER.info("Model saved with model.save method.")
# tf.keras.models.save_model(self._model, filepath=tmp_path, save_format="tf")
# except NotImplementedError:
# import warnings
# warnings.warn('Saving the model as SavedModel is still in experimental stages. '
# 'trying tf.keras.experimental.export_saved_model...')
tf.keras.experimental.export_saved_model(self._model, saved_model_path=tmp_path)
model_bytes = zip_dir_as_bytes(tmp_path)
return model_bytes
示例11: __init__
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def __init__(self, encoderArchitecture,
decoderArchitecture):
self.encoder = encoderArchitecture.model
self.decoder = decoderArchitecture.model
self.ae = Model(self.encoder.inputs, self.decoder(self.encoder.outputs))
示例12: test_mnist_unet_with_shape_valid
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def test_mnist_unet_with_shape_valid(self):
num_subsamples = 100
(x_train, y_train), (x_test, y_test) = TestUtil.get_mnist(flattened=False, num_subsamples=num_subsamples)
explained_model_builder = MLPModelBuilder(num_layers=2, num_units=64, activation="relu", p_dropout=0.2,
verbose=0, batch_size=256, learning_rate=0.001, num_epochs=2,
early_stopping_patience=128)
input_shape = x_train.shape[1:]
input_layer = Input(shape=input_shape)
last_layer = Flatten()(input_layer)
last_layer = explained_model_builder.build(last_layer)
last_layer = Dense(y_train.shape[-1], activation="softmax")(last_layer)
explained_model = Model(input_layer, last_layer)
explained_model.compile(loss="categorical_crossentropy",
optimizer="adam")
explained_model.fit(x_train, y_train)
masking_operation = ZeroMasking()
loss = categorical_crossentropy
downsample_factors = [(2, 2), (4, 4), (4, 7), (7, 4), (7, 7)]
with_bns = [True if i % 2 == 0 else False for i in range(len(downsample_factors))]
for downsample_factor, with_bn in zip(downsample_factors, with_bns):
model_builder = UNetModelBuilder(downsample_factor, num_layers=2, num_units=64, activation="relu",
p_dropout=0.2, verbose=0, batch_size=256, learning_rate=0.001,
num_epochs=2, early_stopping_patience=128, with_bn=with_bn)
explainer = CXPlain(explained_model, model_builder, masking_operation, loss,
downsample_factors=downsample_factor)
explainer.fit(x_train, y_train)
eval_score = explainer.score(x_test, y_test)
train_score = explainer.get_last_fit_score()
median = explainer.predict(x_test)
self.assertTrue(median.shape == x_test.shape)
示例13: trivial_model
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def trivial_model(num_classes):
"""Trivial model for ImageNet dataset."""
input_shape = (224, 224, 3)
img_input = layers.Input(shape=input_shape)
x = layers.Lambda(lambda x: backend.reshape(x, [-1, 224 * 224 * 3]),
name='reshape')(img_input)
x = layers.Dense(1, name='fc1')(x)
x = layers.Dense(num_classes, name='fc1000')(x)
x = layers.Activation('softmax', dtype='float32')(x)
return models.Model(img_input, x, name='trivial')
开发者ID:ShivangShekhar,项目名称:Live-feed-object-device-identification-using-Tensorflow-and-OpenCV,代码行数:15,代码来源:trivial_model.py
示例14: is_multi_gpu_model
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def is_multi_gpu_model(model):
""" Check if a specific model is a multi_gpu model by checking if one of
the layers is a keras model itself
"""
for layer in model.layers:
if isinstance(layer, Model):
return True
return False
示例15: get_gpu_base_model
# 需要导入模块: from tensorflow.python.keras import models [as 别名]
# 或者: from tensorflow.python.keras.models import Model [as 别名]
def get_gpu_base_model(model):
""" get multi_gpu base model
"""
for layer in model.layers:
if isinstance(layer, Model):
return layer
return None