【练习笔记(第一次)】2020年数学建模国赛C题:数据处理、源代码

前言

本来因为ACM竞赛培训的原因没有参加数学建模的培训和系列赛事,开学被同学拉过来凑数,就这样阴差阳错的参加了一次数学建模国赛。由于没有系统的学习数学建模,还是第一次接触数学建模正式赛事,所以论文写的比较水。主要用到的方法都是烂大街的没有新意的方法,都是我在平时做数据练习时的一些偏机器学习的模型。前期想着队长能有什么模型想出来,结果队长啥也没想出来只好自己上,导致正式开始动笔建模时已经比较晚。其实论文还有很多可以改进的地方,比如没有查阅足够的文献资料,综合前人的结果,其实前人已经做出一些信用风险评估模型,其次集成学习比较仓促,没有分配分类器权重系数,时间够的话还应该可以做一下信用迁移矩阵,将题目中的时间用到。但最终还是写出了一个可行但并非最优解,也算完成论文。

题目

在这里插入图片描述

摘要

在这里插入图片描述

说明

详细论文、程序源码和数据

请见代码仓库,过一阵子放

数据预处理

据说这个部分让很多队伍头痛,其实也不是很难,不用很多时间。主要是根据发票信息对每个公司进行统计,我们算出了一些指标,以便以后使用,由于时间原因,没有处理发票中的时间信息。如果时间足够的话,其实还可以算一下信用迁移矩阵。详细程序见下。

综合评价系统

我们用的是Topsis+熵权法,其实综合评价系统有很多种,应该针对不同的数据区别使用,但笔者没系统学过建模,也是现学现用。读者可以尝试使用其他评价系统,或者尝试一些现有信用风险模型,谷歌学术搜一搜就可。

分类系统

使用kmeans分类,我也只知道这个,太菜了╯﹏╰。论文里分了九类,是根据聚类效果评价算法得出来的最佳聚类簇个数,其实3个也就够了的。

程序

1.问题1

数据读取

#导入相关库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import zscore
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
#读取数据
data = pd.read_excel('a0.xlsx')
data2 =pd.read_excel('a0.xlsx',sheet_name=1)
data3 =pd.read_excel('a0.xlsx',sheet_name=2)
#将企业代号前的E去掉,使其成为数值型变量,便于排序
data['企业代号']=data['企业代号'].apply(lambda x:int(x[1:]))
data2['企业代号']=data2['企业代号'].apply(lambda x:int(x[1:]))
data3['企业代号']=data3['企业代号'].apply(lambda x:int(x[1:]))

数据概览

data
企业代号 企业名称 信誉评级 是否违约
0 1 ***电器销售有限公司 A
1 2 ***技术有限责任公司 A
2 3 ***电子(中国)有限公司***分公司 C
3 4 ***发展有限责任公司 C
4 5 ***供应链管理有限公司 B
... ... ... ... ...
118 119 ***药房 D
119 120 ***陈列广告有限公司 D
120 121 ***药业连锁有限公司***药店 D
121 122 ***商贸有限责任公司 D
122 123 ***创科技有限责任公司 D

123 rows × 4 columns

data2
企业代号 发票号码 开票日期 销方单位代号 金额 税额 价税合计 发票状态
0 1 3390939 2017-07-18 A00297 -943.40 -56.60 -1000.00 有效发票
1 1 3390940 2017-07-18 A00297 -4780.24 -286.81 -5067.05 有效发票
2 1 3390941 2017-07-18 A00297 943.40 56.60 1000.00 有效发票
3 1 3390942 2017-07-18 A00297 4780.24 286.81 5067.05 有效发票
4 1 9902669 2017-08-07 A05061 326.21 9.79 336.00 有效发票
... ... ... ... ... ... ... ... ...
210942 122 54706234 2019-04-17 A08967 223.30 6.70 230.00 有效发票
210943 122 55721344 2020-01-10 A09184 264.15 15.85 280.00 有效发票
210944 123 38493295 2017-12-15 A03624 264.15 15.85 280.00 有效发票
210945 123 95472001 2018-12-29 A03626 264.15 15.85 280.00 有效发票
210946 123 54469883 2019-12-18 A03626 264.15 15.85 280.00 有效发票

210947 rows × 8 columns

data3
企业代号 发票号码 开票日期 购方单位代号 金额 税额 价税合计 发票状态
0 1 11459356 2017-08-04 B03711 9401.71 1598.29 11000.0 有效发票
1 1 5076239 2017-08-09 B00844 8170.94 1389.06 9560.0 有效发票
2 1 5076240 2017-08-09 B00844 8170.94 1389.06 9560.0 有效发票
3 1 5076241 2017-08-09 B00844 4085.47 694.53 4780.0 有效发票
4 1 5076242 2017-08-09 B00844 4085.47 694.53 4780.0 有效发票
... ... ... ... ... ... ... ... ...
162479 123 8887701 2019-12-17 B10944 4827.67 144.83 4972.5 有效发票
162480 123 8887702 2019-12-17 B10944 7412.62 222.38 7635.0 有效发票
162481 123 34173085 2019-12-17 B13093 1917.47 57.53 1975.0 有效发票
162482 123 8887703 2019-12-25 B13093 7252.42 217.58 7470.0 有效发票
162483 123 8887704 2019-12-25 B13093 6660.19 199.81 6860.0 有效发票

162484 rows × 8 columns

数据预处理

#计算有效发票、负数发票和作废发票数量
def cnt(a,b,df):
    tot=0
    for i in range(a,b):
        if df.iloc[i,6]<0 and df.iloc[i,7] == '有效发票':
            tot+=1 
    if(len(df.iloc[a:b,:]['发票状态'].value_counts())==1):
        return  df.iloc[a:b,:]['发票状态'].value_counts()['有效发票'],0,tot
    return df.iloc[a:b,:]['发票状态'].value_counts()['有效发票'],df.iloc[a:b,:]['发票状态'].value_counts()['作废发票'],tot
#计算有效金额,有效税额,作废额
def cnt2(a,b,df):
    zf=0
    yxj=0
    yxs=0
    for i in range(a,b):
        if df.iloc[i,7] == '作废发票':
            zf+=df.iloc[i,6]
        else:
            yxj+=df.iloc[i,4]
            yxs+=df.iloc[i,5]
    return yxj,yxs,zf
#对进项发票进行统计
checkin=pd.DataFrame(data2['企业代号'].value_counts())
checkin.columns=['进项发票数量']
checkin.sort_index(inplace=True)

last=0
temp1=[]
temp2=[]
temp3=[]
temp4=[]
temp5=[]
temp6=[]
temp7=[]

for i in range(len(checkin)):
    a,b,c=cnt(last,last+int(checkin.iloc[i,0]),data2)
    d,e,f=cnt2(last,last+int(checkin.iloc[i,0]),data2)
    last=last+int(checkin.iloc[i,0])
    temp1.append(a)
    temp2.append(b)
    temp3.append(c)
    temp4.append(d)
    temp5.append(e)
    temp6.append(f)
    temp7.append(d+e)

checkin['进项有效发票']=temp1
checkin['进项作废发票']=temp2
checkin['进项负数发票']=temp3
checkin['进项有效金额']=temp4
checkin['进项有效税额']=temp5
checkin['进项无效额']=temp6
checkin['进项有效价税']=temp7
#对销项发票进行统计
checkout=pd.DataFrame(data3['企业代号'].value_counts())
checkout.columns=['销项发票数量']
checkout.sort_index(inplace=True)

last=0
temp1=[]
temp2=[]
temp3=[]
temp4=[]
temp5=[]
temp6=[]
temp7=[]

for i in range(len(checkout)):
    a,b,c=cnt(last,last+int(checkout.iloc[i,0]),data3)
    d,e,f=cnt2(last,last+int(checkout.iloc[i,0]),data3)
    last=last+int(checkout.iloc[i,0])
    temp1.append(a)
    temp2.append(b)
    temp3.append(c)
    temp4.append(d)
    temp5.append(e)
    temp6.append(f)
    temp7.append(d+e)
    
checkout['销项有效发票']=temp1
checkout['销项作废发票']=temp2
checkout['销项负数发票']=temp3
checkout['销项有效金额']=temp4
checkout['销项有效税额']=temp5
checkout['销项无效额']=temp6
checkout['销项有效价税']=temp7
#保存中间结果
checkin.to_excel('value_counts_in.xls')
checkout.to_excel('value_counts_out.xls')
#合并进项和销项发票收据数据,为进行下一步计算做准备
checks=pd.concat([checkin,checkout],axis=1)
#对发票进行汇总统计
temp1=data['信誉评级']
temp2=data['是否违约']

temp1.index=range(1,124)
temp2.index=range(1,124)
checks=pd.concat([temp1,temp2,checks],axis=1)
checks['收入']=checks['销项有效价税']-checks['进项有效价税']

temp1=[]
temp2=[]
temp3=[]
temp4=[]
temp5=[]
last1=last2=0
a=b=0
for i in range(len(checks)):
    next1=last1+checks.iloc[i,2]
    next2=last2+checks.iloc[i,10]
    temp3=data2.iloc[last1:next1,3].value_counts()
    temp4=data3.iloc[last2:next2,3].value_counts()
    if(len(temp3)<=3):
        temp1.append(1)
        temp2.append(1)
        temp5.append(1)
    else:
        a=sum(temp3[:3])/sum(temp3)
        b=sum(temp4[:3])/sum(temp4)
        temp1.append(a)
        temp2.append(b)
        temp5.append(np.sqrt((a*a+b*b)/2))
    last1=next1
    last2=next2
    
checks['进稳定度指标']=temp1
checks['销稳定度指标']=temp2
checks['供求稳定度指标']=temp5

temp1=[]
temp2=[]
for i in range(len(checks)):
    sum1=sum2=sum3=0
    sum1=checks.iloc[i,2]+checks.iloc[i,10]
    sum2=checks.iloc[i,4]+checks.iloc[i,12]
    sum3=checks.iloc[i,5]+checks.iloc[i,13]
    temp1.append(sum2/sum1)
    temp2.append(sum3/sum1)
    
checks['作废发票率']=temp1
checks['负数发票率']=temp2
#保存中间结果
checks.to_excel('checks_1.xls')

第一问子问题一求解

pa0=checks[checks['信誉评级']!='D']
pa0
信誉评级 是否违约 进项发票数量 进项有效发票 进项作废发票 进项负数发票 进项有效金额 进项有效税额 进项无效额 进项有效价税 ... 销项有效金额 销项有效税额 销项无效额 销项有效价税 收入 进稳定度指标 销稳定度指标 供求稳定度指标 作废发票率 负数发票率
1 A 3441 3249 192 71 5.744706e+09 8.932358e+08 2.547518e+08 6.637942e+09 ... 4.065843e+09 6.327901e+08 1.001785e+08 4.698633e+09 -1.939309e+09 0.515838 0.236252 0.401188 0.036014 0.025885
2 A 32156 31435 721 156 1.557623e+08 6.725653e+06 9.248509e+06 1.624880e+08 ... 5.908417e+08 3.545392e+07 6.841255e+07 6.262956e+08 4.638077e+08 0.268597 0.084520 0.199108 0.039297 0.011457
3 C 4561 4367 194 26 5.202698e+07 2.152374e+06 3.341486e+06 5.417935e+07 ... 5.701780e+08 9.089228e+07 2.166951e+07 6.610703e+08 6.068909e+08 0.168823 0.568936 0.419636 0.020221 0.154781
4 C 558 521 37 4 2.198771e+08 3.470711e+07 1.258232e+08 2.545842e+08 ... 1.839970e+09 3.065709e+08 1.990901e+08 2.146541e+09 1.891956e+09 0.261649 0.710892 0.535643 0.081391 0.004661
5 B 2169 2084 85 16 1.977850e+08 2.954699e+07 4.718235e+06 2.273320e+08 ... 2.026323e+08 3.065841e+07 9.497473e+06 2.332907e+08 5.958721e+06 0.393269 0.591509 0.502267 0.043357 0.008052
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
98 B 51 50 1 1 1.993190e+05 9.963970e+03 2.060000e+02 2.092830e+05 ... 1.403242e+06 4.186923e+04 3.697712e+05 1.445111e+06 1.235828e+06 0.392157 0.732026 0.587218 0.102941 0.034314
104 C 1 1 0 0 2.641500e+02 1.585000e+01 0.000000e+00 2.800000e+02 ... 2.626505e+05 7.879490e+03 2.000000e+04 2.705300e+05 2.702500e+05 1.000000 1.000000 1.000000 0.090909 0.045455
105 C 6 6 0 0 7.436920e+03 1.043080e+03 0.000000e+00 8.480000e+03 ... 9.248194e+05 2.774452e+04 1.039500e+04 9.525639e+05 9.440839e+05 0.833333 0.196721 0.605452 0.007812 0.031250
106 B 36 35 1 0 5.033527e+04 2.125830e+03 9.000000e+03 5.246110e+04 ... 5.860489e+05 1.762900e+04 5.552000e+04 6.036779e+05 5.512168e+05 0.361111 0.156863 0.278395 0.084656 0.021164
110 C 3 3 0 0 9.633900e+02 7.661000e+01 0.000000e+00 1.040000e+03 ... 1.969199e+05 5.907650e+03 7.257769e+04 2.028275e+05 2.017875e+05 1.000000 1.000000 1.000000 0.244186 0.000000

99 rows × 24 columns

pa0.iloc[:,0].value_counts()
B    38
C    34
A    27
Name: 信誉评级, dtype: int64
#替换指标值、删除多余项
pa1=pa0
pa1=pa1.replace('是',0)
pa1=pa1.replace('否',1)
pa1=pa1.replace('A',100)
pa1=pa1.replace('B',80)
pa1=pa1.replace('C',52.45)

pa1.drop(pa1.columns[range(2,18)],axis=1,inplace=True)
pa1.drop(pa1.columns[range(3,5)],axis=1,inplace=True)
pa1
信誉评级 是否违约 收入 供求稳定度指标 作废发票率 负数发票率
1 100.00 1 -1.939309e+09 0.401188 0.036014 0.025885
2 100.00 1 4.638077e+08 0.199108 0.039297 0.011457
3 52.45 1 6.068909e+08 0.419636 0.020221 0.154781
4 52.45 1 1.891956e+09 0.535643 0.081391 0.004661
5 80.00 1 5.958721e+06 0.502267 0.043357 0.008052
... ... ... ... ... ... ...
98 80.00 1 1.235828e+06 0.587218 0.102941 0.034314
104 52.45 1 2.702500e+05 1.000000 0.090909 0.045455
105 52.45 1 9.440839e+05 0.605452 0.007812 0.031250
106 80.00 1 5.512168e+05 0.278395 0.084656 0.021164
110 52.45 1 2.017875e+05 1.000000 0.244186 0.000000

99 rows × 6 columns

#成本型指标转换,数据归一化
pa1['作废发票率']=(max(pa1['作废发票率'])-pa1['作废发票率'])/(max(pa1['作废发票率'])-min(pa1['作废发票率']))
pa1['负数发票率']=(max(pa1['负数发票率'])-pa1['负数发票率'])/(max(pa1['负数发票率'])-min(pa1['负数发票率']))
pa1=(pa1-pa1.min())/(pa1.max()-pa1.min())
pa2=np.asarray(pa1)
#熵权法计算权重
ta=pa1
tb=pa2
n,m=np.shape(tb)
s=np.sum(ta,axis=0)
s=np.asarray(s)
s=np.reshape(s,(1,len(s)))
s=np.repeat(s,len(tb),axis=0)
s=s.reshape((n,m))
tb=tb/s
a=tb*1.0
a[np.where(tb==0)]=0.001
e=(-1.0/np.log(n))*np.sum(tb*np.log(a),axis=0)
w=(1-e)/np.sum(1-e)
w
array([0.62060705, 0.04171411, 0.02020687, 0.25088922, 0.04182548,
       0.02475726])
#Topsis综合评价
df=pa2/np.sqrt((pa2**2).sum())
df=pd.DataFrame(df)
X=pd.DataFrame([df.min(),df.max()],index=['负理想解','正理想解'])
R=df.copy()
R.columns=['信誉评级','是否违约','收入','供求稳定度指标','作废发票率','负数发票率']
R['正理想解']=np.sqrt(((df - X.loc['正理想解']) ** 2 * w).sum(axis=1))
R['负理想解']=np.sqrt(((df - X.loc['负理想解']) ** 2 * w).sum(axis=1))
R['综合得分']=R['负理想解'] / (R['负理想解'] + R['正理想解'])
R['排序']=R.rank(ascending=False)['综合得分']
R['公司识别码']=pa1.index
R['利率']=15-(R['综合得分']-R['综合得分'].min())/(R['综合得分'].max()-R['综合得分'].min())*11
#保存第一问子问题一结果
R.to_excel('result_1.xls')

第一问子问题二求解

pb0=pa0
pb1=pb0.iloc[:,[2,6,7,10,14,15,18,19,20,21,22,23]]#删去多余的指标
pb2=np.asarray(pb1)#转化为numpy数组,便于进行下一步计算
pb2=zscore(pb2)#数据标准化
#PCA主成分分析
pca=PCA()
pca.fit(pb2)
#计算差异保留比例
pcavr=[]
for i in range(1,13):
    pcavr.append(sum(pca.explained_variance_ratio_[:i]))
pcavr
[0.35983267152542864,
 0.5976689949959799,
 0.7300543810440263,
 0.8069829584129986,
 0.8737054990987985,
 0.9362732312043334,
 0.9788073230784305,
 0.9989350168474531,
 0.9995699794090525,
 0.9999523012802018,
 0.9999999999999999,
 0.9999999999999999]
#PCA差异保留画图分析
X = range(1,13)
#plt.figure(figsize=(12,8))
plt.xlabel('n_components')
plt.title('Principal Component Analysis')
plt.ylabel('Explained Variance Ratio')
plt.plot(X,pcavr,'o-')
plt.locator_params('x',nbins=12)
plt.savefig('Principal_Component_Analysis.jpg')
plt.show()

在这里插入图片描述

#选取最佳维度6,保留93%差异性
pca_=PCA(n_components=6)
pb3=pca_.fit_transform(pb2)
#肘部法则计算最佳聚类数
SSE=[]
for k in range(2,21):
    km=KMeans(n_clusters=k,random_state=10)
    km.fit(pb3)
    SSE.append(km.inertia_)
    X = range(2,21)
    
#肘部法则画图分析
#plt.figure(figsize=(12,8))
plt.xlabel('k')
plt.title('Elbow Method')
plt.ylabel('SSE')
plt.plot(X,SSE,'o-')
plt.locator_params('x',nbins=20)
plt.savefig('Elbow_Method.jpg')
plt.show()

在这里插入图片描述

#轮廓系数计算最佳聚类数
SC=[]
for k in range(2,21):
    km=KMeans(n_clusters=k,random_state=10)
    km.fit(pb3)
    a=silhouette_score(pb3,km.labels_, metric='euclidean')
    SC.append(a)
    
#轮廓系数画图分析
X = range(2,21)
#plt.figure(figsize=(12,8))
plt.xlabel('k')
plt.title('Silhouette Coefficient')
plt.ylabel('SC')
plt.plot(X,SC,'o-')
plt.locator_params('x',nbins=20)
plt.savefig('Silhouette_Coefficient.jpg')
plt.show()

在这里插入图片描述

#选取最佳聚类数9进行聚类分析
km=KMeans(n_clusters=9,random_state=12)
km.fit(pb3)
#标签统计
pd.DataFrame(km.labels_)[0].value_counts()
7    34
6    29
2    16
5     8
8     5
4     3
3     2
1     1
0     1
Name: 0, dtype: int64
#加入标签
pb1['分类']=km.labels_
pb1
/home/yang/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

进项发票数量 进项有效金额 进项有效税额 销项发票数量 销项有效金额 销项有效税额 收入 进稳定度指标 销稳定度指标 供求稳定度指标 作废发票率 负数发票率 分类
1 3441 5.744706e+09 8.932358e+08 8110 4.065843e+09 6.327901e+08 -1.939309e+09 0.515838 0.236252 0.401188 0.036014 0.025885 1
2 32156 1.557623e+08 6.725653e+06 12707 5.908417e+08 3.545392e+07 4.638077e+08 0.268597 0.084520 0.199108 0.039297 0.011457 4
3 4561 5.202698e+07 2.152374e+06 24073 5.701780e+08 9.089228e+07 6.068909e+08 0.168823 0.568936 0.419636 0.020221 0.154781 3
4 558 2.198771e+08 3.470711e+07 2231 1.839970e+09 3.065709e+08 1.891956e+09 0.261649 0.710892 0.535643 0.081391 0.004661 0
5 2169 1.977850e+08 2.954699e+07 1060 2.026323e+08 3.065841e+07 5.958721e+06 0.393269 0.591509 0.502267 0.043357 0.008052 7
... ... ... ... ... ... ... ... ... ... ... ... ... ...
98 51 1.993190e+05 9.963970e+03 153 1.403242e+06 4.186923e+04 1.235828e+06 0.392157 0.732026 0.587218 0.102941 0.034314 6
104 1 2.641500e+02 1.585000e+01 21 2.626505e+05 7.879490e+03 2.702500e+05 1.000000 1.000000 1.000000 0.090909 0.045455 5
105 6 7.436920e+03 1.043080e+03 122 9.248194e+05 2.774452e+04 9.440839e+05 0.833333 0.196721 0.605452 0.007812 0.031250 6
106 36 5.033527e+04 2.125830e+03 153 5.860489e+05 1.762900e+04 5.512168e+05 0.361111 0.156863 0.278395 0.084656 0.021164 7
110 3 9.633900e+02 7.661000e+01 83 1.969199e+05 5.907650e+03 2.017875e+05 1.000000 1.000000 1.000000 0.244186 0.000000 5

99 rows × 13 columns

#保存问题一子问题二结果
pb1.to_excel('result_2.xls')

2.附件一Topsis综合评价

说明
这些程序从问题一改写而来,问题要去掉信誉等级为D的再算topsis综合得分,为了神经网络的学习,这里不需要去D

数据读取

#导入相关库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import zscore
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
#读取数据
data = pd.read_excel('a0.xlsx')
data2 =pd.read_excel('a0.xlsx',sheet_name=1)
data3 =pd.read_excel('a0.xlsx',sheet_name=2)
#将企业代号前的E去掉,使其成为数值型变量,便于排序
data['企业代号']=data['企业代号'].apply(lambda x:int(x[1:]))
data2['企业代号']=data2['企业代号'].apply(lambda x:int(x[1:]))
data3['企业代号']=data3['企业代号'].apply(lambda x:int(x[1:]))

数据概览

data
企业代号 企业名称 信誉评级 是否违约
0 1 ***电器销售有限公司 A
1 2 ***技术有限责任公司 A
2 3 ***电子(中国)有限公司***分公司 C
3 4 ***发展有限责任公司 C
4 5 ***供应链管理有限公司 B
... ... ... ... ...
118 119 ***药房 D
119 120 ***陈列广告有限公司 D
120 121 ***药业连锁有限公司***药店 D
121 122 ***商贸有限责任公司 D
122 123 ***创科技有限责任公司 D

123 rows × 4 columns

data2
企业代号 发票号码 开票日期 销方单位代号 金额 税额 价税合计 发票状态
0 1 3390939 2017-07-18 A00297 -943.40 -56.60 -1000.00 有效发票
1 1 3390940 2017-07-18 A00297 -4780.24 -286.81 -5067.05 有效发票
2 1 3390941 2017-07-18 A00297 943.40 56.60 1000.00 有效发票
3 1 3390942 2017-07-18 A00297 4780.24 286.81 5067.05 有效发票
4 1 9902669 2017-08-07 A05061 326.21 9.79 336.00 有效发票
... ... ... ... ... ... ... ... ...
210942 122 54706234 2019-04-17 A08967 223.30 6.70 230.00 有效发票
210943 122 55721344 2020-01-10 A09184 264.15 15.85 280.00 有效发票
210944 123 38493295 2017-12-15 A03624 264.15 15.85 280.00 有效发票
210945 123 95472001 2018-12-29 A03626 264.15 15.85 280.00 有效发票
210946 123 54469883 2019-12-18 A03626 264.15 15.85 280.00 有效发票

