AI 自动获客系统中精准客户画像功能的 Python 代码示例。该示例会利用模拟数据构建客户画像,涵盖了数据预处理、特征提取、模型训练和画像生成等步骤。ai获客软件开发公司,ai获客源码出售
代码说明
数据生成:generate_mock_data 函数创建了一个模拟的客户数据集,包含年龄、性别、收入、购买频率、平均购买金额和客户类型等特征。
数据预处理:
preprocess_data 函数对分类特征(如性别和客户类型)使用 LabelEncoder 进行编码。
提取特征矩阵 X 和目标变量 y。
使用 StandardScaler 对特征矩阵进行标准化处理,以确保所有特征具有相同的尺度。
模型训练:
train_model 函数将数据集划分为训练集和测试集,使用随机森林分类器进行训练。
计算模型在测试集上的准确率并输出。
生成客户画像:
generate_customer_portrait 函数使用训练好的模型对所有客户数据进行预测。
将预测结果转换回原始的客户类型标签,并将其与客户特征组合成一个新的 DataFrame,即客户画像。
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# 生成模拟数据
def generate_mock_data():
data = {
'age': [25, 30, 35, 40, 45, 22, 28, 32, 38, 42],
'gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Female', 'Male', 'Female', 'Male', 'Female'],
'income': [50000, 60000, 70000, 80000, 90000, 45000, 55000, 65000, 75000, 85000],
'purchase_frequency': [5, 3, 7, 2, 4, 6, 8, 1, 3, 5],
'average_purchase_amount': [100, 200, 150, 300, 250, 80, 120, 220, 180, 280],
'customer_type': ['Low - value', 'High - value', 'Medium - value', 'High - value', 'Medium - value',
'Low - value', 'High - value', 'Low - value', 'Medium - value', 'High - value']
}
return pd.DataFrame(data)
# 数据预处理
def preprocess_data(df):
# 对分类特征进行编码
le_gender = LabelEncoder()
df['gender'] = le_gender.fit_transform(df['gender'])
le_customer_type = LabelEncoder()
df['customer_type'] = le_customer_type.fit_transform(df['customer_type'])
# 提取特征和目标变量
X = df.drop('customer_type', axis=1)
y = df['customer_type']
# 数据标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
return X_scaled, y, le_customer_type
# 模型训练
def train_model(X, y):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
print(f"模型准确率: {accuracy}")
return model
# 生成客户画像
def generate_customer_portrait(model, X, le_customer_type):
predictions = model.predict(X)
customer_types = le_customer_type.inverse_transform(predictions)
portrait_df = pd.DataFrame({
'age': X[:, 0],
'gender': X[:, 1],
'income': X[:, 2],
'purchase_frequency': X[:, 3],
'average_purchase_amount': X[:, 4],
'customer_type': customer_types
})
return portrait_df
if __name__ == "__main__":
# 生成模拟数据
df = generate_mock_data()
# 数据预处理
X_scaled, y, le_customer_type = preprocess_data(df)
# 模型训练
model = train_model(X_scaled, y)
# 生成客户画像
portrait = generate_customer_portrait(model, X_scaled, le_customer_type)
print("精准客户画像:")
print(portrait)