【实战】用机器学习来提升你的用户增长
作者:Bar?? KaramanFollow??編譯:ronghuaiyang
正文共:10130?字 24 圖
預計閱讀時間:29 分鐘
導讀
這一系列的文章通過了一個實際的案例,向大家介紹了如何使用機器學習的方式來對公司的用戶增長做提升,如果你對用戶增長這部分不是很了解的話,這篇文章會帶你走過整個流程,包括了數據分析,編程,以及機器學習各個方面。
第一部分:了解你的指標
我們都記得加勒比海盜中杰克船長的著名的羅盤,它顯示了他最想要的東西的位置。在我們的用戶增長中,沒有北極星指標,這就是我們的增長方式。我們想要更多的客戶,更多的訂單,更多的收入,更多的注冊,更高的效率……
在寫代碼之前,我們需要了解究竟什么是北極星指標。如果你已經了解并跟蹤了北極星指標,這篇文章可以幫助您你入分析Python。如果你不知道,首先你應該找到你的北極星指標(可能你已經在跟蹤它,但沒有把它命名為北極星指標)。Sean Ellis是這樣描述的:
北極星指標是指可以最好的抓住你的產品交付給客戶的核心價值的單個指標。
這個指標取決于你公司的產品、定位、目標等等。Airbnb的北極星指標是預定的天數,而Facebook的指標是每日活躍用戶數。
在我們的例子中,我們會使用一個在線零售的數據集。對于在線零售,我們可以選擇我們的月收入作為北極星指標。
月收入
讓我們從導入我們需要的庫開始,然后使用pandas從CSV中讀取數據:
#?import?libraries from?datetime?import?datetime,?timedelta import?pandas?as?pd %matplotlib?inline import?matplotlib.pyplot?as?plt import?numpy?as?np import?seaborn?as?sns from?__future__?import?divisionimport?plotly.plotly?as?py import?plotly.offline?as?pyoff import?plotly.graph_objs?as?go#initiate?visualization?library?for?jupyter?notebook? pyoff.init_notebook_mode()tx_data?=?pd.read_csv('data.csv')tx_data.head(10)我們的數據看起來是這樣的:
我們有我們需要的所有重要信息:
客戶ID
單價
數量
訂單日期
有了所有這些特征,我們可以建立我們的北極星指標方程:
月收入 = 活躍用戶數量 * 訂單數量 * 平均訂單價格
我們現在可以動手試試了。我們希望看到每月的收入,但不幸的是,沒有免費的午餐。我們對數據做一些處理:
#converting?the?type?of?Invoice?Date?Field?from?string?to?datetime. tx_data['InvoiceDate']?=?pd.to_datetime(tx_data['InvoiceDate'])#creating?YearMonth?field?for?the?ease?of?reporting?and?visualization tx_data['InvoiceYearMonth']?=?tx_data['InvoiceDate'].map(lambda?date:?100*date.year?+?date.month)#calculate?Revenue?for?each?row?and?create?a?new?dataframe?with?YearMonth?-?Revenue?columns tx_data['Revenue']?=?tx_data['UnitPrice']?*?tx_data['Quantity'] tx_revenue?=?tx_data.groupby(['InvoiceYearMonth'])['Revenue'].sum().reset_index() tx_revenue好了,現在我們有了一個顯示我們每月收入的dataframe:
下一步,可視化,畫個折線圖就可以了:
這清楚地表明我們的收入在增長,尤其是在2011年8月11日以后(我們12月的數據是不完整的)。絕對數字是好的,讓我們看看我們的月收入增長率是多少:
一切看起來都很好,上個月我們看到了36.5%的增長(12月沒有包含在代碼中,因為它還沒有完成)。但我們需要看看4月份到底發生了什么。是由于客戶的活躍度降低,還是我們的客戶的訂單減少?也許他們只是開始買更便宜的產品了?如果不做深入的分析,我們什么也不知道。
月活躍客戶
要查看每月活躍客戶的詳細信息,我們將按照我們對每月收入所做的步驟進行操作。從這一部分開始,我們將只關注英國的數據(記錄最多的國家)。我們可以通過計算唯一的CustomerIDs來獲得每月的活躍客戶。代碼和輸出如下:
#creating?a?new?dataframe?with?UK?customers?only tx_uk?=?tx_data.query("Country=='United?Kingdom'").reset_index(drop=True)#creating?monthly?active?customers?dataframe?by?counting?unique?Customer?IDs tx_monthly_active?=?tx_uk.groupby('InvoiceYearMonth')['CustomerID'].nunique().reset_index()#print?the?dataframe tx_monthly_active#plotting?the?output plot_data?=?[go.Bar(x=tx_monthly_active['InvoiceYearMonth'],y=tx_monthly_active['CustomerID'],) ]plot_layout?=?go.Layout(xaxis={"type":?"category"},title='Monthly?Active?Customers')fig?=?go.Figure(data=plot_data,?layout=plot_layout) pyoff.iplot(fig)每個月的活躍客戶以及柱狀圖:
4月份,月活躍客戶數量從923個降至817個(-11.5%)。我們還會看到訂單數量的同樣趨勢。
月訂單數量
我們對 Quantity字段使用同樣的代碼:
#create?a?new?dataframe?for?no.?of?order?by?using?quantity?field tx_monthly_sales?=?tx_uk.groupby('InvoiceYearMonth')['Quantity'].sum().reset_index()#print?the?dataframe tx_monthly_sales#plot plot_data?=?[go.Bar(x=tx_monthly_sales['InvoiceYearMonth'],y=tx_monthly_sales['Quantity'],) ]plot_layout?=?go.Layout(xaxis={"type":?"category"},title='Monthly?Total?#?of?Order')fig?=?go.Figure(data=plot_data,?layout=plot_layout) pyoff.iplot(fig)月訂單數量以及柱狀圖:
正如我們所預期的,4月份的訂單數量也下降了(279k到257k,下降了8%)。
我們知道活躍客戶數量直接影響訂單數量的減少。最后,我們還應該檢查一下我們的平均訂單收入。
平均訂單收入
為了得到這個數據,我們需要計算每個月的平均訂單收入:
#?create?a?new?dataframe?for?average?revenue?by?taking?the?mean?of?it tx_monthly_order_avg?=?tx_uk.groupby('InvoiceYearMonth')['Revenue'].mean().reset_index()#print?the?dataframe tx_monthly_order_avg#plot?the?bar?chart plot_data?=?[go.Bar(x=tx_monthly_order_avg['InvoiceYearMonth'],y=tx_monthly_order_avg['Revenue'],) ]plot_layout?=?go.Layout(xaxis={"type":?"category"},title='Monthly?Order?Average') fig?=?go.Figure(data=plot_data,?layout=plot_layout) pyoff.iplot(fig)月平均訂單收入以及柱狀圖:
甚至4月份的月平均訂單量也下降了(16.7至15.8)。我們觀察到影響北極星指標的每一個指標都在下降。
我們已經看到了我們的主要指標。當然還有很多不同的指標,根據行業的不同。讓我們繼續研究其他一些重要的指標:
新客戶比例:如果我們正在失去現有的客戶或無法吸引新的客戶,這是一個很好的指標
留存率:指標之王。指示在特定時間段內我們保留了多少客戶。我們將展示月度留存率和基于群組的留存率的例子。
新客戶比例
首先,我們應該定義什么是新客戶。在我們的數據集中,我們可以假設新客戶是在我們定義的時間窗口中進行第一次購買的人。對于這個例子,我們將按月執行。
我們將使用**.min()**函數來查找每個客戶的首次購買日期,并在此基礎上定義新客戶。下面的代碼將應用此函數,并向我們顯示每個組每月的收入明細。
#create?a?dataframe?contaning?CustomerID?and?first?purchase?date tx_min_purchase?=?tx_uk.groupby('CustomerID').InvoiceDate.min().reset_index() tx_min_purchase.columns?=?['CustomerID','MinPurchaseDate'] tx_min_purchase['MinPurchaseYearMonth']?=?tx_min_purchase['MinPurchaseDate'].map(lambda?date:?100*date.year?+?date.month)#merge?first?purchase?date?column?to?our?main?dataframe?(tx_uk) tx_uk?=?pd.merge(tx_uk,?tx_min_purchase,?on='CustomerID')tx_uk.head()#create?a?column?called?User?Type?and?assign?Existing? #if?User's?First?Purchase?Year?Month?before?the?selected?Invoice?Year?Month tx_uk['UserType']?=?'New' tx_uk.loc[tx_uk['InvoiceYearMonth']>tx_uk['MinPurchaseYearMonth'],'UserType']?=?'Existing'#calculate?the?Revenue?per?month?for?each?user?type tx_user_type_revenue?=?tx_uk.groupby(['InvoiceYearMonth','UserType'])['Revenue'].sum().reset_index()#filtering?the?dates?and?plot?the?result tx_user_type_revenue?=?tx_user_type_revenue.query("InvoiceYearMonth?!=?201012?and?InvoiceYearMonth?!=?201112") plot_data?=?[go.Scatter(x=tx_user_type_revenue.query("UserType?==?'Existing'")['InvoiceYearMonth'],y=tx_user_type_revenue.query("UserType?==?'Existing'")['Revenue'],name?=?'Existing'),go.Scatter(x=tx_user_type_revenue.query("UserType?==?'New'")['InvoiceYearMonth'],y=tx_user_type_revenue.query("UserType?==?'New'")['Revenue'],name?=?'New') ]plot_layout?=?go.Layout(xaxis={"type":?"category"},title='New?vs?Existing') fig?=?go.Figure(data=plot_data,?layout=plot_layout) pyoff.iplot(fig)與首次購買日期合并后的Dataframe的輸出:
新客戶和現有客戶的月收入:
把上面畫成圖表:
現有客戶顯示出正的趨勢,并告訴我們,我們的客戶群正在增長,但新客戶有輕微的下降趨勢。
讓我們來看看新客戶比例:
#create?a?dataframe?that?shows?new?user?ratio?-?we?also?need?to?drop?NA?values?(first?month?new?user?ratio?is?0) tx_user_ratio?=?tx_uk.query("UserType?==?'New'").groupby(['InvoiceYearMonth'])['CustomerID'].nunique()/tx_uk.query("UserType?==?'Existing'").groupby(['InvoiceYearMonth'])['CustomerID'].nunique()? tx_user_ratio?=?tx_user_ratio.reset_index() tx_user_ratio?=?tx_user_ratio.dropna()#print?the?dafaframe tx_user_ratio#plot?the?resultplot_data?=?[go.Bar(x=tx_user_ratio.query("InvoiceYearMonth>201101?and?InvoiceYearMonth<201112")['InvoiceYearMonth'],y=tx_user_ratio.query("InvoiceYearMonth>201101?and?InvoiceYearMonth<201112")['CustomerID'],) ]plot_layout?=?go.Layout(xaxis={"type":?"category"},title='New?Customer?Ratio') fig?=?go.Figure(data=plot_data,?layout=plot_layout) pyoff.iplot(fig)新客戶比例如預期般下降(我們在2月時假設所有客戶都是新客戶),并在20%左右。
月留存率
留存率應該被密切監控,因為它表明了你的服務的黏性,你的產品有多適合市場。為了使月留存率可視化,我們需要計算上個月留存了多少客戶。
月留存率 = 上個月的留存客戶/總的活躍客戶
我們使用pandas中的crosstab()函數,可以非常簡單的算出留存率:
#identify?which?users?are?active?by?looking?at?their?revenue?per?month tx_user_purchase?=?tx_uk.groupby(['CustomerID','InvoiceYearMonth'])['Revenue'].sum().reset_index()#create?retention?matrix?with?crosstab tx_retention?=?pd.crosstab(tx_user_purchase['CustomerID'],?tx_user_purchase['InvoiceYearMonth']).reset_index()tx_retention.head()#create?an?array?of?dictionary?which?keeps?Retained?&?Total?User?count?for?each?month months?=?tx_retention.columns[2:] retention_array?=?[] for?i?in?range(len(months)-1):retention_data?=?{}selected_month?=?months[i+1]prev_month?=?months[i]retention_data['InvoiceYearMonth']?=?int(selected_month)retention_data['TotalUserCount']?=?tx_retention[selected_month].sum()retention_data['RetainedUserCount']?=?tx_retention[(tx_retention[selected_month]>0)?&?(tx_retention[prev_month]>0)][selected_month].sum()retention_array.append(retention_data)#convert?the?array?to?dataframe?and?calculate?Retention?Rate tx_retention?=?pd.DataFrame(retention_array) tx_retention['RetentionRate']?=?tx_retention['RetainedUserCount']/tx_retention['TotalUserCount']#plot?the?retention?rate?graph plot_data?=?[go.Scatter(x=tx_retention.query("InvoiceYearMonth<201112")['InvoiceYearMonth'],y=tx_retention.query("InvoiceYearMonth<201112")['RetentionRate'],name="organic")]plot_layout?=?go.Layout(xaxis={"type":?"category"},title='Monthly?Retention?Rate') fig?=?go.Figure(data=plot_data,?layout=plot_layout) pyoff.iplot(fig)首先,我們創建一個dataframe,顯示每個客戶的每月總收入:
用**crosstab()**函數轉換成留存表:
留存表顯示了每個月哪些客戶是活躍的(1代表活躍)。
用一個簡單的for循環,對于每個月,我們計算前一個月的留存客戶數量和總客戶數量。
最后,我們得到了我們的留存率dataframe以及折線圖,如下:
月留存率從6月到8月顯著上升,之后又回到以前的水平。
基于群體的留存率
還有另一種度量留存率的方法可以讓你看到每個群體的留存率。這個群體被定義為客戶的第一次購買年份-月份。我們將度量每個月第一次購買后留存客戶的比例。這個視圖將幫助我們了解最近的和過去的客戶群體在留存率方面有何不同,以及最近的客戶體驗變化是否影響了新客戶的留存率。
在代碼方面,要比其他的復雜一些。
#create?our?retention?table?again?with?crosstab()?-?we?need?to?change?the?column?names?for?using?them?in?.query()?function tx_retention?=?pd.crosstab(tx_user_purchase['CustomerID'],?tx_user_purchase['InvoiceYearMonth']).reset_index() new_column_names?=?[?'m_'?+?str(column)?for?column?in?tx_retention.columns] tx_retention.columns?=?new_column_names#create?the?array?of?Retained?users?for?each?cohort?monthly retention_array?=?[] for?i?in?range(len(months)):retention_data?=?{}selected_month?=?months[i]prev_months?=?months[:i]next_months?=?months[i+1:]for?prev_month?in?prev_months:retention_data[prev_month]?=?np.nantotal_user_count?=??retention_data['TotalUserCount']?=?tx_retention['m_'?+?str(selected_month)].sum()retention_data[selected_month]?=?1?query?=?"{}?>?0".format('m_'?+?str(selected_month))for?next_month?in?next_months:query?=?query?+?"?and?{}?>?0".format(str('m_'?+?str(next_month)))retention_data[next_month]?=?np.round(tx_retention.query(query)['m_'?+?str(next_month)].sum()/total_user_count,2)retention_array.append(retention_data)tx_retention?=?pd.DataFrame(retention_array) tx_retention.index?=?months#showing?new?cohort?based?retention?table tx_retentionTx_retention就是這個基于群體的留存率視圖:
我們可以看到,第一個月的客戶留存率最近變得更好了(不考慮12月11日),在近1年的時間里,只有7%的客戶留了下來。
現在,我們知道了我們的度量標準以及如何使用Python跟蹤/分析它們。
代碼鏈接:https://gist.github.com/karamanbk/314d3d5483b9be1d2cc7f9694368f3bc
后面,我們會嘗試劃分我們的客戶,看看哪些是最好的客戶。
—END—
英文原文:https://towardsdatascience.com/data-driven-growth-with-python-part-1-know-your-metrics-812781e66a5b
往期精彩回顧適合初學者入門人工智能的路線及資料下載機器學習在線手冊深度學習在線手冊AI基礎下載(pdf更新到25集)本站qq群1003271085,加入微信群請回復“加群”獲取一折本站知識星球優惠券,復制鏈接直接打開:https://t.zsxq.com/yFQV7am喜歡文章,點個在看
總結
以上是生活随笔為你收集整理的【实战】用机器学习来提升你的用户增长的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何画出几种常见二分类损失函数(附代码)
- 下一篇: 【基础】pandas中apply与map