210947 rows × 8 columns

data3
企业代号 发票号码 开票日期 购方单位代号 金额 税额 价税合计 发票状态
0 1 11459356 2017-08-04 B03711 9401.71 1598.29 11000.0 有效发票
1 1 5076239 2017-08-09 B00844 8170.94 1389.06 9560.0 有效发票
2 1 5076240 2017-08-09 B00844 8170.94 1389.06 9560.0 有效发票
3 1 5076241 2017-08-09 B00844 4085.47 694.53 4780.0 有效发票
4 1 5076242 2017-08-09 B00844 4085.47 694.53 4780.0 有效发票
... ... ... ... ... ... ... ... ...
162479 123 8887701 2019-12-17 B10944 4827.67 144.83 4972.5 有效发票
162480 123 8887702 2019-12-17 B10944 7412.62 222.38 7635.0 有效发票
162481 123 34173085 2019-12-17 B13093 1917.47 57.53 1975.0 有效发票
162482 123 8887703 2019-12-25 B13093 7252.42 217.58 7470.0 有效发票
162483 123 8887704 2019-12-25 B13093 6660.19 199.81 6860.0 有效发票

162484 rows × 8 columns

数据预处理

#计算有效发票、负数发票和作废发票数量
def cnt(a,b,df):
    tot=0
    for i in range(a,b):
        if df.iloc[i,6]<0 and df.iloc[i,7] == '有效发票':
            tot+=1 
    if(len(df.iloc[a:b,:]['发票状态'].value_counts())==1):
        return  df.iloc[a:b,:]['发票状态'].value_counts()['有效发票'],0,tot
    return df.iloc[a:b,:]['发票状态'].value_counts()['有效发票'],df.iloc[a:b,:]['发票状态'].value_counts()['作废发票'],tot
#计算有效金额,有效税额,作废额
def cnt2(a,b,df):
    zf=0
    yxj=0
    yxs=0
    for i in range(a,b):
        if df.iloc[i,7] == '作废发票':
            zf+=df.iloc[i,6]
        else:
            yxj+=df.iloc[i,4]
            yxs+=df.iloc[i,5]
    return yxj,yxs,zf
#对进项发票进行统计
checkin=pd.DataFrame(data2['企业代号'].value_counts())
checkin.columns=['进项发票数量']
checkin.sort_index(inplace=True)

last=0
temp1=[]
temp2=[]
temp3=[]
temp4=[]
temp5=[]
temp6=[]
temp7=[]

for i in range(len(checkin)):
    a,b,c=cnt(last,last+int(checkin.iloc[i,0]),data2)
    d,e,f=cnt2(last,last+int(checkin.iloc[i,0]),data2)
    last=last+int(checkin.iloc[i,0])
    temp1.append(a)
    temp2.append(b)
    temp3.append(c)
    temp4.append(d)
    temp5.append(e)
    temp6.append(f)
    temp7.append(d+e)

checkin['进项有效发票']=temp1
checkin['进项作废发票']=temp2
checkin['进项负数发票']=temp3
checkin['进项有效金额']=temp4
checkin['进项有效税额']=temp5
checkin['进项无效额']=temp6
checkin['进项有效价税']=temp7
#对销项发票进行统计
checkout=pd.DataFrame(data3['企业代号'].value_counts())
checkout.columns=['销项发票数量']
checkout.sort_index(inplace=True)

last=0
temp1=[]
temp2=[]
temp3=[]
temp4=[]
temp5=[]
temp6=[]
temp7=[]

for i in range(len(checkout)):
    a,b,c=cnt(last,last+int(checkout.iloc[i,0]),data3)
    d,e,f=cnt2(last,last+int(checkout.iloc[i,0]),data3)
    last=last+int(checkout.iloc[i,0])
    temp1.append(a)
    temp2.append(b)
    temp3.append(c)
    temp4.append(d)
    temp5.append(e)
    temp6.append(f)
    temp7.append(d+e)
    
checkout['销项有效发票']=temp1
checkout['销项作废发票']=temp2
checkout['销项负数发票']=temp3
checkout['销项有效金额']=temp4
checkout['销项有效税额']=temp5
checkout['销项无效额']=temp6
checkout['销项有效价税']=temp7
#合并进项和销项发票收据数据,为进行下一步计算做准备
checks=pd.concat([checkin,checkout],axis=1)
#对发票进行汇总统计
temp1=data['信誉评级']
temp2=data['是否违约']

temp1.index=range(1,124)
temp2.index=range(1,124)
checks=pd.concat([temp1,temp2,checks],axis=1)
checks['收入']=checks['销项有效价税']-checks['进项有效价税']

temp1=[]
temp2=[]
temp3=[]
temp4=[]
temp5=[]
last1=last2=0
a=b=0
for i in range(len(checks)):
    next1=last1+checks.iloc[i,2]
    next2=last2+checks.iloc[i,10]
    temp3=data2.iloc[last1:next1,3].value_counts()
    temp4=data3.iloc[last2:next2,3].value_counts()
    if(len(temp3)<=3):
        temp1.append(1)
        temp2.append(1)
        temp5.append(1)
    else:
        a=sum(temp3[:3])/sum(temp3)
        b=sum(temp4[:3])/sum(temp4)
        temp1.append(a)
        temp2.append(b)
        temp5.append(np.sqrt((a*a+b*b)/2))
    last1=next1
    last2=next2
    
checks['进稳定度指标']=temp1
checks['销稳定度指标']=temp2
checks['供求稳定度指标']=temp5

temp1=[]
temp2=[]
for i in range(len(checks)):
    sum1=sum2=sum3=0
    sum1=checks.iloc[i,2]+checks.iloc[i,10]
    sum2=checks.iloc[i,4]+checks.iloc[i,12]
    sum3=checks.iloc[i,5]+checks.iloc[i,13]
    temp1.append(sum2/sum1)
    temp2.append(sum3/sum1)
    
checks['作废发票率']=temp1
checks['负数发票率']=temp2

对不去D的数据进行topsis综合评价

