TensorFlow¶
Snowflake ML モデルレジストリは、 TensorFlow(tensorflow.Module から派生したモデル)およびKeras v2モデル(Kerasバージョン< 3.0.0の keras.Model)を使用して作成されたモデルをサポートします。
注釈
Keras 3.0.0以降の場合は、 Keras ハンドラーを使用します。
以下の追加オプションは、 options ディクショナリで log_model を呼び出すときに使用できます。
オプション |
説明 |
|---|---|
|
モデルオブジェクトで利用可能なメソッドの名前のリスト。 TensorFlow モデルにはデフォルトのターゲットメソッドとして |
|
GPUを持つプラットフォームへの展開時に使用する CUDAランタイムのバージョン。デフォルトで11.8。手動で |
|
モデルが複数のテンソル入力を期待するかどうか。デフォルトは |
TensorFlow モデルをログする場合は、 sample_input_data か signatures のどちらかのパラメーターを指定する必要があります。
注釈
Keras v2モデルは、ターゲットメソッドを1つだけ持つことができます。
注釈
Pandas DataFrames(デフォルトではfloat64を使用)を使用する場合、dtypeの不一致エラーを避けるために、 TensorFlow モデルで変数と tf.TensorSpec 入力署名に tf.float64 が使用されていることを確認してください。
例¶
これらの例では、 reg が snowflake.ml.registry.Registry のインスタンスであると想定しています。
TensorFlow モジュール¶
次の例は、 tf.Module をサブクラス化し、それをSnowflake ML モデルレジストリに記録し、推論を実行して TensorFlow モデルを作成する方法を示しています。
import tensorflow as tf
import pandas as pd
# Define a simple TensorFlow module
class LinearModel(tf.Module):
def __init__(self, name=None):
super().__init__(name=name)
self.weight = tf.Variable(2.0, dtype=tf.float64, name="weight")
self.bias = tf.Variable(1.0, dtype=tf.float64, name="bias")
@tf.function(input_signature=[tf.TensorSpec(shape=(None, 1), dtype=tf.float64)])
def __call__(self, x):
return self.weight * x + self.bias
# Create model instance
model = LinearModel(name="linear_model")
# Create sample input data as DataFrame
sample_df = pd.DataFrame({"input": [1.0, 2.0, 3.0, 4.0, 5.0]})
# Log the model
model_ref = reg.log_model(
model=model,
model_name="my_tf_linear_model",
version_name="v1",
sample_input_data=sample_df,
)
# Make predictions (default target method is __call__)
test_df = pd.DataFrame({"input": [6.0, 7.0, 8.0]})
result_df = model_ref.run(test_df)
Keras v2シーケンシャルモデル¶
次の例は、Keras v2シーケンシャルモデルをトレーニングし、それをSnowflake ML モデルレジストリに記録し、推論を実行する方法を示しています。
import tf_keras as keras
from sklearn import datasets, model_selection
# Load dataset
iris = datasets.load_iris(as_frame=True)
X = iris.data
y = iris.target
# Rename columns for valid Snowflake identifiers
X.columns = [col.replace(' ', '_').replace('(', '').replace(')', '') for col in X.columns]
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2)
# Build Keras v2 model
model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dense(3, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Train the model
model.fit(X_train, y_train, epochs=50, verbose=0)
# Log the model
model_ref = reg.log_model(
model=model,
model_name="my_iris_classifier",
version_name="v1",
sample_input_data=X_test,
)
# Make predictions
result_df = model_ref.run(X_test[-10:], function_name="predict")