使用機器學習預測客戶下次購買
在競爭激烈的市場中,留住客戶對於成功至關重要。留住現有客戶比獲取新客戶更經濟有效。客戶留存率帶來忠誠的客戶群體、更高的收入和長期的盈利能力。然而,許多因素,包括經濟狀況、競爭和時尚趨勢,使得預測客戶行為和偏好變得困難。為了應對這些挑戰,企業需要利用先進的機器學習和資料分析能力來分析客戶資料並做出準確預測。透過預測客戶的下次購買,企業可以調整營銷策略,改進客戶體驗,提高客戶滿意度,最終提高留存率和忠誠度。在本文中,我們將運用機器學習來預測讀者的下次購買。
使用機器學習預測客戶下次購買
以下是使用機器學習預測客戶即將購買的逐步指南:
透過載入資料、進行特徵工程、資料清洗和匯入必要的庫來收集和準備資料
從資料中建立訓練集和測試集。
利用訓練資料,建立一個隨機森林迴歸模型
使用多種指標評估模型的效能,包括解釋方差得分、R方、平均絕對誤差和均方誤差。
演算法
匯入必要的庫,包括datetime、numpy和pandas。
使用pd.read_excel()載入資料,然後將其儲存為DataFrame。
刪除任何缺少CustomerID的條目,因為如果沒有CustomerID,我們就無法預測客戶的下次購買。為此,使用df = df[df['CustomerID'].notna()]。
刪除任何數量為0或值為負的記錄,因為這些記錄可能不正確。為此使用的公式是df = df[df['Quantity'] > 0]。
刪除任何價格為負或為零的條目,因為這些也可能是錯誤的。為此使用的公式是df = df[df['UnitPrice'] > 0]。
使用pd.to_datetime()將InvoiceDate列轉換為datetime物件。
TotalPrice,它是數量和價格列的結果,表示每次交易的總成本。
每次交易的年份和月份在InvoiceYearMonth列中找到,該列是從InvoiceDate列派生的。
LastPurchaseDate - 每個客戶上次購買的日期。
DaysSinceLastPurchase - 自每個客戶上次購買以來已經過去了多少天
NextPurchaseDate是一個隨機選擇的日期,介於客戶上次購買後的7到30天之間。
DaysUntilNextPurchase - 每個客戶下次購買之前的持續時間。
選擇CustomerID、TotalPrice、InvoiceYearMonth、DaysSinceLastPurchase和DaysUntilNextPurchase作為我們希望用於訓練模型的列
使用df = df.drop_duplicates()刪除任何重複的行。
收集和準備資料
在這個階段,我們獲取資料並進行必要的特徵工程和資料清洗。UCI機器學習資源庫在這裡公開提供線上零售資料集,我們可以將其用於此專案。
# Import libraries
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, explained_variance_score
# Step 1: Gather and Prepare the Data
df = pd.read_excel('/content/sample_data/online_retail_II.xlsx')
df = df[df['Customer ID'].notna()] # Remove rows without CustomerID
df = df[df['Quantity'] > 0] # Remove rows with negative or zero quantity
df = df[df['Price'] > 0] # Remove rows with negative or zero price
# Parse dates
df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])
# Create features
df['TotalPrice'] = df['Quantity'] * df['Price']
df['InvoiceYearMonth'] = df['InvoiceDate'].apply(lambda x: x.strftime('%Y%m'))
df['LastPurchaseDate'] = df.groupby('Customer ID')['InvoiceDate'].transform('max')
df['DaysSinceLastPurchase'] = (df['LastPurchaseDate'].max() - df['LastPurchaseDate']).dt.days
df['NextPurchaseDate'] = df.groupby('Customer ID')['InvoiceDate'].transform(lambda x: x.max() + timedelta(days=np.random.randint(7, 30)))
df['DaysUntilNextPurchase'] = (df['NextPurchaseDate'] - df['InvoiceDate']).dt.days
df = df[['Customer ID', 'TotalPrice', 'InvoiceYearMonth', 'DaysSinceLastPurchase', 'DaysUntilNextPurchase']]
df = df.drop_duplicates()
將資料分成訓練集和測試集
使用公式X = df.drop(['DaysUntilNextPurchase'], axis=1)和y = df['DaysUntilNextPurchase']將自變數(X)與因變數(y)分開。
利用train_test_split()將資料分成訓練集和測試集。我們指定隨機狀態為42,測試大小為0.2,即20%。
在這個階段,我們將資料分成訓練集和測試集。
# Step 2 − Split the Data into Training and Testing Sets X = df.drop(['DaysUntilNextPurchase'], axis=1) y = df['DaysUntilNextPurchase'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
訓練機器學習模型
應匯入sklearn.ensemble的RandomForestRegressor類。
將n_estimators設定為100,並將random_state設定為42,建立一個新的類例項。
Model.fit(X_train, y_train)將模型擬合到訓練資料。
基於訓練資料,我們現在訓練一個隨機森林迴歸模型。
# Step 3 − Train the Machine Learning Model model = RandomForestRegressor(n_estimators=100, random_state=42) model.fit(X_train, y_train)
評估模型
model.predict(X_test)使用學習到的模型根據測試資料做出預測。
使用mean_absolute_error(y_test, y_pred)計算平均絕對誤差(MAE)。
均方誤差(MSE)可以使用公式mean_squared_error(y_test, y_pred)計算。
R方(R2)可以使用公式r2_score(y_test, y_pred)計算。
此時,我們使用一系列指標來評估模型的有效性。
# Step 4− Evaluate the Model
y_pred = model.predict(X_test)
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
evs = explained_variance_score(y_test, y_pred)
print('Mean Absolute Error:', mae)
print('Mean Squared Error:', mse)
print('R-squared:', r2)
print('Explained Variance Score:', evs)
結果
Mean Absolute Error− 2.8361809953950248 Mean Squared Error − 31.313248452439648 R-squared − 0.9975804147472181 Explained Variance Score − 0.9975804233638988
均方誤差(MSE)計算預期值和實際值之間的平均差異。R2統計量表示模型解釋的目標變數變化的百分比。與總體方差相比,EVS計算模型解釋的目標變數變化的百分比。
結論
總之,本文中使用的方法包括獲取和處理客戶資料、將其分成訓練集和測試集、訓練機器學習模型以及使用多種指標評估模型的效能。預測客戶的下次購買,可以有多種潛在用途,例如個性化營銷策略、改進客戶體驗和提高客戶留存率。
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP