税务合规性预测

前言

本项目使用数据挖掘相关算法对企业税务是否合规进行预测。本项目主要使用了XGBoost随机森林两种算法进行对比分析。整个项目包含了一般项目的所有流程:特征预处理,特征编码,特征过滤,数据集切分,模型训练,模型评价,可视化检视。经过实验对比分析,随机森林的预测效果略优于XGBoost,他们的准确率最高都能达到80%以上(随机森林可达86%)。本项目所用的数据集来源于公众号:Dathon数据分析

实验部分

数据集介绍

本实验所用数据集是关于某汽车销售行业124位纳税人的纳税情况。数据集保存为csv格式,最后一列是标签,共有两个类型:异常/正常。前15列是特征,但显然,第一列纳税人编号不能作为有效特征,可以剔除,所以有效特征只有14个。

技术选型

numpy pandas matplotlib sklearn xgboost

数据导入

导包

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OrdinalEncoder
from sklearn.model_selection import train_test_split as TTS
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import VarianceThreshold
from sklearn.metrics import f1_score
from sklearn.metrics import average_precision_score
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import plot_precision_recall_curve
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import PrecisionRecallDisplay
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
from sklearn.neural_network import MLPClassifier
from xgboost import XGBClassifier as XGBC
df = pd.read_csv('./tax.csv')
df.head()
tax_numsale_typesale_modesales_profitmaintenance_profitmaintenance_revenue_ratevat_burdeninventory_turnovercost_profit_ratetheoretical_tax_burdentotal_tax_controllicensing_ratesingle_station_feeagent_insurance_ratepremium_return_ratelabel
01国产轿车4S店0.06350.32410.08790.00848.52410.00180.01660.01470.40000.020.71550.1500正常
12国产轿车4S店0.05200.25770.13940.02985.2782-0.00130.00320.01370.33070.020.26970.1367正常
23国产轿车4S店0.01730.19650.10250.006719.83560.00140.00800.00610.22560.020.24450.1301正常
34国产轿车一级代理商0.05010.00000.00000.00001.0673-0.3596-0.16730.00000.00000.000.00000.0000异常
45进口轿车4S店0.05640.00340.00660.001712.8470-0.00140.01230.00950.00390.080.01170.1872正常
df.describe()
tax_numsales_profitmaintenance_profitmaintenance_revenue_ratevat_burdeninventory_turnovercost_profit_ratetheoretical_tax_burdentotal_tax_controllicensing_ratesingle_station_feeagent_insurance_ratepremium_return_rate
count124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000
mean62.5000000.0237090.1548940.0687170.00828711.0365400.1748390.0104350.0069610.1460770.0163870.1699760.039165
std35.9397640.1037900.4143870.1582540.01338912.9849481.1217570.0327530.0089260.2360640.0325100.3362200.065910
min1.000000-1.064600-3.1255000.0000000.0000000.000000-1.000000-0.181000-0.0070000.0000000.0000000.000000-0.014800
25%31.7500000.0031500.0000000.0000000.0004752.459350-0.0040750.0007250.0000000.0000000.0000000.0000000.000000
50%62.5000000.0251000.1567000.0259500.0048008.4212500.0005000.0091000.0060000.0000000.0000000.0000000.000000
75%93.2500000.0494250.3989250.0795500.00880015.1997250.0094250.0159250.0114250.2723250.0200000.1385000.081350
max124.0000000.1774001.0000001.0000000.07700096.7461009.8272000.1593000.0570000.8775000.2000001.5297000.270000
缺失值检查
df.isnull().sum().sum()
数据预处理

数据集中的一些特征和标签都是字符型,例如:国产轿车,4S店,正常。这种字符型值不方便应用到模型中,需要提前编码为数值型。在sklearn中与数据预处理相关的类都在sklearn.preprocessing子包下,读者可参考我之前的文章数据预处理

字符型标签编码为数值型

data = df.copy()
y =  data.iloc[:, -1]
data.iloc[:, -1] = LabelEncoder().fit_transform(y)

