背景:某金融公司新推出的理財產(chǎn)品,預測客戶是否會接受新的產(chǎn)品,并提高產(chǎn)品的銷售量。
數(shù)據(jù):根據(jù)公司提供的用戶數(shù)據(jù),包括職業(yè)、婚姻狀態(tài)房產(chǎn)、年齡、違約情況等數(shù)據(jù)。與近期購買的詳細資料,包括金額、購買頻率,時間等相關(guān)數(shù)據(jù)。
目標:根據(jù)客戶的信息,將客戶進行分類打上標簽,預測該用戶是否會購買理財產(chǎn)品以及是否需要對該用戶進行主動銷售。

【一】思路&流程
對客戶進行精準營銷可以提高產(chǎn)品的銷售。那么對產(chǎn)品分析轉(zhuǎn)換為對客戶的分析。
——考慮客戶是否能接受新的產(chǎn)品,可以從兩方面著手分析。
1>依據(jù)往期客戶數(shù)據(jù)進行是否購買預測,二分類回歸問題。
2>根據(jù)客戶價值進行劃分,對高價值客戶加大營銷力度。
根據(jù)結(jié)果可以對客戶進行分群劃分,降低營銷成本。

【二】數(shù)據(jù)處理
1>數(shù)據(jù)探索
IO1 = r'C:\Users\Ziger\Desktop\Yian_Cinformation1782.csv'
IO2= r'C:\Users\Ziger\Desktop\Yian_details1782.csv'
data1 = pd.read_csv(IO, header=None, names=(['id','name','age','job','marital','education','default','balance','housing','loan','contact','day','month','duration','campaign','pdays','previous','poutcome','address','y'])
data2 = pd.read_csv(IO2)
根據(jù)業(yè)務常識,客戶基本信息刪除如ID,姓名等無關(guān)維度。
還款明細提取總計金額,購買時間,購買產(chǎn)品數(shù)等維度。
2>清洗數(shù)據(jù)
客戶資料文本數(shù)據(jù)較多,去除缺失的數(shù)據(jù)以免影響結(jié)果。

3>數(shù)據(jù)處理
文本數(shù)值化 ,本次基本信息中主要處理的是職業(yè),學歷,地址等文本信息。
data1.groupby(['job']).describe()

根據(jù)業(yè)務經(jīng)驗將對應的職業(yè)劃分打分。
def Replace (X,columns):
a = X.groupby([columns],as_index=False)[columns].agg({'cnt':'count'})
for i in a[columns]:
X[columns] = X[columns].replace(i,a[(a[columns]== i )].index.tolist()[0])
return (X)
def Len(X,columns):
for i in X[columns]:
X[columns] = X[columns].replace(i,len(i))
return (X)
將文本轉(zhuǎn)化為數(shù)值
def Sigmoid (X):
return (1.0 / (1 + np.exp(-float(X)))
數(shù)據(jù)歸一化
4>相關(guān)性分析
數(shù)據(jù)處理之后,選擇相關(guān)性最強的前17位維度進行分析觀測
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
corrmat = data.corr()
k = 17
plt.figure(figsize=(12,9))
cols = corrmat.nlargest(k, 'y')['y'].index
cm = np.corrcoef(data[cols].values.T)
sns.set(font_scale=1.25,font='SimHei')
hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', cmap='YlOrBr_r',annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values)
plt.show()

5>提取維度
data1客戶分析,將相關(guān)性較低的維度數(shù)據(jù)刪除。
data2貸款記錄,提取R,F,M。
import datetime as dt
now = dt.datetime(2017,11,14)
#查看交易最早-最晚日期
print(data2['Borrowing_date'].min())
print(data2['Borrowing_date'].max())
#構(gòu)造交易時間間隔變量 hist
data2['hist'] = now - df['Borrowing_date']
data2['hist'].astype('timedelta64[D]')
data2['hist'] = data2['hist'] / np.timedelta64(1,'D')
data2.head()
#生成R F M 特征變量 agg()分組函數(shù)
customer = data2.groupby('customer_id').agg(['hist':'min', #Recency
'customer_id':'count', #Frequency
'tran_amount':'sum']) #Monetary
#對變量重命名
customer.rename(columns = {'hist':'recency'
'customer_id':'frequency'
'tran_amount':'monetary'},inplace = True)
6>特征工程
驗衍生出新的維度。
a. 統(tǒng)計每個客戶使用的不同產(chǎn)品量,1列(目的:分析產(chǎn)品總數(shù)與是否購買關(guān)聯(lián))
b.統(tǒng)計每個客戶近期的產(chǎn)品購買頻率。(目的:分析客戶的近期的資金需求量)
c. 統(tǒng)計客戶借款金額與還款的差值。(目的:分析客戶貸款產(chǎn)品的需求度)
.........等
對已有數(shù)據(jù)進行觀測分析
eg:分析借貸時間可以針對銷售時間進行調(diào)整。
plt.subplots(figsize=(12,9))
sns.countplot(x='month',,hue='day',data=data1)

7>特征篩選
本次維度較少,但是為了提高模型預測準確率,對數(shù)據(jù)進行特征整合。
考慮因子分析與主成分分析,根據(jù)模型準確率選擇使用。
【三】RMF分析
1>用SPSS封裝模型進行預測

2>K-Means聚類算法對客戶數(shù)據(jù)進行分群
from sklearn.externals import joblib
from sklearn.cluster import KMeans
k=5
kmodel=KMeans(n_clusters=k,n_jobs=4)
kmodel.fit(customer)
r1=pd.Series(kmodel.labels_).value_counts()
r2=pd.DataFrame(kmodel.cluster_centers_)
r3=pd.Series(['group1','group2','group3','group4','group5',])
r=pd.concat([r3,r1,r2],axis=1)
r.columns=['聚類類別','聚類個數(shù)']+list(customer.columns)
r.to_csv(KMeans_result,encoding = 'utf_8_sig',index=False)
通過觀測客戶數(shù)及聚類中心,劃分客戶分類。
labels = np.array(list(customer.columns))
dataLenth = 5
r4=r2.T
r4.columns=list(customer.columns)
fig = plt.figure()
y=[]
for x in list(customer.columns):
dt= r4[x]
dt=np.concatenate((dt,[dt[0]]))
y.append(dt)
ax = fig.add_subplot(111, polar=True)
angles = np.linspace(0, 2*np.pi, dataLenth, endpoint=False)
angles = np.concatenate((angles, [angles[0]]))
ax.plot(angles, y[0], 'b-', linewidth=2)
ax.plot(angles, y[1], 'r-', linewidth=2)
ax.plot(angles, y[2], 'g-', linewidth=2)
ax.plot(angles, y[3], 'y-', linewidth=2)
ax.plot(angles, y[4], 'm-', linewidth=2)
plt.rcParams['font.sans-serif']=['SimHei']
ax.legend(r3,loc=1)
ax.set_thetagrids(angles * 180/np.pi, labels, fontproperties="SimHei")
ax.set_title("Customer_loan", va='bottom', fontproperties="SimHei")
ax.grid(True)
plt.show()
3>綜合分析
根據(jù)2次結(jié)果綜合考慮,將5類客戶打上標簽,劃分價值群。
【四】建模預測
二分類問題考慮邏輯回歸與隨機森林進行訓練。
交叉驗證
from sklearn import cross_validation
X = data1
Y1 = X['y']
X1 = X.drop(['y'],axis = 1)
X1_train, X1_test, y1_train, y1_test = \
cross_validation.train_test_split( X1, Y1, test_size=0.3, random_state=0)
設(shè)置early stop round 提前停止迭代參數(shù),防止過擬合,其他參數(shù)采用隨機搜索尋優(yōu)。
def LR(X_train, X_test, y_train, y_test):
from sklearn.linear_model import LogisticRegression
lor = LogisticRegression(penalty='l1',C=100,multi_class='ovr')
lor.fit(X_train, y_train)
predicted= lor.predict(X_test)
score = accuracy_score(y_test, predicted)
return (score)
def RF(X_train, X_test, y_train, y_test):
from sklearn.ensemble import RandomForestClassifier
model= RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
predicted= model.predict(X_test)
score = accuracy_score(y_test, predicted)
return (score)
優(yōu)化參數(shù),提高預測的準確率。
【五】總結(jié)分析
1>銷售策略
①考慮模型預測結(jié)果,對預測會購買的客戶進行營銷。
②RFM分群后,針對資金量高,購買頻繁的高價值客戶進行定向宣傳。
③考慮特殊維度的影響力,改變銷售策略。(如:貸款熱門時間段,貸款人年齡)
2>不足
①
②數(shù)據(jù)缺失值與異常值較少,但本身維度較少,特征工程中選擇面較少。
③