#pa0=checks[checks['信誉评级']!='D']
pa0=checks
pa0
信誉评级 是否违约 进项发票数量 进项有效发票 进项作废发票 进项负数发票 进项有效金额 进项有效税额 进项无效额 进项有效价税 ... 销项有效金额 销项有效税额 销项无效额 销项有效价税 收入 进稳定度指标 销稳定度指标 供求稳定度指标 作废发票率 负数发票率
1 A 3441 3249 192 71 5.744706e+09 8.932358e+08 2.547518e+08 6.637942e+09 ... 4.065843e+09 6.327901e+08 1.001785e+08 4.698633e+09 -1.939309e+09 0.515838 0.236252 0.401188 0.036014 0.025885
2 A 32156 31435 721 156 1.557623e+08 6.725653e+06 9.248509e+06 1.624880e+08 ... 5.908417e+08 3.545392e+07 6.841255e+07 6.262956e+08 4.638077e+08 0.268597 0.084520 0.199108 0.039297 0.011457
3 C 4561 4367 194 26 5.202698e+07 2.152374e+06 3.341486e+06 5.417935e+07 ... 5.701780e+08 9.089228e+07 2.166951e+07 6.610703e+08 6.068909e+08 0.168823 0.568936 0.419636 0.020221 0.154781
4 C 558 521 37 4 2.198771e+08 3.470711e+07 1.258232e+08 2.545842e+08 ... 1.839970e+09 3.065709e+08 1.990901e+08 2.146541e+09 1.891956e+09 0.261649 0.710892 0.535643 0.081391 0.004661
5 B 2169 2084 85 16 1.977850e+08 2.954699e+07 4.718235e+06 2.273320e+08 ... 2.026323e+08 3.065841e+07 9.497473e+06 2.332907e+08 5.958721e+06 0.393269 0.591509 0.502267 0.043357 0.008052
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
119 D 315 314 1 1 2.197387e+05 2.999611e+04 6.250000e+01 2.497348e+05 ... 3.567186e+04 1.070140e+03 5.000000e+02 3.674200e+04 -2.129928e+05 0.761905 0.333333 0.588052 0.011905 0.002976
120 D 36 35 1 0 1.811556e+04 1.330780e+03 1.075000e+04 1.944634e+04 ... 1.906732e+05 5.720210e+03 0.000000e+00 1.963934e+05 1.769471e+05 0.583333 0.206897 0.437655 0.323077 0.000000
121 D 50 50 0 1 1.073486e+06 1.776337e+05 0.000000e+00 1.251120e+06 ... 1.014620e+05 1.282553e+04 3.505210e+03 1.142875e+05 -1.136832e+06 0.740000 0.215054 0.544907 0.097458 0.004237
122 D 48 47 1 1 5.067211e+04 3.074150e+03 9.620000e+02 5.374626e+04 ... 5.892182e+04 1.818780e+03 2.674846e+04 6.074060e+04 6.994340e+03 0.437500 0.169492 0.331763 0.102410 0.054217
123 D 3 3 0 0 7.924500e+02 4.755000e+01 0.000000e+00 8.400000e+02 ... 2.002358e+05 2.732385e+04 3.960850e+04 2.275597e+05 2.267197e+05 1.000000 1.000000 1.000000 0.470588 0.000000

123 rows × 24 columns

pa0.iloc[:,0].value_counts()
B    38
C    34
A    27
D    24
Name: 信誉评级, dtype: int64
#替换指标值、删除多余项
pa1=pa0
pa1=pa1.replace('是',0)
pa1=pa1.replace('否',1)
pa1=pa1.replace('A',100)
pa1=pa1.replace('B',80)
pa1=pa1.replace('C',52.45)
pa1=pa1.replace('D',1)

pa1.drop(pa1.columns[range(2,18)],axis=1,inplace=True)
pa1.drop(pa1.columns[range(3,5)],axis=1,inplace=True)
pa1
信誉评级 是否违约 收入 供求稳定度指标 作废发票率 负数发票率
1 100.00 1 -1.939309e+09 0.401188 0.036014 0.025885
2 100.00 1 4.638077e+08 0.199108 0.039297 0.011457
3 52.45 1 6.068909e+08 0.419636 0.020221 0.154781
4 52.45 1 1.891956e+09 0.535643 0.081391 0.004661
5 80.00 1 5.958721e+06 0.502267 0.043357 0.008052
... ... ... ... ... ... ...
119 1.00 0 -2.129928e+05 0.588052 0.011905 0.002976
120 1.00 0 1.769471e+05 0.437655 0.323077 0.000000
121 1.00 0 -1.136832e+06 0.544907 0.097458 0.004237
122 1.00 0 6.994340e+03 0.331763 0.102410 0.054217
123 1.00 0 2.267197e+05 1.000000 0.470588 0.000000

123 rows × 6 columns

#成本型指标转换,数据归一化
pa1['作废发票率']=(max(pa1['作废发票率'])-pa1['作废发票率'])/(max(pa1['作废发票率'])-min(pa1['作废发票率']))
pa1['负数发票率']=(max(pa1['负数发票率'])-pa1['负数发票率'])/(max(pa1['负数发票率'])-min(pa1['负数发票率']))
pa1=(pa1-pa1.min())/(pa1.max()-pa1.min())
pa2=np.asarray(pa1)
#熵权法计算权重
ta=pa1
tb=pa2
n,m=np.shape(tb)
s=np.sum(ta,axis=0)
s=np.asarray(s)
s=np.reshape(s,(1,len(s)))
s=np.repeat(s,len(tb),axis=0)
s=s.reshape((n,m))
tb=tb/s
a=tb*1.0
a[np.where(tb==0)]=0.001
e=(-1.0/np.log(n))*np.sum(tb*np.log(a),axis=0)
w=(1-e)/np.sum(1-e)
w
array([0.34111674, 0.33907811, 0.01653923, 0.24240319, 0.03652877,
       0.02433396])
#Topsis综合评价
df=pa2/np.sqrt((pa2**2).sum())
df=pd.DataFrame(df)
X=pd.DataFrame([df.min(),df.max()],index=['负理想解','正理想解'])
R=df.copy()
R.columns=['信誉评级','是否违约','收入','供求稳定度指标','作废发票率','负数发票率']
R['正理想解']=np.sqrt(((df - X.loc['正理想解']) ** 2 * w).sum(axis=1))
R['负理想解']=np.sqrt(((df - X.loc['负理想解']) ** 2 * w).sum(axis=1))
R['综合得分']=R['负理想解'] / (R['负理想解'] + R['正理想解'])
R['排序']=R.rank(ascending=False)['综合得分']
R['公司识别码']=pa1.index
R['利率']=15-(R['综合得分']-R['综合得分'].min())/(R['综合得分'].max()-R['综合得分'].min())*11
#保存topsisi分析结果
R.to_excel('result_a1.xls')

3.问题2

数据读取

#导入相关库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import zscore
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn import svm
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
#读取数据
data = pd.read_excel('b0.xlsx')
data2 =pd.read_excel('b0.xlsx',sheet_name=1)
data3 =pd.read_excel('b0.xlsx',sheet_name=2)
#将企业代号前的E去掉,使其成为数值型变量,便于排序
data['企业代号']=data['企业代号'].apply(lambda x:int(x[1:]))
data2['企业代号']=data2['企业代号'].apply(lambda x:int(x[1:]))
data3['企业代号']=data3['企业代号'].apply(lambda x:int(x[1:]))
#比较坑,附件一附件二进销项位置不一样,互换位置即可
temp=data2
data2=data3
data3=temp

数据概览

data
企业代号 企业名称
0 124 个体经营E124
1 125 个体经营E125
2 126 个体经营E126
3 127 个体经营E127
4 128 个体经营E128
... ... ...
297 421 ***保温材料有限公司
298 422 ***童装店
299 423 ***通风设备有限公司
300 424 ***贸易有限公司
301 425 ***商贸有限公司

302 rows × 2 columns

data2
企业代号 发票号码 开票日期 销方单位代号 金额 税额 价税合计 发票状态
0 124 18891676 2017-09-01 00:00:00 C00014 338.46 57.54 396.0 有效发票
1 124 18691267 2017-09-01 00:00:00 C00480 230.10 6.90 237.0 有效发票
2 124 12995412 2017-09-01 00:00:00 C23675 223.30 6.70 230.0 有效发票
3 124 6378193 2017-09-01 11:11:03 C00333 90090.09 9909.91 100000.0 有效发票
4 124 6378194 2017-09-01 11:12:01 C00333 90090.09 9909.91 100000.0 有效发票
... ... ... ... ... ... ... ... ...
395170 425 72101375 2019-12-30 00:00:00 C23112 663.11 19.89 683.0 有效发票
395171 425 20253285 2020-01-05 00:00:00 C01937 45.41 4.09 49.5 有效发票
395172 425 20253315 2020-01-05 00:00:00 C01937 110.14 1.16 111.3 有效发票
395173 425 52449404 2020-01-06 00:00:00 C15032 73.22 6.58 79.8 有效发票
395174 425 5666299 2020-01-10 00:00:00 C23112 132.04 3.96 136.0 有效发票

395175 rows × 8 columns

