آزمایشگاه کد رگرسیون خطی

۱. مقدمه

این آزمایشگاه کد به شما آموزش می‌دهد که چگونه از رگرسیون خطی برای ایجاد مدلی استفاده کنید که هزینه به ازای هر کلیک را پیش‌بینی می‌کند.

پیش‌نیازها

برای تکمیل این آزمایشگاه کد، به داده‌های کمپین با کیفیت بالا و کافی برای ایجاد یک مدل نیاز دارید.

۲. ایجاد یک جدول موقت

کوئری زیر را اجرا کنید

CREATE TABLE
 linear_regression_example_data
AS(
 WITH all_data AS (
   SELECT
     imp.user_id as user_id,
     ROW_NUMBER() OVER(PARTITION BY imp.user_id) AS rowIdx,
     imp.browser AS browser_name,
     gender_name AS gender_name,
     age_group_name AS age_group_name,
     DATETIME(TIMESTAMP_MICROS(
       imp.query_id.time_usec), "America/Los_Angeles") as impression_time,
     clk.advertiser_click_cost_usd AS label
   FROM adh.google_ads_impressions imp
     INNER JOIN adh.google_ads_creative_conversions clk USING (impression_id)
     LEFT JOIN adh.gender ON demographics.gender = gender_id
     LEFT JOIN adh.age_group ON demographics.age_group = age_group_id
 )
 # Need just one user ID or regression won't work
 SELECT
   label,
   browser_name,
   gender_name,
   age_group_name,
   # Although BQML could divide impression_time into several useful variables on
   # its own, it may attempt to divide it into too many features. As a best
   # practice extract the variables that you think will be most helpful.
   # The output of impression_time is a number, but we care about it as a
   # category, so we cast it to a string.
   CAST(EXTRACT(DAYOFWEEK FROM impression_time) AS STRING) AS day_of_week,
   CAST(EXTRACT(HOUR FROM impression_time) AS STRING) AS hour,
 FROM
   all_data
 WHERE
   rowIdx = 1 # This ensures that there's only 1 row per user.
   AND
   label IS NOT NULL
   AND
   gender_name IS NOT NULL
   AND
   age_group_name IS NOT NULL
);

۳. ایجاد و آموزش یک مدل

بهتر است مراحل ایجاد جدول را از مراحل ایجاد مدل جدا کنید.

کوئری زیر را روی جدول موقت که در مرحله قبل ایجاد کردید، اجرا کنید. نگران ارائه تاریخ شروع و پایان نباشید، زیرا این تاریخ‌ها بر اساس داده‌های موجود در جدول موقت استنباط می‌شوند.

CREATE OR REPLACE
MODEL `example_linear`
OPTIONS(
   model_type = 'adh_linear_regression'
)
AS (
   SELECT *
   FROM
       tmp.linear_regression_example_data
);

SELECT * FROM ML.EVALUATE(MODEL `example_linear`)

ردیف

خطای_مطلق_میانگین

میانگین_مربع_خطا

میانگین مربعات_ورود_خطا

خطای_مطلق_میانه

امتیاز r2

واریانس_توضیح_داده‌شده

۱

۰.۱۱۱۰۲۳۸۰۶۶۶۸۷۴۱۰۷

۰.۰۱۹۹۳۸۹۷۲۴۶۱۵۶۹۴۷۶

۰.۰۱۹۵۰۳۳۹۳۴۴۸۲۳۴۱۳۱

۰.۰۹۱۷۹۲۰۲۴۵۰۳۵۶۲۱۳۶

‎-9.8205955364568478

‎-9.7975398794423025