Aracılığıyla paylaş


Modelleri eğitmek için özellikleri kullanma

Bu makalede Unity Kataloğu'nda veya yerel Çalışma Alanı Özellik Deposu'nda Özellik Mühendisliği'ni kullanarak modelleri nasıl eğitebileceğiniz açıklanmaktadır. Öncelikle kullanılacak özellikleri ve bunlara nasıl katılacağını tanımlayan bir eğitim veri kümesi oluşturmanız gerekir. Ardından modeli eğittiğiniz zaman model özelliklere yönelik başvuruları korur.

Unity Kataloğu'nda Özellik Mühendisliği'ni kullanarak bir modeli eğittiğinizde, modelin kökenini Katalog Gezgini'nde görüntüleyebilirsiniz. Modeli oluşturmak için kullanılan tablolar ve işlevler otomatik olarak izlenir ve görüntülenir. Bkz. Özellik deposu kökenini görüntüleme.

Modeli çıkarım için kullandığınızda, özellik deposundan özellik değerlerini almasını seçebilirsiniz. Modeli Model Sunma ile de kullanabilirsiniz ve çevrimiçi mağazalarda yayımlanan özellikleri otomatik olarak arar. Özellik deposu modelleri MLflow pyfunc arabirimiyle de uyumludur, bu nedenle özellik tablolarıyla toplu çıkarım gerçekleştirmek için MLflow kullanabilirsiniz.

Modeliniz ortam değişkenlerini kullanıyorsa modeli çevrimiçi olarak kullanıma alırken bunların nasıl kullanılacağı hakkında daha fazla bilgi için bkz . Model sunma uç noktalarındaki kaynaklara erişimi yapılandırma.

Bir model eğitim için en fazla 50 tablo ve 100 işlev kullanabilir.

Eğitim veri kümesi oluşturma