字符型特征编码为数值型

data.iloc[:, 1:3] = OrdinalEncoder().fit_transform(data.iloc[:, 1:3])
X, y = data.iloc[:, 1:-1], data.iloc[:, -1]
data.describe()
tax_numsale_typesale_modesales_profitmaintenance_profitmaintenance_revenue_ratevat_burdeninventory_turnovercost_profit_ratetheoretical_tax_burdentotal_tax_controllicensing_ratesingle_station_feeagent_insurance_ratepremium_return_ratelabel
count124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000124.000000
mean62.5000003.4354840.7661290.0237090.1548940.0687170.00828711.0365400.1748390.0104350.0069610.1460770.0163870.1699760.0391650.572581
std35.9397641.9052431.1694550.1037900.4143870.1582540.01338912.9849481.1217570.0327530.0089260.2360640.0325100.3362200.0659100.496711
min1.0000000.0000000.000000-1.064600-3.1255000.0000000.0000000.000000-1.000000-0.181000-0.0070000.0000000.0000000.000000-0.0148000.000000
25%31.7500003.0000000.0000000.0031500.0000000.0000000.0004752.459350-0.0040750.0007250.0000000.0000000.0000000.0000000.0000000.000000
50%62.5000003.0000000.0000000.0251000.1567000.0259500.0048008.4212500.0005000.0091000.0060000.0000000.0000000.0000000.0000001.000000
75%93.2500004.0000001.0000000.0494250.3989250.0795500.00880015.1997250.0094250.0159250.0114250.2723250.0200000.1385000.0813501.000000
max124.0000007.0000004.0000000.1774001.0000001.0000000.07700096.7461009.8272000.1593000.0570000.8775000.2000001.5297000.2700001.000000
特征过滤

特征过滤是特征选择的一种方式,特征过滤又分为方差过滤和相关性过滤。在本实验中使用的过滤方法是方差过滤,方差过滤就是通过特征本身的方差来筛选特征。比如一个特征本身的方差很小,就表示样本在这个特征上基本没有差异,可能特征中的大多数值都一样,甚至整个特征的取值都相同,那这个特征对于样本区分没有什么作用。所以无论接下来的特征工程要做什么,都要优先消除方差为0的特征。VarianceThreshold有重要参数threshold,表示方差的阈值,表示舍弃所有方差小于threshold的特征,不填默认为0,即删除所有的记录都相同的特征。

X = VarianceThreshold(np.median(X.var().values)).fit_transform(X)
训练集切分

将数据集切分为测试集和训练集

Xtrain, Xtest, Ytrain, Ytest = TTS(X, y, test_size=0.3, random_state=22)
模型训练

XGBoost

xgb = XGBC(n_estimators=20, random_state=420).fit(Xtrain, Ytrain)
xgb_y_pre = xgb.predict(Xtest)

随机森林

rfc = RandomForestClassifier(n_estimators=20, random_state=22)
rfc.fit(Xtrain, Ytrain)
rfc_y_pre = rfc.predict(Xtest)
模型评价

emmm…回归模型的评价指标也就那些,ROC,AUC,P-R图,f1_score等等。本实验中选用了f1_score和P-R图这两个评价指标。

XGBoost

f1_score

f1_score(Ytest,xgb_y_pre)
# 0.8444444444444444

P-R图

average_precision = average_precision_score(Ytest, xgb_y_pre)
disp = plot_precision_recall_curve(xgb, Xtest, Ytest)
disp.ax_.set_title('2-class Precision-Recall curve: '
                   'AP={0:0.2f}'.format(average_precision))

随机森林

f1_score

f1_score(Ytest,rfc_y_pre)
# 0.8636363636363636

P-R图

average_precision = average_precision_score(Ytest, rfc_y_pre)
disp = plot_precision_recall_curve(rfc, Xtest, Ytest)
disp.ax_.set_title('2-class Precision-Recall curve: '
                   'AP={0:0.2f}'.format(average_precision))

