Ingenieurfunktionen für maschinelles Lernen
In diesem Dokument wird gezeigt, wie Sie Daten in Adobe Experience Platform in Funktionen oder Variablen umwandeln können, die von einem maschinellen Lernmodell genutzt werden können. Dieser Prozess wird als „Feature ". Verwenden Sie Data Distiller, um ML-Funktionen im benötigten Umfang zu berechnen und diese Funktionen für Ihre maschinelle Lernumgebung freizugeben. Dies umfasst Folgendes:
- Erstellen Sie eine Abfragevorlage, um die Zielbeschriftungen und -funktionen zu definieren, die Sie für Ihr Modell berechnen möchten
- Ausführen der Abfrage und Speichern der Ergebnisse in einem Trainings-Datensatz
Definieren von Schulungsdaten define-training-data
Das folgende Beispiel zeigt eine Abfrage zum Ableiten von Schulungsdaten aus einem Erlebnisereignis-Datensatz für ein Modell, um die Neigung eines Benutzers vorherzusagen, einen Newsletter zu abonnieren. Abonnementereignisse werden durch den Ereignistyp web.formFilledOut dargestellt. Andere Verhaltensereignisse im Datensatz werden verwendet, um Funktionen auf Profilebene abzuleiten und Abonnements vorherzusagen.
Abfrage von positiven und negativen Kennzeichnungen query-positive-and-negative-labels
Ein vollständiger Datensatz für das Training eines (überwachten) Modells für maschinelles Lernen enthält eine Zielvariable oder -bezeichnung, die das vorherzusagende Ergebnis darstellt, und einen Satz von Funktionen oder erklärenden Variablen, die zur Beschreibung der Beispielprofile verwendet werden, die zum Trainieren des Modells verwendet werden.
In diesem Fall ist die Bezeichnung eine Variable mit der Bezeichnung subscriptionOccurred , die gleich 1 ist, wenn das Benutzerprofil ein Ereignis mit dem Typ web.formFilledOut hat, andernfalls ist es 0. Die folgende Abfrage gibt einen Satz von 50.000 Benutzern aus dem Ereignisdatensatz zurück, einschließlich aller Benutzer mit positiven Kennzeichnungen (subscriptionOccurred = 1) plus einem Satz zufällig ausgewählter Benutzer mit negativen Kennzeichnungen, um die Stichprobengröße von 50.000 Benutzern abzuschließen. Dadurch wird sichergestellt, dass die Trainings-Daten sowohl positive als auch negative Beispiele für das Modell enthalten, aus denen gelernt werden kann.
from aepp import queryservice
dd_conn = queryservice.QueryService().connection()
dd_cursor = queryservice.InteractiveQuery2(dd_conn)
query_labels = f"""
SELECT *
FROM (
SELECT
eventType,
_{tenant_id}.user_id as userId,
SUM(CASE WHEN eventType='web.formFilledOut' THEN 1 ELSE 0 END)
OVER (PARTITION BY _{tenant_id}.user_id)
AS "subscriptionOccurred",
row_number() OVER (PARTITION BY _{tenant_id}.user_id ORDER BY randn()) AS random_row_number_for_user
FROM {table_name}
)
WHERE (subscriptionOccurred = 1 AND eventType = 'web.formFilledOut') OR (subscriptionOccurred = 0 AND random_row_number_for_user = 1)
"""
df_labels = dd_cursor.query(query_labels, output="dataframe")
print(f"Number of classes: {len(df_labels)}")
df_labels.head()
Beispielausgabe
Anzahl Klassen: 50000
Aggregieren von Ereignissen zur Definition von Funktionen für ML define-features
Mit einer entsprechenden Abfrage können Sie die Ereignisse im Datensatz in aussagekräftigen numerischen Funktionen erfassen, die zum Trainieren eines Tendenzmodells verwendet werden können. Beispielereignisse werden unten angezeigt:
- Anzahl der E Mails, die zu Marketing-Zwecken gesendet und vom Benutzer empfangen wurden.
- Teil dieser E-Mails, die geöffnet wurden.
- Teil dieser E-Mails, bei dem der Benutzer ausgewählt den Link.
- Anzahl der Produkte die angezeigt wurden.
- Anzahl der Vorschläge, mit denen interagiert wurde.
- Anzahl abgelehnten Vorschläge.
- Anzahl ausgewählten Links.
- Anzahl der Minuten zwischen zwei aufeinander folgenden empfangenen E-Mails.
- Anzahl der Minuten zwischen zwei aufeinander folgenden geöffneten E-Mails
- Anzahl der Minuten zwischen zwei aufeinander folgenden E-Mails, in denen der Benutzer den Link tatsächlich ausgewählt hat.
- Anzahl der Minuten zwischen zwei aufeinander folgenden Produktansichten.
- Anzahl der Minuten zwischen zwei Vorschlägen, mit denen interagiert wurde.
- Anzahl der Minuten zwischen zwei abgelehnten Vorschlägen.
- Anzahl der Minuten zwischen zwei ausgewählten Links.
Die folgende Abfrage aggregiert diese Ereignisse:
| code language-python |
|---|
|
Beispielausgabe
Combine labels and features queries combine-queries
Finally, the labels query and the features query can be combined into a single query that returns a training dataset of labels and features:
| code language-python |
|---|
|
Beispielausgabe
Create a query template to incrementally compute training data
It is typical to periodically retrain a model with updated training data to maintain accuracy of the model over time. As a best practice for efficiently updating your training dataset, you can create a template from your training set query to compute new training data incrementally. This allows you compute labels and features only from data that was added to the original Experience Events dataset since the training data was last updated, and insert the new labels and features into the existing training dataset.
Doing so requires a few modifications to the training set query:
-
Add logic to create a new training dataset if it doesn't exist, and insert the new labels and features into the existing training dataset otherwise. This requires a series of two versions of the training set query:
- First, using the
CREATE TABLE IF NOT EXISTS {table_name} ASstatement - Next, using the
INSERT INTO {table_name}statement for the case where the training dataset already exists
- First, using the
-
Add a
SNAPSHOT BETWEEN $from_snapshot_id AND $to_snapshot_idstatement to limit the query to event data that was added within a specified interval. The$prefix on the snapshot IDs indicates that thy are variables that will be passed in when the query template is executed.
Applying those changes results in the following query:
| code language-python |
|---|
|
Finally, the following code saves the query template in Data Distiller:
template_res = dd.createQueryTemplate({
"sql": query_training_set_template,
"queryParameters": {},
"name": "Template for propensity training data"
})
template_id = template_res["id"]
print(f"Template for propensity training data created as ID {template_id}")
Beispielausgabe
Template for propensity training data created as ID f3d1ec6b-40c2-4d13-93b6-734c1b3c7235
With the template saved, you can execute the query at any time by referencing the template ID and specify the range of snapshot IDs that should be included in the query. The following query retrieves the snapshots of the original Experience Events dataset:
query_snapshots = f"""
SELECT snapshot_id
FROM (
SELECT history_meta('{table_name}')
)
WHERE is_current = true OR snapshot_generation = 0
ORDER BY snapshot_generation ASC
"""
df_snapshots = dd_cursor.query(query_snapshots, output="dataframe")
The following code demonstrates execution of the query template, using the first and last snapshots to query the entire dataset:
snapshot_start_id = str(df_snapshots["snapshot_id"].iloc[0])
snapshot_end_id = str(df_snapshots["snapshot_id"].iloc[1])
query_final_res = qs.postQueries(
name=f"[CMLE][Week2] Query to generate training data created by {username}",
templateId=template_id,
queryParameters={
"from_snapshot_id": snapshot_start_id,
"to_snapshot_id": snapshot_end_id,
},
dbname=f"{cat_conn.sandbox}:all"
)
query_final_id = query_final_res["id"]
print(f"Query started successfully and got assigned ID {query_final_id} - it will take some time to execute")
Beispielausgabe
Query started successfully and got assigned ID c6ea5009-1315-4839-b072-089ae01e74fd - it will take some time to execute
You can define the following function to periodically check the status of the query:
def wait_for_query_completion(query_id):
while True:
query_info = qs.getQuery(query_id)
query_state = query_info["state"]
if query_state in ["SUCCESS", "FAILED"]:
break
print("Query is still in progress, sleeping…")
time.sleep(60)
duration_secs = query_info["elapsedTime"] / 1000
if query_state == "SUCCESS":
print(f"Query completed successfully in {duration_secs} seconds")
else:
print(f"Query failed with the following errors:", file=sys.stderr)
for error in query_info["errors"]:
print(f"Error code {error['code']}: {error['message']}", file=sys.stderr)
wait_for_query_completion(query_final_id)
Beispielausgabe
Query is still in progress, sleeping…
Query is still in progress, sleeping…
Query is still in progress, sleeping…
Query is still in progress, sleeping…
Query is still in progress, sleeping…
Query is still in progress, sleeping…
Query is still in progress, sleeping…
Query is still in progress, sleeping…
Query completed successfully in 473.8 seconds
Next steps:
By reading this document you have learned how to transform data in Adobe Experience Platform into features, or variables, that can be consumed by a machine learning model. The next step in creating feature pipelines from Experience Platform to feed custom models in your machine learning environment is to export feature datasets.