data3
企业代号 发票号码 开票日期 购方单位代号 金额 税额 价税合计 发票状态
0 124 15212483 2017-09-01 11:58:43 D00585 839350.55 92328.56 931679.11 有效发票
1 124 15212484 2017-09-01 11:59:20 D00585 900900.90 99099.10 1000000.00 有效发票
2 124 15212485 2017-09-01 11:59:51 D00585 900900.90 99099.10 1000000.00 有效发票
3 124 15212486 2017-09-01 12:00:45 D00585 697365.74 76710.23 774075.97 有效发票
4 124 6089615 2017-09-05 10:58:38 D00108 726216.22 79883.78 806100.00 有效发票
... ... ... ... ... ... ... ... ...
330830 425 21803468 2018-04-03 00:00:00 D21446 9000.00 270.00 9270.00 有效发票
330831 425 21803469 2018-04-03 00:00:00 D21446 5155.34 154.66 5310.00 有效发票
330832 425 21803470 2019-06-11 00:00:00 D02126 4854.37 145.63 5000.00 作废发票
330833 425 21803471 2019-06-11 00:00:00 D02126 4854.37 145.63 5000.00 作废发票
330834 425 21803472 2019-06-11 00:00:00 D02126 4854.37 145.63 5000.00 有效发票

330835 rows × 8 columns

数据预处理

#计算有效发票、负数发票和作废发票数量
def cnt(a,b,df):
    tot=0
    for i in range(a,b):
        if df.iloc[i,6]<0 and df.iloc[i,7] == '有效发票':
            tot+=1 
    if(len(df.iloc[a:b,:]['发票状态'].value_counts())==1):
        return  df.iloc[a:b,:]['发票状态'].value_counts()['有效发票'],0,tot
    return df.iloc[a:b,:]['发票状态'].value_counts()['有效发票'],df.iloc[a:b,:]['发票状态'].value_counts()['作废发票'],tot
#计算有效金额,有效税额,作废额
def cnt2(a,b,df):
    zf=0
    yxj=0
    yxs=0
    for i in range(a,b):
        if df.iloc[i,7] == '作废发票':
            zf+=df.iloc[i,6]
        else:
            yxj+=df.iloc[i,4]
            yxs+=df.iloc[i,5]
    return yxj,yxs,zf
#对进项发票进行统计
checkin=pd.DataFrame(data2['企业代号'].value_counts())
checkin.columns=['进项发票数量']
checkin.sort_index(inplace=True)

last=0
temp1=[]
temp2=[]
temp3=[]
temp4=[]
temp5=[]
temp6=[]
temp7=[]

for i in range(len(checkin)):
    a,b,c=cnt(last,last+int(checkin.iloc[i,0]),data2)
    d,e,f=cnt2(last,last+int(checkin.iloc[i,0]),data2)
    last=last+int(checkin.iloc[i,0])
    temp1.append(a)
    temp2.append(b)
    temp3.append(c)
    temp4.append(d)
    temp5.append(e)
    temp6.append(f)
    temp7.append(d+e)

checkin['进项有效发票']=temp1
checkin['进项作废发票']=temp2
checkin['进项负数发票']=temp3
checkin['进项有效金额']=temp4
checkin['进项有效税额']=temp5
checkin['进项无效额']=temp6
checkin['进项有效价税']=temp7
#对销项发票进行统计
checkout=pd.DataFrame(data3['企业代号'].value_counts())
checkout.columns=['销项发票数量']
checkout.sort_index(inplace=True)

last=0
temp1=[]
temp2=[]
temp3=[]
temp4=[]
temp5=[]
temp6=[]
temp7=[]

for i in range(len(checkout)):
    a,b,c=cnt(last,last+int(checkout.iloc[i,0]),data3)
    d,e,f=cnt2(last,last+int(checkout.iloc[i,0]),data3)
    last=last+int(checkout.iloc[i,0])
    temp1.append(a)
    temp2.append(b)
    temp3.append(c)
    temp4.append(d)
    temp5.append(e)
    temp6.append(f)
    temp7.append(d+e)
    
checkout['销项有效发票']=temp1
checkout['销项作废发票']=temp2
checkout['销项负数发票']=temp3
checkout['销项有效金额']=temp4
checkout['销项有效税额']=temp5
checkout['销项无效额']=temp6
checkout['销项有效价税']=temp7
#保存中间结果
checkin.to_excel('value_counts_in.xls')
checkout.to_excel('value_counts_out.xls')
#合并进项和销项发票收据数据,为进行下一步计算做准备
checks=pd.concat([checkin,checkout],axis=1)
#对发票进行汇总统计
checks['收入']=checks['销项有效价税']-checks['进项有效价税']

temp1=[]
temp2=[]
temp3=[]
temp4=[]
temp5=[]
last1=last2=0
a=b=0
for i in range(len(checks)):
    next1=last1+checks.iloc[i,0]
    next2=last2+checks.iloc[i,8]
    temp3=data2.iloc[last1:next1,3].value_counts()
    temp4=data3.iloc[last2:next2,3].value_counts()
    if(len(temp3)<=3):
        temp1.append(1)
        temp2.append(1)
        temp5.append(1)
    else:
        if(sum(temp3)==0):
            a=0
        else:
            a=sum(temp3[:3])/sum(temp3)
        if(sum(temp4)==0):
            b=0
        else:
            b=sum(temp4[:3])/sum(temp4)
        temp1.append(a)
        temp2.append(b)
        temp5.append(np.sqrt((a*a+b*b)/2))
    last1=next1
    last2=next2
    
checks['进稳定度指标']=temp1
checks['销稳定度指标']=temp2
checks['供求稳定度指标']=temp5

temp1=[]
temp2=[]
for i in range(len(checks)):
    sum1=sum2=sum3=0
    sum1=checks.iloc[i,0]+checks.iloc[i,8]
    sum2=checks.iloc[i,2]+checks.iloc[i,10]
    sum3=checks.iloc[i,3]+checks.iloc[i,11]
    temp1.append(sum2/sum1)
    temp2.append(sum3/sum1)
    
checks['作废发票率']=temp1
checks['负数发票率']=temp2
#保存中间结果
checks.to_excel('checks_2.xls')
#读取问题一的信誉评级数据
checks_2=pd.read_excel('checks_a1.xls',index_col=0)
#做标注,为下面的支持向量机做准备
labels=checks_2['信誉评级']
labels=labels.replace('A',1)
labels=labels.replace('B',2)
labels=labels.replace('C',3)
labels=labels.replace('D',4)
labels=np.asarray(labels)
#合并附件一和附件二的企业
checks_2.drop(['信誉评级','是否违约'],axis=1,inplace=True)
checks_3=pd.concat([checks_2,checks],axis=0)
checks_3
进项发票数量 进项有效发票 进项作废发票 进项负数发票 进项有效金额 进项有效税额 进项无效额 进项有效价税 销项发票数量 销项有效发票 ... 销项有效金额 销项有效税额 销项无效额 销项有效价税 收入 进稳定度指标 销稳定度指标 供求稳定度指标 作废发票率 负数发票率
1 3441 3249 192 71 5.744706e+09 8.932358e+08 2.547518e+08 6.637942e+09 8110 7886 ... 4.065843e+09 6.327901e+08 1.001785e+08 4.698633e+09 -1.939309e+09 0.515838 0.236252 0.401188 0.036014 0.025885
2 32156 31435 721 156 1.557623e+08 6.725653e+06 9.248509e+06 1.624880e+08 12707 11665 ... 5.908417e+08 3.545392e+07 6.841255e+07 6.262956e+08 4.638077e+08 0.268597 0.084520 0.199108 0.039297 0.011457
3 4561 4367 194 26 5.202698e+07 2.152374e+06 3.341486e+06 5.417935e+07 24073 23688 ... 5.701780e+08 9.089228e+07 2.166951e+07 6.610703e+08 6.068909e+08 0.168823 0.568936 0.419636 0.020221 0.154781
4 558 521 37 4 2.198771e+08 3.470711e+07 1.258232e+08 2.545842e+08 2231 2041 ... 1.839970e+09 3.065709e+08 1.990901e+08 2.146541e+09 1.891956e+09 0.261649 0.710892 0.535643 0.081391 0.004661
5 2169 2084 85 16 1.977850e+08 2.954699e+07 4.718235e+06 2.273320e+08 1060 1005 ... 2.026323e+08 3.065841e+07 9.497473e+06 2.332907e+08 5.958721e+06 0.393269 0.591509 0.502267 0.043357 0.008052
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
421 19 19 0 0 3.039381e+04 1.776190e+03 0.000000e+00 3.217000e+04 29 28 ... 2.457008e+05 7.371070e+03 0.000000e+00 2.530718e+05 2.209018e+05 0.894737 0.862069 0.878555 0.020833 0.000000
422 3 3 0 0 8.893900e+02 7.061000e+01 0.000000e+00 9.600000e+02 30 27 ... 2.701831e+04 8.383000e+02 1.351000e+03 2.785661e+04 2.689661e+04 1.000000 1.000000 1.000000 0.090909 0.000000
423 21 21 0 1 6.104614e+04 8.005560e+03 0.000000e+00 6.905170e+04 7 6 ... 7.278640e+04 2.183600e+03 5.770000e+03 7.497000e+04 5.918300e+03 0.714286 1.000000 0.868966 0.035714 0.035714
424 25 25 0 0 2.543299e+05 1.766949e+04 0.000000e+00 2.719994e+05 43 37 ... 7.689642e+04 2.306880e+03 1.148231e+04 7.920330e+04 -1.927961e+05 0.560000 0.534884 0.547586 0.088235 0.029412
425 118 116 2 3 5.719625e+04 4.885150e+03 2.678840e+03 6.208140e+04 18 10 ... 8.512621e+04 2.553790e+03 6.947200e+04 8.768000e+04 2.559860e+04 0.576271 1.000000 0.816115 0.073529 0.022059

