[파이썬] TensorFlow에서 TensorFlow.js

First, let’s start by creating a simple TensorFlow model using Python. Suppose we want to build a basic image classification model. We can use TensorFlow’s high-level API, Keras, to accomplish this task. Here’s an example code snippet to create and train a simple model:

import tensorflow as tf
from tensorflow import keras

# Load the dataset
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

# Preprocess the data
x_train = x_train.reshape((x_train.shape[0], 28, 28, 1))
x_test = x_test.reshape((x_test.shape[0], 28, 28, 1))
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255

# Define the model architecture
model = keras.Sequential([
    keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    keras.layers.MaxPooling2D((2, 2)),
    keras.layers.Flatten(),
    keras.layers.Dense(10, activation='softmax')
])

# Compile and train the model
model.compile(optimizer='adam', 
              loss='sparse_categorical_crossentropy', 
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test, y_test))

Once we have trained our TensorFlow model, we can proceed to convert it into TensorFlow.js format. TensorFlow provides a handy tool called tensorflowjs_converter that performs the conversion. To use tensorflowjs_converter, we need to save our trained model in a format compatible with TensorFlow.js. Here’s an example code snippet to convert the trained model:

# Save the model in TensorFlow SavedModel format
tf.saved_model.save(model, 'saved_model')

# Convert the SavedModel into TensorFlow.js format
!tensorflowjs_converter --input_format=tf_saved_model saved_model/ model_js

After running the above conversion code, you will have a directory called “model_js” that contains all the necessary files for deploying your TensorFlow model in the browser using TensorFlow.js.

Now, you can take the “model_js” directory and include it in your web application. You can then use the TensorFlow.js library to load and make predictions with the model directly in the browser using JavaScript.

const model = await tf.loadLayersModel('model_js/model.json');

// Preprocess input data
const inputData = tf.tensor(...);
const preprocessedInput = ...;

// Make predictions
const predictions = model.predict(preprocessedInput);

// Do something with the predictions
...

By leveraging the TensorFlow Python API and the tensorflowjs_converter tool, you can easily create TensorFlow models in Python and convert them into TensorFlow.js format for deployment in the browser. This provides a powerful and seamless integration between TensorFlow and TensorFlow.js, allowing you to leverage the strengths of both libraries in your machine learning workflows. Happy coding!