Model eğitimi için bir özellik tablosundan belirli özellikleri seçmek için , (Unity Kataloğu'nda Özellik Mühendisliği için) veya FeatureStoreClient.create_training_set (Çalışma Alanı Özellik Deposu için) API'sini ve adlı FeatureLookupnesneyi kullanarak FeatureEngineeringClient.create_training_set bir eğitim veri kümesi oluşturursunuz. A FeatureLookup , özellik tablosunun adı, özelliklerin adları ve özellik tablosuna geçirilen create_training_setDataFrame ile birleştirilirken kullanılacak anahtarlar da dahil olmak üzere eğitim kümesinde kullanılacak her özelliği belirtir. Daha fazla bilgi için bkz . Özellik Arama .

oluştururken FeatureLookupparametresini feature_names kullanın. feature_names , eğitim kümesinin oluşturulduğu sırada özellik tablosundaki tüm özellikleri (birincil anahtarlar hariç) aramak için tek bir özellik adı, özellik adları listesi veya Hiçbiri alır.

Not

DataFrame'deki sütunların lookup_key türü ve sırası, başvuru özellik tablosunun birincil anahtarların türü ve sırasıyla (zaman damgası anahtarları hariç) eşleşmelidir.

Bu makalede, söz diziminin her iki sürümü için kod örnekleri yer alır.

Bu örnekte, tarafından trainingSet.load_df döndürülen DataFrame içindeki feature_lookupsher özellik için bir sütun içerir. Kullanılarak exclude_columnsdışlananlar dışında dataframe'in sağlanan create_training_set tüm sütunlarını korur.

Unity kataloğunda özellik mühendisliği

from databricks.feature_engineering import FeatureEngineeringClient, FeatureLookup

# The model training uses two features from the 'customer_features' feature table and
# a single feature from 'product_features'
feature_lookups = [
    FeatureLookup(
      table_name='ml.recommender_system.customer_features',
      feature_names=['total_purchases_30d', 'total_purchases_7d'],
      lookup_key='customer_id'
    ),
    FeatureLookup(
      table_name='ml.recommender_system.product_features',
      feature_names=['category'],
      lookup_key='product_id'
    )
  ]

fe = FeatureEngineeringClient()

# Create a training set using training DataFrame and features from Feature Store
# The training DataFrame must contain all lookup keys from the set of feature lookups,
# in this case 'customer_id' and 'product_id'. It must also contain all labels used
# for training, in this case 'rating'.
training_set = fe.create_training_set(
  df=training_df,
  feature_lookups=feature_lookups,
  label='rating',
  exclude_columns=['customer_id', 'product_id']
)

training_df = training_set.load_df()

Çalışma alanı özellik deposu

from databricks.feature_store import FeatureLookup, FeatureStoreClient

# The model training uses two features from the 'customer_features' feature table and
# a single feature from 'product_features'
feature_lookups = [
    FeatureLookup(
      table_name='recommender_system.customer_features',
      feature_names=['total_purchases_30d', 'total_purchases_7d'],
      lookup_key='customer_id'
    ),
    FeatureLookup(
      table_name='recommender_system.product_features',
      feature_names=['category'],
      lookup_key='product_id'
    )
  ]

fs = FeatureStoreClient()

# Create a training set using training DataFrame and features from Feature Store
# The training DataFrame must contain all lookup keys from the set of feature lookups,
# in this case 'customer_id' and 'product_id'. It must also contain all labels used
# for training, in this case 'rating'.
training_set = fs.create_training_set(
  df=training_df,
  feature_lookups=feature_lookups,
  label='rating',
  exclude_columns=['customer_id', 'product_id']
)

training_df = training_set.load_df()

Arama anahtarları birincil anahtarlarla eşleşmediğinde TrainingSet oluşturma

Eğitim kümesindeki FeatureLookup sütun adı için içindeki bağımsız değişkenini lookup_key kullanın. create_training_set özellik tablosu oluşturulduğunda birincil anahtarların belirtildiği sırayı kullanarak bağımsız değişkende lookup_key belirtilen eğitim kümesindeki sütunlar arasında sıralı birleştirme gerçekleştirir.

Bu örnekte, recommender_system.customer_features şu birincil anahtarlara sahiptir: customer_id, dt.

Özellik recommender_system.product_features tablosunda birincil anahtar product_idbulunur.

aşağıdaki training_df sütunlara sahipse:

  • cid
  • transaction_dt
  • product_id
  • rating

aşağıdaki kod için TrainingSetdoğru özellik aramalarını oluşturur:

Unity kataloğunda özellik mühendisliği

feature_lookups = [
    FeatureLookup(
      table_name='ml.recommender_system.customer_features',
      feature_names=['total_purchases_30d', 'total_purchases_7d'],
      lookup_key=['cid', 'transaction_dt']
    ),
    FeatureLookup(
      table_name='ml.recommender_system.product_features',
      feature_names=['category'],
      lookup_key='product_id'
    )
  ]

Çalışma alanı özellik deposu

feature_lookups = [
    FeatureLookup(
      table_name='recommender_system.customer_features',
      feature_names=['total_purchases_30d', 'total_purchases_7d'],
      lookup_key=['cid', 'transaction_dt']
    ),
    FeatureLookup(
      table_name='recommender_system.product_features',
      feature_names=['category'],
      lookup_key='product_id'
    )
  ]

Çağrıldığındacreate_training_set, aşağıdaki kodda gösterildiği gibi sol birleştirme gerçekleştirerek, tabloları recommender_system.customer_features birleştirerek ve training_df (cid,) öğesine karşılık gelen anahtarları (customer_id,dttransaction_dt) kullanarak bir eğitim veri kümesi oluşturur:

Unity kataloğunda özellik mühendisliği

customer_features_df = spark.sql("SELECT * FROM ml.recommender_system.customer_features")
product_features_df = spark.sql("SELECT * FROM ml.recommender_system.product_features")

training_df.join(
  customer_features_df,
  on=[training_df.cid == customer_features_df.customer_id,
      training_df.transaction_dt == customer_features_df.dt],
  how="left"
).join(
  product_features_df,
  on="product_id",
  how="left"
)

Çalışma alanı özellik deposu

customer_features_df = spark.sql("SELECT * FROM recommender_system.customer_features")
product_features_df = spark.sql("SELECT * FROM recommender_system.product_features")

training_df.join(
  customer_features_df,
  on=[training_df.cid == customer_features_df.customer_id,
      training_df.transaction_dt == customer_features_df.dt],
  how="left"
).join(
  product_features_df,
  on="product_id",
  how="left"
)

Farklı özellik tablolarından aynı ada sahip iki özellik içeren bir TrainingSet oluşturma

içinde isteğe bağlı bağımsız değişkenini output_nameFeatureLookupkullanın. Sağlanan ad, tarafından TrainingSet.load_dfdöndürülen DataFrame'deki özellik adının yerine kullanılır. Örneğin, aşağıdaki kodla, tarafından training_set.load_df döndürülen DataFrame ve product_heightsütunlarını customer_height içerir.

Unity kataloğunda özellik mühendisliği

feature_lookups = [
    FeatureLookup(
      table_name='ml.recommender_system.customer_features',
      feature_names=['height'],
      lookup_key='customer_id',
      output_name='customer_height',
    ),
    FeatureLookup(
      table_name='ml.recommender_system.product_features',
      feature_names=['height'],
      lookup_key='product_id',
      output_name='product_height'
    ),
  ]

fe = FeatureEngineeringClient()

with mlflow.start_run():
  training_set = fe.create_training_set(
    df=df,
    feature_lookups=feature_lookups,
    label='rating',
    exclude_columns=['customer_id']
  )
  training_df = training_set.load_df()

Çalışma alanı özellik deposu

feature_lookups = [
    FeatureLookup(
      table_name='recommender_system.customer_features',
      feature_names=['height'],
      lookup_key='customer_id',
      output_name='customer_height',
    ),
    FeatureLookup(
      table_name='recommender_system.product_features',
      feature_names=['height'],
      lookup_key='product_id',
      output_name='product_height'
    ),
  ]

fs = FeatureStoreClient()

with mlflow.start_run():
  training_set = fs.create_training_set(
    df=df,
    feature_lookups=feature_lookups,
    label='rating',
    exclude_columns=['customer_id']
  )
  training_df = training_set.load_df()

Aynı özelliği birden çok kez kullanarak TrainingSet oluşturma

Farklı arama anahtarları tarafından birleştirilen aynı özelliği kullanarak bir TrainingSet oluşturmak için birden çok FeatureLookups kullanın. Her FeatureLookup çıkışı için benzersiz output_name bir kullanın.

Unity kataloğunda özellik mühendisliği

feature_lookups = [
    FeatureLookup(
      table_name='ml.taxi_data.zip_features',
      feature_names=['temperature'],
      lookup_key=['pickup_zip'],
      output_name='pickup_temp'
    ),
    FeatureLookup(
      table_name='ml.taxi_data.zip_features',
      feature_names=['temperature'],
      lookup_key=['dropoff_zip'],
      output_name='dropoff_temp'
    )
  ]

Çalışma alanı özellik deposu

feature_lookups = [
    FeatureLookup(
      table_name='taxi_data.zip_features',
      feature_names=['temperature'],
      lookup_key=['pickup_zip'],
      output_name='pickup_temp'
    ),
    FeatureLookup(
      table_name='taxi_data.zip_features',
      feature_names=['temperature'],
      lookup_key=['dropoff_zip'],
      output_name='dropoff_temp'
    )
  ]

Denetimsiz makine öğrenmesi modelleri için TrainingSet oluşturma

Denetimsiz öğrenme modelleri için TrainingSet oluştururken ayarlayın label=None . Örneğin, aşağıdaki TrainingSet farklı müşterileri ilgi alanlarına göre gruplar halinde kümelemesi için kullanılabilir:

Unity kataloğunda özellik mühendisliği

feature_lookups = [
    FeatureLookup(
      table_name='ml.recommender_system.customer_features',
      feature_names=['interests'],
      lookup_key='customer_id',
    ),
  ]

fe = FeatureEngineeringClient()
with mlflow.start_run():
  training_set = fe.create_training_set(
    df=df,
    feature_lookups=feature_lookups,
    label=None,
    exclude_columns=['customer_id']
  )

  training_df = training_set.load_df()

Çalışma alanı özellik deposu

feature_lookups = [
    FeatureLookup(
      table_name='recommender_system.customer_features',
      feature_names=['interests'],
      lookup_key='customer_id',
    ),
  ]

fs = FeatureStoreClient()
with mlflow.start_run():
  training_set = fs.create_training_set(
    df=df,
    feature_lookups=feature_lookups,
    label=None,
    exclude_columns=['customer_id']
  )

  training_df = training_set.load_df()

Özellik tabloları ile modelleri eğitin ve toplu çıkarım gerçekleştirin

Özellik Deposu'ndan özellikleri kullanarak bir modeli eğittiğiniz zaman model, özelliklere yönelik başvuruları korur. Modeli çıkarım için kullandığınızda Özellik Deposu'ndan özellik değerlerini almasını seçebilirsiniz. Modelde kullanılan özelliklerin birincil anahtarlarını sağlamanız gerekir. Model, çalışma alanınızdaki Özellik Deposu'ndan gerektirdiği özellikleri alır. Ardından puanlama sırasında özellik değerlerini gerektiği gibi birleştirir.

Çıkarım zamanında özellik aramasını desteklemek için:

  • (Unity Kataloğu'nda Özellik Mühendisliği için) veya FeatureStoreClient (Çalışma Alanı Özellik Deposu için) yöntemini FeatureEngineeringClient kullanarak log_model modeli günlüğe kaydetmeniz gerekir.
  • Modeli eğitmek için tarafından TrainingSet.load_df döndürülen DataFrame'i kullanmanız gerekir. Bu DataFrame'i modeli eğitmek için kullanmadan önce herhangi bir şekilde değiştirirseniz, modeli çıkarım için kullandığınızda değişiklikler uygulanmaz. Bu, modelin performansını düşürür.
  • Model türünün MLflow'da karşılık gelen python_flavor bir değeri olmalıdır. MLflow, aşağıdakiler dahil olmak üzere çoğu Python modeli eğitim çerçevesini destekler:
    • scikit-learn
    • keras
    • PyTorch
    • SparkML
    • LightGBM
    • XGBoost
    • TensorFlow Keras (kullanarak python_flavormlflow.keras)
  • Özel MLflow pyfunc modelleri

Unity kataloğunda özellik mühendisliği

# Train model
import mlflow
from sklearn import linear_model

feature_lookups = [
    FeatureLookup(
      table_name='ml.recommender_system.customer_features',
      feature_names=['total_purchases_30d'],
      lookup_key='customer_id',
    ),
    FeatureLookup(
      table_name='ml.recommender_system.product_features',
      feature_names=['category'],
      lookup_key='product_id'
    )
  ]

fe = FeatureEngineeringClient()

with mlflow.start_run():

  # df has columns ['customer_id', 'product_id', 'rating']
  training_set = fe.create_training_set(
    df=df,
    feature_lookups=feature_lookups,
    label='rating',
    exclude_columns=['customer_id', 'product_id']
  )

  training_df = training_set.load_df().toPandas()

  # "training_df" columns ['total_purchases_30d', 'category', 'rating']
  X_train = training_df.drop(['rating'], axis=1)
  y_train = training_df.rating

  model = linear_model.LinearRegression().fit(X_train, y_train)

  fe.log_model(
    model=model,
    artifact_path="recommendation_model",
    flavor=mlflow.sklearn,
    training_set=training_set,
    registered_model_name="recommendation_model"
  )

# Batch inference

# If the model at model_uri is packaged with the features, the FeatureStoreClient.score_batch()
# call automatically retrieves the required features from Feature Store before scoring the model.
# The DataFrame returned by score_batch() augments batch_df with
# columns containing the feature values and a column containing model predictions.

fe = FeatureEngineeringClient()

# batch_df has columns ‘customer_id’ and ‘product_id’
predictions = fe.score_batch(
    model_uri=model_uri,
    df=batch_df
)

# The ‘predictions’ DataFrame has these columns:
# ‘customer_id’, ‘product_id’, ‘total_purchases_30d’, ‘category’, ‘prediction’

Çalışma alanı özellik deposu

# Train model
import mlflow
from sklearn import linear_model

feature_lookups = [
    FeatureLookup(
      table_name='recommender_system.customer_features',
      feature_names=['total_purchases_30d'],
      lookup_key='customer_id',
    ),
    FeatureLookup(
      table_name='recommender_system.product_features',
      feature_names=['category'],
      lookup_key='product_id'
    )
  ]

fs = FeatureStoreClient()

with mlflow.start_run():

  # df has columns ['customer_id', 'product_id', 'rating']
  training_set = fs.create_training_set(
    df=df,
    feature_lookups=feature_lookups,
    label='rating',
    exclude_columns=['customer_id', 'product_id']
  )

  training_df = training_set.load_df().toPandas()

  # "training_df" columns ['total_purchases_30d', 'category', 'rating']
  X_train = training_df.drop(['rating'], axis=1)
  y_train = training_df.rating

  model = linear_model.LinearRegression().fit(X_train, y_train)

  fs.log_model(
    model=model,
    artifact_path="recommendation_model",
    flavor=mlflow.sklearn,
    training_set=training_set,
    registered_model_name="recommendation_model"
  )

# Batch inference

# If the model at model_uri is packaged with the features, the FeatureStoreClient.score_batch()
# call automatically retrieves the required features from Feature Store before scoring the model.
# The DataFrame returned by score_batch() augments batch_df with
# columns containing the feature values and a column containing model predictions.

fs = FeatureStoreClient()

# batch_df has columns ‘customer_id’ and ‘product_id’
predictions = fs.score_batch(
    model_uri=model_uri,
    df=batch_df
)

# The ‘predictions’ DataFrame has these columns:
# ‘customer_id’, ‘product_id’, ‘total_purchases_30d’, ‘category’, ‘prediction’

Özellik meta verileriyle paketlenmiş bir modeli puanlarken özel özellik değerlerini kullanma

Varsayılan olarak, özellik meta verileriyle paketlenmiş bir model, çıkarım sırasında özellik tablolarındaki özellikleri arar. Puanlama için özel özellik değerlerini kullanmak için, bunları geçirilen DataFrame'e FeatureEngineeringClient.score_batch (Unity Kataloğu'nda Özellik Mühendisliği için) veya FeatureStoreClient.score_batch (Çalışma Alanı Özellik Deposu için) ekleyin.

Örneğin, bir modeli şu iki özellik ile paketlediğiniz varsayılmaktadır:

Unity kataloğunda özellik mühendisliği

feature_lookups = [
    FeatureLookup(
      table_name='ml.recommender_system.customer_features',
      feature_names=['account_creation_date', 'num_lifetime_purchases'],
      lookup_key='customer_id',
    ),
  ]

Çalışma alanı özellik deposu

feature_lookups = [
    FeatureLookup(
      table_name='recommender_system.customer_features',
      feature_names=['account_creation_date', 'num_lifetime_purchases'],
      lookup_key='customer_id',
    ),
  ]

Çıkarım sırasında, adlı account_creation_datebir sütun içeren bir DataFrame'de arayarak score_batch özellik account_creation_date için özel değerler sağlayabilirsiniz. Bu durumda API yalnızca num_lifetime_purchases Özellik Deposu'ndaki özelliği arar ve model puanlaması için sağlanan özel account_creation_date sütun değerlerini kullanır.

Unity kataloğunda özellik mühendisliği

# batch_df has columns ['customer_id', 'account_creation_date']
predictions = fe.score_batch(
  model_uri='models:/ban_prediction_model/1',
  df=batch_df
)

Çalışma alanı özellik deposu

# batch_df has columns ['customer_id', 'account_creation_date']
predictions = fs.score_batch(
  model_uri='models:/ban_prediction_model/1',
  df=batch_df
)

Özellik Deposu özelliklerinin ve Özellik Deposu dışında bulunan verilerin birleşimini kullanarak modeli eğitin ve puanlayın

Özellik Deposu özelliklerinin ve verilerinin bir bileşimini kullanarak bir modeli, Özellik Deposu dışından eğitebilirsiniz. Modeli özellik meta verileriyle paketlediğinizde model, çıkarım için Özellik Deposu'ndan özellik değerlerini alır.

Modeli eğitmek için, ek verileri DataFrame'e FeatureEngineeringClient.create_training_set geçirilen sütun olarak ekleyin (Unity Kataloğu'nda Özellik Mühendisliği için) veya FeatureStoreClient.create_training_set (Çalışma Alanı Özellik Deposu için). Bu örnekte Özellik Deposu'ndan ve dış sütunundan browserözelliği total_purchases_30d kullanılır.

