How to use the tensorflowjs.converters function in tensorflowjs

To help you get started, we’ve selected a few tensorflowjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jaynilpatel / playing-with-ai / training.py View on Github external
model.add(Dense(3, activation='softmax'))

adam = keras.optimizers.Adam(lr=0.001)

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

model.fit(x_train, y_train,
          epochs=10,
          batch_size=128)

score = model.evaluate(x_test, y_test, batch_size=128)
print(score)
model.save("Keras-64x2-10epoch")
tfjs.converters.save_keras_model(model, "trainedModel")
github piyush-kgp / Digit-Recognition-with-TFJS / model_builder.py View on Github external
X_test = X_test.reshape(-1, 784)

def create_model():
    model = Sequential([
                Dense(512, activation=tf.nn.relu, input_shape=(784,)),
                Dropout(0.2),
                Dense(10, activation=tf.nn.softmax)
            ])
    print(model.summary())
    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    return model

model = create_model()
model.fit(x = X_train, y = Y_train, batch_size = 100, validation_data = (X_test, Y_test))
model.save('my_mnist_model.h5')
tfjs.converters.save_keras_model(model, 'tfjs_target_dir')
github tensorflow / tfjs / scripts / translation.py View on Github external
num_encoder_tokens, num_decoder_tokens,
   __, target_token_index,
   encoder_input_data, decoder_input_data, decoder_target_data) = read_data()

  (encoder_inputs, encoder_states, decoder_inputs, decoder_lstm,
   decoder_dense, model) = seq2seq_model(
       num_encoder_tokens, num_decoder_tokens, FLAGS.latent_dim)

  # Run training.
  model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
  model.fit([encoder_input_data, decoder_input_data], decoder_target_data,
            batch_size=FLAGS.batch_size,
            epochs=FLAGS.epochs,
            validation_split=0.2)

  tfjs.converters.save_keras_model(model, FLAGS.artifacts_dir)

  # Next: inference mode (sampling).
  # Here's the drill:
  # 1) encode input and retrieve initial decoder state
  # 2) run one step of decoder with this initial state
  # and a "start of sequence" token as target.
  # Output will be the next target token
  # 3) Repeat with the current target token and current states

  # Define sampling models
  encoder_model = Model(encoder_inputs, encoder_states)

  decoder_state_input_h = Input(shape=(FLAGS.latent_dim,))
  decoder_state_input_c = Input(shape=(FLAGS.latent_dim,))
  decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
  decoder_outputs, state_h, state_c = decoder_lstm(
github piyush-kgp / Digit-Recognition-with-TFJS / v2_model_builder.py View on Github external
])
    print(model.summary())
    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    return model

model = create_model()
# checkpoint_path = "checkpoints/cp.ckpt"
# checkpoint_dir = os.path.dirname(checkpoint_path)
# cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,
#                                                  save_weights_only=True,
#                                                  verbose=1)
# model.fit(x = X_train, y = Y_train, batch_size = 100, validation_data = (X_test, Y_test), callbacks = [cp_callback])
# model.save('my_mnist_model.h5')
model.fit(x = X_train, y = Y_train, batch_size = 100, validation_data = (X_test, Y_test))
model.save('my_mnist_model.h5')
tfjs.converters.save_keras_model(model, 'tfjs_target_dir')
github tensorflow / tfjs-examples / sentiment / python / imdb.py View on Github external
'index_from': INDEX_FROM,
      'max_len': FLAGS.max_len,
      'model_type': FLAGS.model_type,
      'vocabulary_size': FLAGS.vocabulary_size,
      'embedding_size': FLAGS.embedding_size,
      'epochs': FLAGS.epochs,
      'batch_size': FLAGS.batch_size,
  }

  if not os.path.isdir(FLAGS.artifacts_dir):
    os.makedirs(FLAGS.artifacts_dir)
  metadata_json_path = os.path.join(FLAGS.artifacts_dir, 'metadata.json')
  json.dump(metadata, open(metadata_json_path, 'wt'))
  print('\nSaved model metadata at: %s' % metadata_json_path)

  tfjs.converters.save_keras_model(model, FLAGS.artifacts_dir)
  print('\nSaved model artifacts in directory: %s' % FLAGS.artifacts_dir)
github DiscreetAI / dml-library-js / server / model.py View on Github external
def _keras_2_tfjs(h5_model_path, path_to_save):
    """
    Do Keras stuff here
    """
    model = keras.models.load_model(h5_model_path)
    tfjs.converters.save_keras_model(model, path_to_save)
    K.clear_session()
github rodrigopivi / aida / python / src / pipelines / zebra_wings / pipeline.py View on Github external
def save(self, cfg):
        tfjs.converters.save_keras_model(self.__classification_model.keras_model(), cfg['classificationPath'])
        slots_length = len(self.__dataset_params["slotsToId"].keys())
        # NOTE: only save the ner model if there are slots
        if slots_length >= 2:
            tfjs.converters.save_keras_model(self.__ner_model.keras_model(), cfg['nerPath'])
        tfjs.converters.save_keras_model(self.__embeddings_model.keras_model(), cfg['embeddingPath'])
github vin-nag / GANs-n-reels / src / Model / ConvertToJS.py View on Github external
import tensorflowjs as tfjs
import tensorflow as tf

file_name = './Trained/generator_Aug10.h5'
gen_model = tf.keras.models.load_model(file_name)

tfjs.converters.save_keras_model(gen_model, './Trained')
print('done')
github micah5 / sneaker-generator / python / predict.py View on Github external
def predict():
    generator = construct_generator()

    if os.path.exists("./output/generator_weights.h5"):
        print('loaded generator model weights')
        generator.load_weights('./output/generator_weights.h5')

    # Saving model for tensorflow.js
    tfjs.converters.save_keras_model(generator, 'generator')

    batch_size = 64

    # Generate noise
    noise = np.random.uniform(size=[batch_size, 1, 1, 100])
    print(noise.shape)

    # Generate images
    generated_images = generator.predict(noise)

    # Save images
    for i in range(batch_size):
        image = generated_images[i, :, :, :]
        image += 1
        image *= 127.5
        matplotlib.image.imsave('./output/shoe%d.png' % i, image.astype(np.uint8))