有关信用卡欺诈的那个例子
附件那边上传大小必须2m以下,我就只取了csv前面几行数据
代码是这样写的:
#信用卡欺诈检测
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#%matplotlib inline 魔法方法ipython中用
data = pd.read_csv(r"D:\储存\学习\唐宇迪python\01、python数据分析与机器学习实战\课程资料\唐宇迪-机器学习课程资料\机器学习算法配套案例实战\逻辑回归-信用卡欺诈检测\creditcard.csv")
count_classes = pd.value_counts(data['Class'], sort = True).sort_index()
count_classes.plot(kind = 'bar') #建立柱状图
plt.title("Fraud class histogram")
plt.xlabel("Class")
plt.ylabel("Frequency")
from sklearn.preprocessing import StandardScaler
data['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1, 1))
data = data.drop(['Time','Amount'],axis=1)
X = data.ix[:, data.columns != 'Class']
y = data.ix[:, data.columns == 'Class']
number_records_fraud = len(data)
fraud_indices = np.array(data.index)
normal_indices = data.index
random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)
random_normal_indices = np.array(random_normal_indices)
under_sample_indices = np.concatenate()
under_sample_data = data.iloc
X_undersample = under_sample_data.ix[:, under_sample_data.columns != 'Class']
y_undersample = under_sample_data.ix[:, under_sample_data.columns == 'Class']
# Showing ratio
print("Percentage of normal transactions: ", len(under_sample_data)/len(under_sample_data))
print("Percentage of fraud transactions: ", len(under_sample_data)/len(under_sample_data))
print("Total number of transactions in resampled data: ", len(under_sample_data))
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)
print("Number transactions train dataset: ", len(X_train))
print("Number transactions test dataset: ", len(X_test))
print("Total number of transactions: ", len(X_train)+len(X_test))
# 下采样
X_train_undersample, X_test_undersample, y_train_undersample, y_test_undersample = train_test_split(X_undersample,y_undersample,test_size = 0.3,random_state = 0)
print("")
print("Number transactions train dataset: ", len(X_train_undersample))
print("Number transactions test dataset: ", len(X_test_undersample))
print("Total number of transactions: ", len(X_train_undersample)+len(X_test_undersample))
#Recall = TP/(TP+FN)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix,recall_score,classification_report
#交叉验证
def printing_Kfold_scores(x_train_data,y_train_data):
fold = KFold(5,shuffle=False)
# fold.get_n_splits(len(y_train_data))
# 定义不同正则化惩罚力度
c_param_range =
#可视化显示
results_table = pd.DataFrame(index = range(len(c_param_range),2), columns = ['C_parameter','Mean recall score'])
results_table['C_parameter'] = c_param_range
# the k-fold will give 2 lists: train_indices = indices, test_indices = indices
j = 0
for c_param in c_param_range:
print('-------------------------------------------')
print('C parameter: ', c_param)
print('-------------------------------------------')
print('')
recall_accs = []
for iteration, indices in fold.split(X):
lr = LogisticRegression(C = c_param, penalty = 'l1')
# Use the training data to fit the model. In this case, we use the portion of the fold to train the model
# with indices. We then predict on the portion assigned as the 'test cross validation' with indices
lr.fit(x_train_data.iloc,:],y_train_data.iloc,:].values.ravel())
# Predict values using the test indices in the training data
y_pred_undersample = lr.predict(x_train_data.iloc,:].values)
# Calculate the recall score and append it to a list for recall scores representing the current c_parameter
recall_acc = recall_score(y_train_data.iloc,:].values,y_pred_undersample)
recall_accs.append(recall_acc)
print('Iteration ', iteration,': recall score = ', recall_acc)
# The mean value of those recall scores is the metric we want to save and get hold of.
results_table.ix = np.mean(recall_accs)
j += 1
print('')
print('Mean recall score ', np.mean(recall_accs))
print('')
best_c = results_table.loc.idxmax()]['C_parameter']
# Finally, we can check which C parameter is the best amongst the chosen.
print('*********************************************************************************')
print('Best model to choose from cross validation is with C parameter = ', best_c)
print('*********************************************************************************')
return best_c
best_c = printing_Kfold_scores(X_train_undersample,y_train_undersample)
===========================================================================================
结果就返回错误:
ValueError: Expected 2D array, got 1D array instead:
array=[-1.863755553.44264398 -4.468259732.80533626 -2.11841248 -2.33228489
-4.2612372 1.70168184 -1.43939588 -6.999906636.31620968 -8.670818
0.31602399 -7.41771206 -0.43653747 -3.65280196 -6.29314532 -1.24324829
0.364810480.360924 0.66792657 -0.51624236 -0.012217810.0706137
0.058504470.304882840.418012470.20885828 -0.34923131].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
是这行有什么问题嘛?辛苦各位大神帮忙看看啦~{:10_329:}
lr.fit(x_train_data.iloc,:],y_train_data.iloc,:].values.ravel()) 维度不对,期待的是二维矩阵,而且都提示将其reshape下就行,至于哪个维度该是1,你自己跑的应该更明白 塔利班 发表于 2019-12-11 16:36
维度不对,期待的是二维矩阵,而且都提示将其reshape下就行,至于哪个维度该是1,你自己跑的应该更明白
加了个冒号,维度应该没问题了,可是又提示
ValueError: Found array with 0 sample(s) (shape=(0, 29)) while a minimum of 1 is required.
这又是怎么回事呢?
我查了下如果加填个print(y_train_data.iloc:,:].values.ravel())
他只有第一次有数据,后面循环得到的全都是[] Astray.R 发表于 2019-12-11 21:35
加了个冒号,维度应该没问题了,可是又提示
ValueError: Found array with 0 sample(s) (shape=(0, 29)) ...
没时间跑你的数据,你把numpy数组搞明白就行,还有你的indices也搞明白 解决办法:
for iteration, indices in fold.split(X)改成
for iteration, indices in enumerate(fold.split(x_train_data), start=1) X = data.ix[:, data.columns != 'Class']
y = data.ix[:, data.columns == 'Class']
X = data.ix[:, data.columns != 'Class']
y = data.ix[:, data.columns == 'Class']
这两段代码该怎么理解呢
页:
[1]