Unity kataloğunda özellik mühendisliği

feature_lookups = [
    FeatureLookup(
      table_name='ml.recommender_system.customer_features',
      feature_names=['total_purchases_30d'],
      lookup_key='customer_id',
    ),
  ]

fe = FeatureEngineeringClient()

# df has columns ['customer_id', 'browser', 'rating']
training_set = fe.create_training_set(
  df=df,
  feature_lookups=feature_lookups,
  label='rating',
  exclude_columns=['customer_id']  # 'browser' is not excluded
)

Çalışma alanı özellik deposu

feature_lookups = [
    FeatureLookup(
      table_name='recommender_system.customer_features',
      feature_names=['total_purchases_30d'],
      lookup_key='customer_id',
    ),
  ]

fs = FeatureStoreClient()

# df has columns ['customer_id', 'browser', 'rating']
training_set = fs.create_training_set(
  df=df,
  feature_lookups=feature_lookups,
  label='rating',
  exclude_columns=['customer_id']  # 'browser' is not excluded
)

Çıkarımda, içinde FeatureStoreClient.score_batch kullanılan DataFrame sütununu browser içermelidir.

Unity kataloğunda özellik mühendisliği

# At inference, 'browser' must be provided
# batch_df has columns ['customer_id', 'browser']
predictions = fe.score_batch(
  model_uri=model_uri,
  df=batch_df
)

