-- coding: utf-8 --
"""
Created on Sun Dec 23 01:10:07 2018
@author: NickyChu
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.linear_model import LogisticRegression as LR
from sklearn.linear_model import RandomizedLogisticRegression as RLR
In[121]:
df = pd.read_csv('Train.csv',header=None)#使用header选项让列名为从0开始的数列
df_new = pd.read_csv('Test.csv',header=None)
print(df.duplicated())#检查重复项
df = df.drop_duplicates()#清洗重复项
df
In[163]:
my_matrix = df
data_x=my_matrix.iloc[:,0:-1]
data_y=my_matrix.iloc[:,-1]
In[123]:
rlr = RLR() #建立随机逻辑回归模型,筛选变量
rlr.fit(data_x, data_y) #训练模型
array1 = rlr.get_support() #获取特征筛选结果,也可以通过.scores_方法获取各个特征的分数
score1 = rlr.scores_
score1
In[161]:
i = 1
for name in array1:
if name == True:
print("第{0}个特征值为有用特征值".format(i))
i = i+1
In[162]:
筛选特征值
data_x.columns = score1
df_new.columns = score1
todrop = [0]
try:
data_x.drop(todrop, inplace=True, axis=1)
df_new.drop(todrop, inplace=True, axis=1)
except:
print("No need to drop")
data_x
df_new
In[]
分组
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, auc
from sklearn.grid_search import GridSearchCV
X1_train, X1_test, y1_train, y1_test = train_test_split(data_x,data_y,test_size=0.33)
组内预测
lr=LR(C = 1.5, penalty = 'l1',class_weight='balanced')#逻辑回归模型
lr.fit(X1_train,y1_train)#train组内模拟
print('逻辑回归模型训练结束')
print('模型的平均正确率:%s' % lr.score(X1_train,y1_train))#输出模型平均正确率(不准确)
print(lr.get_params)#输出相关信息
y1_pre_val = lr.predict(X1_test)#train组内的预测函数
输出报告
print("Classification report (training):\n {0}".format(classification_report(y1_test,y1_pre_val,target_names=["0","1"])))
让他去预测一下test组的
y_val_old = lr.predict(df_new)
print(lr.get_params)#输出相关信息
In[]
parameter tuning
运用穷尽网格搜索
from sklearn.grid_search import GridSearchCV
lr_clf_tuned = LR()
tuned_parameters=[{'penalty':['l1','l2'],
'C':[0.01,0.05,0.1,0.5,1,1.1,1.2,1.3,1.4,1.5,10],
'solver':['liblinear'],
'multi_class':['ovr']},
{'penalty':['l2'],
'C':[0.01,0.05,0.1,0.5,1,1.1,1.2,1.3,1.4,1.5,10],
'solver':['lbfgs'],
'multi_class':['ovr','multinomial']}]
lr_clf_params = {"penalty": ["l1", "l2"], "C": [1, 1.1,1.2,1.3,1.4,1.5, 1.7, 2] }
lr_clf_cv = GridSearchCV(lr_clf_tuned, tuned_parameters, cv=5)
lr_clf_cv.fit(X1_train,y1_train)
print(lr_clf_cv.best_params_)
In[]
from sklearn.ensemble import RandomForestClassifier
lr=LR( C = 10, multi_class='ovr', penalty = 'l1', solver='lbfgs')#逻辑回归模型
lr.fit(X1_train,y1_train)
print('逻辑回归模型训练结束')
print('模型的平均正确率:%s' % lr.score(X1_train,y1_train))
print(lr.get_params)
y1_pre_val = lr.predict(X1_test)#train组内的预测函数
输出报告
print("Classification report (training):\n {0}".format(classification_report(y1_test,y1_pre_val,target_names=["0","1"])))
让他去预测一下test组的
y_val_new = lr.predict(df_new)
print(lr.get_params)#输出相关信息
In[]
寻找最优Roc值
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, auc
from sklearn.metrics import roc_auc_score
def FindtheC():
score = []
aucarr = []
Conclu = []
for i in range(1,100):
i = 64
play = i/1000
for j in range(1,100):
j = 67时 达到 0.699的AUC
Canshu = j
lr=LR(C = Canshu, multi_class='ovr', penalty = 'l2', solver='liblinear',class_weight={0: play, 1: 1-play})#逻辑回归模型
lr.fit(X1_train,y1_train)
print('逻辑回归模型训练结束')
print('模型的平均正确率:%s' % lr.score(X1_train,y1_train))
print(lr.get_params)
y1_pre_test1 = lr.predict(X1_test)#预测函数
auc1 = "ROC是{0}".format(roc_auc_score(y1_test, y1_pre_test1))
print(auc1)
aucarr.append(roc_auc_score(y1_test, y1_pre_test1))
Conclu.append([auc1,Canshu])
print(max(aucarr))
In[]
pre_probs = lr.predict_log_proba(data_x)
print(pre_probs[:,1])
print(pre_probs[:,0])
In[]
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LogisticRegression
参数调整
x_train = X1_train
y_train = y1_train
x_test = X1_test
y_test = y1_test
def show_accuracy(a, b, tip):
acc = a.ravel() == b.ravel()
acc_rate = 100 * float(acc.sum()) / a.size
return acc_rate
Maincode
lr = LogisticRegression(penalty='l2')
lr.fit(x_train, y_train)
y_hat = lr.predict(x_test)
lr_rate = show_accuracy(y_hat, y_test, 'Logistic回归 ')
print(roc_auc_score(y_test, y_hat))
随机森林 n_estimators:决策树的个数,越多越好,不过值越大,性能就会越差,至少100
rfc = RandomForestClassifier(n_estimators=100)
rfc.fit(x_train, y_train)
y_hat = rfc.predict(x_test)
rfc_rate = show_accuracy(y_hat, y_test, '随机森林 ')
print(roc_auc_score(y_test, y_hat))
In[]
XGBoost
import xgboost as xgb
data_train = xgb.DMatrix(x_train, label=y_train)
data_test = xgb.DMatrix(x_test, label=y_test)
watch_list = [(data_test, 'eval'), (data_train, 'train')]
param = {'max_depth': 6, 'eta': 0.8, 'silent': 1, 'objective': 'binary:logistic'}
bst = xgb.train(param, data_train, num_boost_round=100, evals=watch_list)
y_hat = bst.predict(data_test)
y_hat[y_hat > 0.5] = 1
y_hat[~(y_hat > 0.5)] = 0
xgb_rate = show_accuracy(y_hat, y_test, 'XGBoost ')
print(roc_auc_score(y_test, y_hat))
In[]
ROC图所需参数
y1 = lr.predict_proba(data_x)
y1_valid_score_lr1 = lr.predict_proba(data_x)
fpr_lr1, tpr_lr1, thresholds_lr1 = roc_curve(data_y, y1_valid_score_lr1[:, 1])
roc_auc_lr1 = auc(fpr_lr1, tpr_lr1)
作ROC图
plt.plot(fpr_lr1, tpr_lr1, lw=2, alpha=.6)
plt.plot([0, 1], [0, 1], lw=2, linestyle="--")
plt.xlim([0, 1])
plt.ylim([0, 1.05])
plt.xlabel("FPR")
plt.ylabel("TPR")
plt.title("ROC curve")