425 rows × 22 columns

checks_3.to_excel('checks_3.xls')

问题二子问题一利率分配

#一些数据的初始化
pa0=checks_3
#pa1=pa0.iloc[:,[0,8,16,19,20,21]]
#pa1=pa0.drop(pa0.columns[[0,7,8,15,16,19,20,21]],axis=1)
pa1=pa0
pa1=np.asarray(pa1)
pa1=zscore(pa1)
ck=np.asarray(checks)
ck2=np.asarray(checks_2)
#主成分分析
pca=PCA()
pca.fit(pa1)
pcavr=[]
for i in range(1,23):
    pcavr.append(sum(pca.explained_variance_ratio_[:i]))
pcavr
[0.3667363880450508,
 0.5647177553788358,
 0.6694778602067868,
 0.7551550627474768,
 0.8131132267472697,
 0.865619957576671,
 0.9107898364534954,
 0.9387893796264828,
 0.9599599037916896,
 0.9788060451769551,
 0.988728920202568,
 0.9942716313124501,
 0.9978255167866447,
 0.999138389215358,
 0.9995923091351523,
 0.999967761573444,
 0.9999999766710131,
 1.0,
 1.0,
 1.0,
 1.0,
 1.0]
#PCA差异保留画图分析
X = range(1,23)
#plt.figure(figsize=(12,8))
plt.xlabel('n_components')
plt.title('Principal Component Analysis')
plt.ylabel('Explained Variance Ratio')
plt.plot(X,pcavr,'o-')
plt.locator_params('x',nbins=12)
plt.savefig('Principal_Component_Analysis.jpg')
plt.show()

在这里插入图片描述

#得到降维后的向量
pca_=PCA(n_components=8)
pa2=pca_.fit_transform(pa1)
#用于打乱训练集和测试集用
import random
rd=np.arange(123)
random.shuffle(rd)
#用支持向量机对前100个训练,后23个测试验证所得到的精度
clf = make_pipeline(StandardScaler(), svm.SVC(gamma='auto'))
clf.fit(pa2[rd[:100]],labels[rd[:100]])
clf.score(pa2[rd[100:123]],labels[rd[100:]])
0.2608695652173913
#对附件一所有企业进行训练,得到的训练精度
clf2 = make_pipeline(StandardScaler(), svm.SVC(gamma='auto'))
clf2.fit(pa2[:123],labels)
clf2.score(pa2[:123],labels)
0.5365853658536586
#得到信誉预测A指标
m1p=clf2.predict(pa2[123:])
labels=pd.DataFrame(labels)
m1p=pd.DataFrame(m1p)
c1=pd.concat([labels,m1p],axis=0)
c1.index=np.arange(1,426)
pa0['信誉预测A']=c1
#改写问题一topsis程序,不去除D,计算综合得分并归一化
ra1=pd.read_excel('result_a1.xls',index_col=0)
lb=(ra1['综合得分']-ra1['综合得分'].min())/(ra1['综合得分'].max()-ra1['综合得分'].min())
lb=np.asarray(lb)
#建立DNN密集链接神经网络模型
from keras import models
from keras import layers
def rmodel():
    model=models.Sequential()
    model.add(layers.Dense(64, activation='relu',
                       input_shape=(pa2.shape[1],)))
    model.add(layers.Dense(64, activation='relu'))
    model.add(layers.Dense(1))
    model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
    return model

model1=rmodel()
model1.fit(pa2[rd[:100]], lb[rd[:100]],epochs=100, batch_size=1,verbose=0)
val_mse, val_mae = model1.evaluate(pa2[rd[100:123]], lb[rd[100:123]], verbose=0)
Using TensorFlow backend.
#用DNN对前100个训练,后23个测试验证所得到的误差
val_mse,val_mae
(0.19183750450611115, 0.3098321855068207)
#训练模型
model2=rmodel()
model2.fit(pa2[:123], lb,epochs=100, batch_size=1,verbose=0)
val2_mse, val2_mae = model2.evaluate(pa2[:123], lb, verbose=0)
val2_mse, val2_mae
(0.055356581490941165, 0.11002491414546967)
#得到信誉预测B指标
m2p=model2.predict(pa2[123:])
m2p=pd.DataFrame(m2p)
lb=pd.DataFrame(lb)
c2=pd.concat([lb,m2p])
c2.index=range(1,426)
pa0['信誉预测B']=c2
#统计计算
pa3=pa0.iloc[123:,:]
pa3['信誉预测A'].replace(1,100,inplace=True)
pa3['信誉预测A'].replace(2,80,inplace=True)
pa3['信誉预测A'].replace(3,52.45,inplace=True)
pa3['信誉预测A'].replace(4,1,inplace=True)
pa3['作废发票率']=(max(pa3['作废发票率'])-pa3['作废发票率'])/(max(pa3['作废发票率'])-min(pa3['作废发票率']))
pa3['负数发票率']=(max(pa3['负数发票率'])-pa3['负数发票率'])/(max(pa3['负数发票率'])-min(pa3['负数发票率']))
pa3=(pa3-pa3.min())/(pa3.max()-pa3.min())
pa3=pa3[['信誉预测A','信誉预测B','收入','供求稳定度指标','作废发票率','负数发票率']]
pa4=np.asarray(pa3)
#熵权法计算权重
ta=pa3
tb=pa4
n,m=np.shape(tb)
s=np.sum(ta,axis=0)
s=np.asarray(s)
s=np.reshape(s,(1,len(s)))
s=np.repeat(s,len(tb),axis=0)
s=s.reshape((n,m))
tb=tb/s
a=tb*1.0
a[np.where(tb==0)]=0.001
e=(-1.0/np.log(n))*np.sum(tb*np.log(a),axis=0)
w=(1-e)/np.sum(1-e)
w
array([0.11221771, 0.11019597, 0.25695496, 0.47673639, 0.01765203,
       0.02624293])
#Topsis综合评价
df=pa4/np.sqrt((pa4**2).sum())
df=pd.DataFrame(df)
X=pd.DataFrame([df.min(),df.max()],index=['负理想解','正理想解'])
R=df.copy()
R.columns=['信誉评级','是否违约','收入','供求稳定度指标','作废发票率','负数发票率']
R['正理想解']=np.sqrt(((df - X.loc['正理想解']) ** 2 * w).sum(axis=1))
R['负理想解']=np.sqrt(((df - X.loc['负理想解']) ** 2 * w).sum(axis=1))
R['综合得分']=R['负理想解'] / (R['负理想解'] + R['正理想解'])
R['排序']=R.rank(ascending=False)['综合得分']
R['利率']=15-(R['综合得分']-R['综合得分'].min())/(R['综合得分'].max()-R['综合得分'].min())*11
#保存利率计算结果
R.to_excel('result_3.xls')