Çalışma alanı özellik deposu

# At inference, 'browser' must be provided
# batch_df has columns ['customer_id', 'browser']
predictions = fs.score_batch(
  model_uri=model_uri,
  df=batch_df
)

MLflow kullanarak modelleri yükleme ve toplu çıkarım gerçekleştirme

Model (Unity Kataloğu'nda Özellik Mühendisliği için) veya FeatureStoreClient (Çalışma Alanı Özellik Deposu için) yöntemi FeatureEngineeringClient kullanılarak log_model günlüğe kaydedildikten sonra, çıkarım sırasında MLflow kullanılabilir. MLflow.pyfunc.predict Özellik Deposu'ndan özellik değerlerini alır ve çıkarım zamanında sağlanan tüm değerleri birleştirir. Modelde kullanılan özelliklerin birincil anahtarlarını sağlamanız gerekir.

Not

MLflow ile toplu çıkarım için MLflow sürüm 2.11 ve üzeri gerekir. Zaman serisi özellik tablolarını kullanan modeller desteklenmez. Zaman serisi özellik tablolarıyla toplu çıkarım yapmak için kullanın score_batch. Bkz. Modelleri eğitma ve özellik tablolarıyla toplu çıkarım gerçekleştirme.

# Train model
import mlflow
from sklearn import linear_model

feature_lookups = [
  FeatureLookup(
    table_name='ml.recommender_system.customer_features',
    feature_names=['total_purchases_30d'],
    lookup_key='customer_id',
  ),
  FeatureLookup(
    table_name='ml.recommender_system.product_features',
    feature_names=['category'],
    lookup_key='product_id'
  )
]

fe = FeatureEngineeringClient()

with mlflow.start_run():

  # df has columns ['customer_id', 'product_id', 'rating']
  training_set = fe.create_training_set(
    df=df,
    feature_lookups=feature_lookups,
    label='rating',
    exclude_columns=['customer_id', 'product_id']
  )

  training_df = training_set.load_df().toPandas()

  # "training_df" columns ['total_purchases_30d', 'category', 'rating']
  X_train = training_df.drop(['rating'], axis=1)
  y_train = training_df.rating

  model = linear_model.LinearRegression().fit(X_train, y_train)

  fe.log_model(
    model=model,
    artifact_path="recommendation_model",
    flavor=mlflow.sklearn,
    training_set=training_set,
    registered_model_name="recommendation_model",
    #refers to the default value of "result_type" if not provided at inference
    params={"result_type":"double"},
  )

# Batch inference with MLflow

# NOTE: the result_type parameter can only be used if a default value
# is provided in log_model. This is automatically done for all models
# logged using Databricks Runtime for ML 15.0 or above.
# For earlier Databricks Runtime versions, use set_result as shown below.

# batch_df has columns ‘customer_id’ and ‘product_id’
model = mlflow.pyfunc.load_model(model_version_uri)

# If result_type parameter is provided in log_model
predictions = model.predict(df, {"result_type":"double"})

# If result_type parameter is NOT provided in log_model
model._model_impl.set_result_type("double")
predictions = model.predict(df)