Keras

Snowflake ML Model Registry 支持 Keras 3 模型(keras.Model,Keras 版本 >= 3.0.0)。Keras 3 是多后端框架,支持 TensorFlow、PyTorch 和 JAX 作为后端。

备注

适用于 Keras 版本 < 3.0.0, use the TensorFlow 处理程序。

调用 options 时,可以在 log_model 字典中使用下列附加选项:

选项

描述

target_methods

可在模型对象上使用的方法的名称列表。Keras 模型以 predict 作为默认目标方法。

cuda_version

部署到具有 GPU 的平台时使用的 CUDA 运行时版本;默认值为 11.8。如果手动设置为 None,则无法将模型部署到具有 GPU 的平台。

在登记 Keras 模型时,您必须指定 sample_input_datasignatures 参数,以确保注册表了解目标方法的签名。

备注

Keras 模型只能有一种目标方法。

示例

这些示例假设 regsnowflake.ml.registry.Registry 的一个实例。

序列模型

以下示例演示了如何训练 Keras 3 顺序模型、将其记录到 Snowflake ML Model Registry 并运行推理。

import 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 sequential model
model = keras.Sequential([
    keras.layers.Dense(64, activation='relu'),
    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_keras_classifier",
    version_name="v1",
    sample_input_data=X_test,
)

# Make predictions
result_df = model_ref.run(X_test[-10:], function_name="predict")
Copy

函数式 API 模型

以下示例演示了如何使用 Keras 函数式 API 创建模型。

import keras
import numpy as np
import pandas as pd

# Create sample data
n_samples, n_features = 100, 10
X = pd.DataFrame(
    np.random.rand(n_samples, n_features),
    columns=[f"feature_{i}" for i in range(n_features)]
)
y = np.random.randint(0, 2, n_samples).astype(np.float32)

# Build model using Functional API
inputs = keras.Input(shape=(n_features,))
x = keras.layers.Dense(32, activation='relu')(inputs)
x = keras.layers.Dense(16, activation='relu')(x)
outputs = keras.layers.Dense(1, activation='sigmoid')(x)
model = keras.Model(inputs=inputs, outputs=outputs)

model.compile(
    optimizer=keras.optimizers.SGD(learning_rate=0.01),
    loss=keras.losses.MeanSquaredError()
)

# Train the model
model.fit(X, y, epochs=10, verbose=0)

# Log the model
model_ref = reg.log_model(
    model=model,
    model_name="my_functional_model",
    version_name="v1",
    sample_input_data=X,
)

# Make predictions
result_df = model_ref.run(X[-10:], function_name="predict")
Copy

自定义子类模型

以下示例演示了如何通过子类化 keras.Model 来创建自定义模型。

import keras
import numpy as np
import pandas as pd

# Define custom model with serialization support
@keras.saving.register_keras_serializable()
class BinaryClassifier(keras.Model):
    def __init__(self, hidden_units: int, output_units: int) -> None:
        super().__init__()
        self.dense1 = keras.layers.Dense(hidden_units, activation="relu")
        self.dense2 = keras.layers.Dense(output_units, activation="sigmoid")

    def call(self, inputs):
        x = self.dense1(inputs)
        return self.dense2(x)

    def get_config(self):
        base_config = super().get_config()
        config = {
            "dense1": keras.saving.serialize_keras_object(self.dense1),
            "dense2": keras.saving.serialize_keras_object(self.dense2),
        }
        return {**base_config, **config}

    @classmethod
    def from_config(cls, config):
        dense1_config = config.pop("dense1")
        dense1 = keras.saving.deserialize_keras_object(dense1_config)
        dense2_config = config.pop("dense2")
        dense2 = keras.saving.deserialize_keras_object(dense2_config)
        obj = cls(1, 1)
        obj.dense1 = dense1
        obj.dense2 = dense2
        return obj

# Create sample data
n_samples, n_features = 100, 10
X = pd.DataFrame(
    np.random.rand(n_samples, n_features),
    columns=[f"feature_{i}" for i in range(n_features)]
)
y = np.random.randint(0, 2, n_samples).astype(np.float32)

# Create and train model
model = BinaryClassifier(hidden_units=32, output_units=1)
model.compile(
    optimizer=keras.optimizers.SGD(learning_rate=0.01),
    loss=keras.losses.MeanSquaredError()
)
model.fit(X, y, epochs=10, verbose=0)

# Log the model
model_ref = reg.log_model(
    model=model,
    model_name="my_custom_classifier",
    version_name="v1",
    sample_input_data=X,
)

# Make predictions
result_df = model_ref.run(X[-10:], function_name="predict")
Copy