问题二子问题二额度分析

pb0=pa0
pb1=pb0.iloc[123:,[0,4,5,8,12,13,16,17,18,19,20,21]]#删去多余的指标
pb2=np.asarray(pb1)#转化为numpy数组,便于进行下一步计算
pb2=zscore(pb2)#数据标准化
#PCA主成分分析
pca=PCA()
pca.fit(pb2)
#计算差异保留比例
pcavr=[]
for i in range(1,13):
    pcavr.append(sum(pca.explained_variance_ratio_[:i]))
pcavr
[0.40237293073369423,
 0.5723379535072953,
 0.6867370550736526,
 0.7714374725780188,
 0.8524884204316454,
 0.9169752220290351,
 0.9662287460931756,
 0.9882960568245,
 0.9959509809020667,
 0.9993026536897576,
 0.9999999999999999,
 0.9999999999999999]
#PCA差异保留画图分析
X = range(1,13)
#plt.figure(figsize=(12,8))
plt.xlabel('n_components')
plt.title('Principal Component Analysis')
plt.ylabel('Explained Variance Ratio')
plt.plot(X,pcavr,'o-')
plt.locator_params('x',nbins=12)
plt.savefig('Principal_Component_Analysis_B.jpg')
plt.show()

在这里插入图片描述

#选取最佳维度6,保留91%差异性
pca_=PCA(n_components=6)
pb3=pca_.fit_transform(pb2)
#肘部法则计算最佳聚类数
SSE=[]
for k in range(2,21):
    km=KMeans(n_clusters=k,random_state=10)
    km.fit(pb3)
    SSE.append(km.inertia_)
    X = range(2,21)
    
#肘部法则画图分析
#plt.figure(figsize=(12,8))
plt.xlabel('k')
plt.title('Elbow Method')
plt.ylabel('SSE')
plt.plot(X,SSE,'o-')
plt.locator_params('x',nbins=20)
plt.savefig('Elbow_Method.jpg')
plt.show()

在这里插入图片描述

#轮廓系数计算最佳聚类数
SC=[]
for k in range(2,21):
    km=KMeans(n_clusters=k,random_state=10)
    km.fit(pb3)
    a=silhouette_score(pb3,km.labels_, metric='euclidean')
    SC.append(a)
    
#轮廓系数画图分析
X = range(2,21)
#plt.figure(figsize=(12,8))
plt.xlabel('k')
plt.title('Silhouette Coefficient')
plt.ylabel('SC')
plt.plot(X,SC,'o-')
plt.locator_params('x',nbins=20)
plt.savefig('Silhouette_Coefficient.jpg')
plt.show()

在这里插入图片描述

#选取最佳聚类数10进行聚类分析
km=KMeans(n_clusters=10,random_state=20)
km.fit(pb3)
#标签统计
pd.DataFrame(km.labels_)[0].value_counts()
6    87
1    87
2    36
0    35
7    31
9     9
5     8
8     4
4     3
3     2
Name: 0, dtype: int64
#加入标签
pb1['分类']=km.labels_
pb1
进项发票数量 进项有效金额 进项有效税额 销项发票数量 销项有效金额 销项有效税额 收入 进稳定度指标 销稳定度指标 供求稳定度指标 作废发票率 负数发票率 分类
124 17411 7.855255e+08 5.867726e+07 1293 7.417804e+08 6.665738e+07 -3.576505e+07 0.127793 0.323279 0.245805 0.125160 0.020477 3
125 20288 9.323832e+08 6.881856e+07 1595 9.412114e+08 8.362975e+07 2.363930e+07 0.121057 0.303448 0.231015 0.124617 0.020016 3
126 533 1.127735e+08 1.604526e+07 1516 5.206911e+08 1.731628e+07 4.091887e+08 0.465291 0.250000 0.373494 0.131772 0.017082 4
127 1450 1.646702e+06 1.188565e+05 4026 6.519380e+08 1.957022e+07 6.697426e+08 0.388966 0.467958 0.430278 0.027027 0.001096 4
128 3222 8.928033e+06 4.324670e+05 1255 2.423902e+08 8.299067e+06 2.413287e+08 0.307573 0.980876 0.726884 0.040652 0.003350 7
... ... ... ... ... ... ... ... ... ... ... ... ... ...
421 19 3.039381e+04 1.776190e+03 29 2.457008e+05 7.371070e+03 2.209018e+05 0.894737 0.862069 0.878555 0.020833 0.000000 0
422 3 8.893900e+02 7.061000e+01 30 2.701831e+04 8.383000e+02 2.689661e+04 1.000000 1.000000 1.000000 0.090909 0.000000 0
423 21 6.104614e+04 8.005560e+03 7 7.278640e+04 2.183600e+03 5.918300e+03 0.714286 1.000000 0.868966 0.035714 0.035714 0
424 25 2.543299e+05 1.766949e+04 43 7.689642e+04 2.306880e+03 -1.927961e+05 0.560000 0.534884 0.547586 0.088235 0.029412 6
425 118 5.719625e+04 4.885150e+03 18 8.512621e+04 2.553790e+03 2.559860e+04 0.576271 1.000000 0.816115 0.073529 0.022059 0

302 rows × 13 columns

#保存问题二子问题二额度分析结果
pb1.to_excel('result_4.xls')

4.问题3

根据调查结果修正利率

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
gsb=pd.read_excel('gsb.xlsx')
gsb['企业代号']=gsb['企业代号'].apply(lambda x:int(x[1:]))
gsb.columns=['企业代号','企业名称','企业评分']
gsb['企业评分'].replace([9,19,18,1,2,8,15,12,5,6,3,14,11,16,4,10,13,17,7],[int(i) for i in np.linspace(5,95,19)],inplace=True)
r3=pd.read_excel('result_3.xls',index_col=0)
r3['评分']=gsb['企业评分']
r3['修正利率']=(r3['评分']-50)*0.06
r3.to_excel('result_6.xls')

5.其他程序

主要是画图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

问题一-隶属函数

x=np.linspace(1,4,300)
y=(0.6952*np.log(x)+0.0362)*(x<3)+((1+1.1086*(x-0.8942)**(-2))**(-1))*(x>=3)
#plt.figure(figsize=(12,8))
plt.plot(x,y)
plt.title('Membership function')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('Membership_function.jpg')
plt.show()

在这里插入图片描述

问题一-不同公司的利率散点图和风险系数散点图

result1=pd.read_excel('result_1.xls',index_col=0)
x=result1['公司识别码']
y1=result1['利率']
y2=result1['综合得分']
y2=1-y2
plt.figure(figsize=(12,8))
plt.title('The interest rate of different companys')
plt.xlabel('Company ID')
plt.ylabel('The interest rate')
plt.plot(x,y1,'ro-')
plt.savefig('The_interest_rate_of_different_companys.jpg')

在这里插入图片描述

plt.figure(figsize=(12,8))
plt.title('The overall ratings of different companys')
plt.xlabel('Company ID')
plt.ylabel('The interest rate')
plt.plot(x,y2,'ro-')
plt.savefig('The_overall_ratings_of_different_companys.jpg')

在这里插入图片描述

问题二-不同公司的利率散点图和风险系数散点图

result3=pd.read_excel('result_3.xls',index_col=0)
x=range(1,303)
y1=result3['利率']
y2=result3['综合得分']
y2=1-y2
#plt.figure(figsize=(12,8))
plt.title('The interest rate of different companys')
plt.xlabel('Company ID')
plt.ylabel('The interest rate')
plt.plot(x,y1,'go-')
plt.savefig('The_interest_rate_of_different_companys.jpg')

在这里插入图片描述

#plt.figure(figsize=(12,8))
plt.title('The overall ratings of different companys')
plt.xlabel('Company ID')
plt.ylabel('The interest rate')
plt.plot(x,y2,'go-')
plt.savefig('The_overall_ratings_of_different_companys.jpg')

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/STL_CC/article/details/108591693