可视化展现

这个还比较有意思点,是借鉴了sklearn官方提供的一个learn curve示例,地址在第二个参考资料。

def plot_learning_curve(estimator, title, X, y, axes=None, ylim=None, cv=None,
                        n_jobs=None, train_sizes=np.linspace(.1, 1.0, 5)):
    if axes is None:
        _, axes = plt.subplots(1, 3, figsize=(20, 5))

    axes[0].set_title(title)
    if ylim is not None:
        axes[0].set_ylim(*ylim)
    axes[0].set_xlabel("Training examples")
    axes[0].set_ylabel("Score")

    train_sizes, train_scores, test_scores, fit_times, _ = \
        learning_curve(estimator, X, y, cv=cv, n_jobs=n_jobs,
                       train_sizes=train_sizes,
                       return_times=True)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    fit_times_mean = np.mean(fit_times, axis=1)
    fit_times_std = np.std(fit_times, axis=1)

    # Plot learning curve
    axes[0].grid()
    axes[0].fill_between(train_sizes, train_scores_mean - train_scores_std,
                         train_scores_mean + train_scores_std, alpha=0.1,
                         color="r")
    axes[0].fill_between(train_sizes, test_scores_mean - test_scores_std,
                         test_scores_mean + test_scores_std, alpha=0.1,
                         color="g")
    axes[0].plot(train_sizes, train_scores_mean, 'o-', color="r",
                 label="Training score")
    axes[0].plot(train_sizes, test_scores_mean, 'o-', color="g",
                 label="Cross-validation score")
    axes[0].legend(loc="best")

    # Plot n_samples vs fit_times
    axes[1].grid()
    axes[1].plot(train_sizes, fit_times_mean, 'o-')
    axes[1].fill_between(train_sizes, fit_times_mean - fit_times_std,
                         fit_times_mean + fit_times_std, alpha=0.1)
    axes[1].set_xlabel("Training examples")
    axes[1].set_ylabel("fit_times")
    axes[1].set_title("Scalability of the model")

    # Plot fit_time vs score
    axes[2].grid()
    axes[2].plot(fit_times_mean, test_scores_mean, 'o-')
    axes[2].fill_between(fit_times_mean, test_scores_mean - test_scores_std,
                         test_scores_mean + test_scores_std, alpha=0.1)
    axes[2].set_xlabel("fit_times")
    axes[2].set_ylabel("Score")
    axes[2].set_title("Performance of the model")

    return plt


fig, axes = plt.subplots(3, 2, figsize=(20, 25))

X, y = data.iloc[:, 1:-1], data.iloc[:, -1]

title = "Learning Curves (XGBC)"
# Cross validation with 100 iterations to get smoother mean test and train
# score curves, each time with 20% data randomly selected as a validation set.
cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)

estimator = XGBC(n_estimators=20, random_state=22)
plot_learning_curve(estimator, title, X, y, axes=axes[:, 0], ylim=(0.7, 1.01),
                    cv=cv, n_jobs=4)

title = r"Learning Curves (RandomForestClassifier)"
# SVC is more expensive so we do a lower number of CV iterations:
cv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=22)
estimator = RandomForestClassifier(n_estimators=20, random_state=22)
plot_learning_curve(estimator, title, X, y, axes=axes[:, 1], ylim=(0.7, 1.01),
                    cv=cv, n_jobs=4)

plt.show()

总结

其实这个项目(也不能叫项目,应该说实验吧)挺简单的,没有什么特别的新意。更多的可能是将整个的项目流程都串起来了。从数据预处理到模型评价和可视化检视,涉及的方法和策略本实验都有所涉及,对初学者应该有指导性帮助。

最后,有需要数据集和完整源代码的可以联系笔者。

参考资料

  • https://mp.weixin.qq.com/s/TzUl888vqR3j9Od2x8D1BQ

  • https://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html#sphx-glr-auto-examples-model-selection-plot-learning-curve-py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值