基于xgboost的购买意愿预测模型的代码
时间: 2023-12-24 18:03:22 浏览: 27
以下是基于XGBoost的购买意愿预测模型的代码示例:
首先需要导入必要的库和数据:
```python
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 读取数据
data = pd.read_csv('purchase_data.csv')
# 将数据分为特征和目标变量
X = data.drop('purchase', axis=1)
y = data['purchase']
```
接下来,将数据集拆分为训练集和测试集:
```python
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
然后,使用XGBoost库中的XGBClassifier类来创建模型:
```python
# 创建XGBoost分类器模型
model = xgb.XGBClassifier()
# 训练模型
model.fit(X_train, y_train)
```
训练完成后,可以使用测试集评估模型的性能:
```python
# 预测测试集
y_pred = model.predict(X_test)
# 计算准确度
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
```
最后,可以使用模型对新数据进行预测:
```python
# 创建新数据
new_data = pd.DataFrame({
'age': [35],
'income': [50000],
'gender': ['male'],
'marital_status': ['married'],
'education': ['college']
})
# 对新数据进行预测
prediction = model.predict(new_data)
print("Purchase prediction:", prediction[0])
```
以上就是基于XGBoost的购买意愿预测模型的代码示例。请注意,此代码仅用于演示目的,实际情况下可能需要进行更多的数据预处理和模型调整以获得更好的性能。