Все компании имеют все больше и больше данных о клиентах, основанных на поведении, и простым, но мощным способом категоризации этих клиентов является сегментация RFM. Сегментация RFM — это решение для разделения наших клиентов на сегменты (кластеры) в соответствии с их поведением, таким как давность, частота и денежная стоимость.

Сегментация RFM позволит нам:

  • Стратегия сегментации клиентов
  • Запускайте автоматические маркетинговые кампании
  • Создавайте более эффективные кампании ремаркетинга

Цель этого метода состоит в том, чтобы классифицировать наших клиентов по сегментам с использованием трех переменных: Давность, Частота и Денежная стоимость (отсюда и название RFM).

Сегодня модель RFM используется цифровыми маркетологами для отправки релевантных маркетинговых сообщений, поддержания вовлеченности своих клиентов и максимизации пожизненной ценности каждого клиента.
Сегментация RFM должна быть одной из первых сегментаций клиентов любой организации.

RFM-сегментация

Итак, здесь мы объясним все шаги, необходимые для успешной сегментации RFM.
Здесь мы будем использовать набор данных реальных клиентов с 31 переменной, описывающий 83 590 экземпляров (клиентов) из отеля в Лиссабоне, Португалия.
Вы можете скачать файлы данных оттуда (возможно, вам придется авторизоваться перед загрузкой).

Весь скрипт этой статьи находится там.

  1. Вычислите показатель RFM
    Здесь у нас есть два источника дохода, LodgingRevenue и OtherRevenue, поэтому мы должны создать новую переменную «Monetary_value», которая представляет собой сумму двух других.
    Затем мы сохраняем только минимальное значение «DaysSinceLastStay» в качестве давности.
    Наконец, мы подсчитываем количество резервирований, чтобы получить частотную переменную.
############################################################
# We keep only some variable for the segmentation
############################################################
colonnes_RFM = ['DocIDHash','ID', 'LodgingRevenue','OtherRevenue',    
                'DaysSinceLastStay']
df_rfm = df[colonnes_RFM]
############################################################
# Create Recency variable
############################################################
df_rfm.rename(columns={'DaysSinceLastStay':'recency'}, inplace=True)
rfm = pd.merge(rfm, df_rfm.groupby(['DocIDHash'])[['recency']].\
               .min().reset_index(), how='inner', on='DocIDHash')
############################################################
# Create Frequency variable
############################################################
rfm = df_rfm.groupby(['DocIDHash'])[['ID']].nunique().\
                    reset_index().rename(columns={'ID':'frequency'})
############################################################
# Create Monetary Value variable
############################################################
df_rfm['monetary_value'] = df_rfm['LodgingRevenue'] +   
                           df_rfm['OtherRevenue']
rfm = pd.merge(rfm, df_rfm.groupby(['DocIDHash'])\. 
            [['monetary_value']].sum().reset_index(), how='inner',       
            on='DocIDHash')
############################################################
# Then we compute quantiles
############################################################
quantiles = rfm.quantile(q=[0.20,0.40, 0.60,0.80])
quantiles = quantiles.to_dict()
############################################################
# This two function to cast the continues variables Recency, 
# Frequency and Monetary Value to discontinues variables
############################################################
# Convert recency variable
def RClass(x,p,d):
    if x <= d[p][0.2]:
        return 1
    elif x <= d[p][0.40]:
        return 2
    elif x <= d[p][0.60]:
        return 3
    elif x <= d[p][0.8]:
        return 4
    else:
        return 5

# Convert Frequency and Monetary Value variables
def FMClass(x,p,d):
    if x <= d[p][0.20]:
        return 5
    elif x <= d[p][0.40]:
        return 4
    elif x <= d[p][0.60]:
        return 3
    elif x <= d[p][0.80]:
        return 2
    else:
        return 1

# Create New discontinue variables from continues ones
rfm['R_Quartile'] = rfm['recency'].apply(RClass, args=
                                   ('recency',quantiles,))
rfm['F_Quartile'] = rfm['frequency'].apply(FMClass, args=
                                   ('frequency',quantiles,))
rfm['M_Quartile'] = rfm['monetary_value'].apply(FMClass, args=
                                   ('monetary_value',quantiles,))
############################################################
# Get The RFM Score
############################################################
rfm['RFMScore'] = rfm['R_Quartile'].astype('str') +  
                  rfm['F_Quartile'].astype('str') + 
                  rfm['M_Quartile'].astype('str')

RFM Scores позволяет вам создавать классы, которые позволят вашей команде посмотреть, как часто клиент совершает покупки у вас и насколько они ценны.
Созданные шаблоны позволят вашей команде создавать очень персонализированные сообщения.

Итак, мы можем увидеть, сколько у нас клиентов по сегментам:

######################################################
# shape of each segment created
######################################################
rfm.groupby(['RFMScore'])['DocIDHash'].nunique().\
                     reset_index().rename(columns={'DocIDHash':'Nb 
                                          Customers'})
########### We get 
RFMScore  Nb Customers
111            85
112            69
113            78
...
315             5

Итак, как вы можете видеть, форма некоторых сегментов очень мала, и персонализированное маркетинговое сообщение для этих небольших сегментов может быть оптимизировано.
Решение состоит в том, чтобы объединить этот небольшой сегмент в более крупные сегменты:

╔═══════════╦══════════════════════════════════════════════════════╗
║ Segment   ║ Score                                                ║
╠═══════════╬══════════════════════════════════════════════════════╣
║ Champions ║111, 112, 122, 121, 212, 211, 221                     ║
║           ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║Give them something extra that the regulars do not get║
║           ║For example, limited series of products or special    ║           ║           ║discounts to make them feel valued : You might make   ║
║           ║them your ambassadors, giving them a margin of your   ║
║           ║profits for bringing you, new customers               ║ 
╠═══════════╬══════════════════════════════════════════════════════╣
║ Loyal     ║123, 222, 231, 311, 312, 321, 322,331
║           ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║Your goal for this segment is to make them even more  ║
║           ║satisfied to preserve their current behavior. As you  ║
║           ║know these customers well use highly personalized     ║
║           ║communication                                         ║
╠═══════════╬══════════════════════════════════════════════════════╣
║Potential  ║113, 115, 114, 125, 124, 133, 134, 135, 214, 215, 224,║
║Loyalist   ║225, 235, 213, 233, 234, 243, 313, 314, 315, 324,325, ║
║           ║333, 343                                              ║   
║           ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║These customers already bought from you more than once║ ║           ║but the size of their basket was not too big. Try to  ║
║           ║motivate them to increase the number of items in their║ ║           ║cart by showing them cross-selling recommendations.   ║
╠═══════════╬══════════════════════════════════════════════════════╣
║New        ║154, 155, 244, 245 254, 255, 355                      ║
║Customers  ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║Possibly this is their first purchase : You do not    ║ 
║           ║know these customers yet so they still have the       ║
║           ║potential to turn up as highly valuable.              ║
║           ║You should offer them discounts for an additional     ║
║           ║product to see whether they are the kinds of the      ║
║           ║customer to whom you can upsell.                      ║
╠═══════════╬══════════════════════════════════════════════════════╣
║Promising  ║141, 142, 143, 144, 145, 151, 152,153, 241,242, 253,  ║
║           ║252,251, 351, 352, 353                                ║
║           ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║Possibly this is their first purchase for high value: ║
║           ║You need to motivate them to make another purchase    ║ 
║           ║because it can be another high monetary value purchase║    ║           ║The high value they bring allow you to invest in this ║
║           ║segment to turn them into regular spenders.           ║
╠═══════════╬══════════════════════════════════════════════════════╣║Need       ║131, 132, 223, 232, 323, 332, 341, 342                ║
║Attention  ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║They are considering to buy a new product, and you    ║
║           ║should motivate them to choose you over competitors.  ║ 
║           ║You should communicate to this segment a time-limited ║    ║           ║promotional campaigns.                                ║
║           ║Use product recommendations based on their behavior to║
║           ║recommend a new product=> show them you know them.    ║
╠═══════════╬══════════════════════════════════════════════════════╣
║About To   ║335, 345, 354, 445, 453, 435, 425, 415                ║
║Sleep      ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║They don't make a purchase since a long time but they ║
║           ║still approachable using discounts. This discounts    ║ 
║           ║motivate them and revive their interest.              ║    
╠═══════════╬══════════════════════════════════════════════════════╣
║At Risk    ║411, 412, 421, 422, 413, 414, 423, 424, 431, 432, 441,║
║           ║442,513, 514, 521,  523, 524, 531, 532,533, 541,542   ║
║           ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║The customer value of the members of this segment is  ║
║           ║above average but thy don't made a purchase recently. ║ 
║           ║It's seems that they still buying products but from   ║    ║           ║your competitors.                                     ║
║           ║You should prepare discounts and gifts for this       ║
║           ║segments. They already give you high value so you can ║
║           ║invest on them. Use product-recommandation engine.    ║
╠═══════════╬══════════════════════════════════════════════════════╣
║Cannot     ║511, 512, 522, 452,451,551, 552, 553                  ║
║Lose Them  ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║This segments is similar to the above segment, the    ║
║           ║only difference is about the recency. This segment is ║ 
║           ║made a purchase less recently than 'At Risk' segment. ║    ║           ║Use the same strategy than the above segment but this ║
║           ║segment is less valuable than the above one.          ║
╠═══════════╬══════════════════════════════════════════════════════╣
║Hibernating║334, 344, 435, 425, 415, 433, 434, 443, 444, 534, 543,║
║customers  ║544, 454, 455                                         ║
║           ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║The customer value of the members of this segment is  ║
║           ║bellow average. Do not overspend on this segment.     ║ 
║           ║You can include them on standard communication and    ║    ║           ║give them some discounts or free product after xxx    ║
║           ║euros spent.                                          ║
╠═══════════╬══════════════════════════════════════════════════════╣
║Lost       ║555, 554, 545, 535,525,515                            ║
║customers  ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║This customers generate a small part of revenue. This ║
║           ║segments have a lowest priority. Do not resources and ║ 
║           ║time on them. But you can send them some discounts and║    
║           ║free products and analyses behavior after that.       ║
╚═══════════╩══════════════════════════════════════════════════════╝

Итак, мы можем агрегировать RFMScore для новых сегментов в соответствии с приведенными выше деталями:

################################################################
# Create segments by aggregating RFM SCores
################################################################
# First we download the segments names by RFM Score
segments_names = pd.read_csv('./results/segments.csv')
rfm = pd.merge(rfm, segments_names, how='inner', left_on='RFMScore', 
                       right_on='segments').drop('segments', axis=1)

# Get the number of customers for each segment after aggregation
rfm.groupby(['segment_name'['DocIDHash'].nunique().reset_index().ren    
                           ame(columns={'DocIDHash':'Nb Customers'})

Как видите, количество клиентов по сегментам приемлемое и маркетинговые действия могут быть полезными.

2. Создавайте классы с помощью CAH
Если сегменты, созданные выше в этом разделе, вам не подходят, вы можете использовать другие методы для создания собственных сегментов.
Здесь мы представим вам один из них для создания персонализированные сегменты.

Этот метод представляет собой кластеризацию CAH для агрегирования сегментов, созданных методом RFM.

Первый шаг состоит в определении центроида каждого сегмента RFM (средние значения каждой переменной созданных кластеров):

rfm_centroid = rfm.groupby('RFMScore')\
                   [['recency','frequency','monetary_value']].mean()

И затем мы запускаем кластеризацию CAH:

from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
################################################
##Generate Links matrix
################################################
Z = linkage(rfm_centroid,method='ward',metric='euclidean')
################################################
##Print dendrogram
################################################
plt.title("CAH : Aggregated segments")
dendrogram(Z,labels=rfm_centroid.index, orientation='left',\
                                               color_threshold=2300)
plt.show()
###############################################
## you can change the value of color_threshold to select the number of cluster that you want

Здесь мы сохраняем только 4 кластера (вы можете оставить больше или меньше сегментов, если хотите, изменив значение color_threshold):

╔═══════════╦══════════════════════════════════════════════════════╗
║ Segment   ║ Score                                                ║
╠═══════════╬══════════════════════════════════════════════════════╣
║Best       ║111                                                   ║
║Customers  ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║Give them something extra that the regulars do not get║
║           ║For example, limited series of products or special    ║           ║           ║discounts to make them feel valued : You might make   ║
║           ║them your ambassadors, giving them a margin of your   ║
║           ║profits for bringing you, new customers               ║ 
╠═══════════╬══════════════════════════════════════════════════════╣
║Big        ║211, 351, 451, 311, 411, 511, 551, 251                ║
║Spenders   ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║Propose them your most expensive product.This segment ║
║           ║have the greatest purchasing power.                   ║
╠═══════════╬══════════════════════════════════════════════════════╣
║Almost     ║412, 413, 414, 415, 452, 555, 554, 454, 455, 512, 513,║
║Lost       ║514, 552, 553, 453                                    ║
║           ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║These customers already bought, a long time ago, from ║
║           ║you but You are loosing them. Try to motivate them by ║
║           ║promotion and gifts.                                  ║
╠═══════════╬══════════════════════════════════════════════════════╣
║Promising  ║252, 155, 353, 352, 253, 254, 354, 114, 115, 214, 255,║
║           ║312, 314, 113, 213, 212, 313, 112, 355, 315, 215      ║
║           ║------------------------------------------------------║
║           ║ Marketing Actions                                    ║
║           ║------------------------------------------------------║
║           ║These customers already bought from you but the size  ║ ║           ║of their basket was not too big. Try to motivate them ║
║           ║to increase the number of items in their cart by      ║ ║           ║showing them cross-selling recommendations.           ║
╚═══════════╩══════════════════════════════════════════════════════╝

3. Продолжайте сегментацию RFM

Сегментация RFM может быть первым шагом к вашим знаниям о клиентах, но мы можем легко улучшить его, профилируя каждый сегмент.
Этап профилирования состоит в определении определенных характеристик поведения для каждого сегмента:
Примеры:

  • Средний возраст этого класса 44 года.
  • Излюбленный канал распространения этого сегмента — «Туристический агент/оператор».
  • Средний расход по этому сегменту составляет 13 465 евро.
  • У них в среднем 45 бронирований
  • Последнее бронирование с -1 дней (клиенты придут завтра)
  • Они из Франции/Германии и Великобритании

Все скрипты есть: https://github.com/Faouzizi/RFM-Analysis

Вывод

После этого вы сможете создать свою собственную RFM-сегментацию и эффективно общаться в соответствии с целью.
Надеюсь, что эта статья поможет вам :)

Вы новичок в Medium?
Не стесняйтесь подписаться менее чем за 5 долларов США здесь, чтобы получать неограниченные выгоды и улучшать свои навыки.