跟我学算法-Logistic回归
虽然Logistic回归叫回归,但是其实它是一个二分类或者多分类问题
这里的话我们使用信用诈骗的数据进行分析
第一步:导入数据,Amount的数值较大,后续将进行(-1,1)的归一化
data = pd.read_csv('creditcard.csv') #读取数据
#查看前5行数据
print(data.head())

第二步: 对正常和欺诈的数目进行查看,正常样本的数目远大于欺诈样本,这个时候可以使用下采样或者过采样
# 画图查看
count_data = pd.value_counts(data['Class'], sort=True).sort_index() #统计样本数
count_data.plot(kind='bar') #画条形图
plt.title("Fraud class histogram") #标题
plt.xlabel('Classes')
plt.ylabel('Frequency')
plt.show()

第三步:将amount进行归一化形成amountNorm,并且去除time和amount项
#把amount数据标准化到-1, 1
from sklearn.preprocessing import StandardScaler
#reshape 需要转换到的数值范围
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_record_fraud = len(data[data.Class==1])
#找出其索引,组成数组
fraud_indices = np.array(data[data.Class == 1].index)
norm_indices = data[data.Class == 0 ].index
#从Class=0中任意挑选500个组成正常的类别
random_norm_indices = np.random.choice(norm_indices, 500, replace=False)
random_norm_indices = np.array(random_norm_indices) #把正常的类别和欺诈类别进行组合
under_sample_indices = np.concatenate([fraud_indices, random_norm_indices])
#根据重组索引重新取值
under_sample_datas = data.iloc[under_sample_indices,:]
#选择出属性和结果
X_undersample = under_sample_datas.ix[:, under_sample_datas.columns != 'Class']
第5步,交叉验证选择权重,这里采用的加权方法为|L* w|
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import KFold, cross_val_score
from sklearn.metrics import confusion_matrix,recall_score,classification_report
def printing_Kfold_socres(x_train_data, y_train_data):
fold = KFold(len(y_train_data), 5, shuffle=False) c_param_range = [0.01, 0.1, 1, 10, 100]
#创建一个空的列表用来存储Mean recall score的值
results_table = pd.DataFrame(index=range(len(c_param_range), 2), columns=['C_parameter', 'Mean recall score']) results_table['C_parameter'] = c_param_range j = 0
for c_param in c_param_range:
print('-----------------------')
print('C paramter:', c_param)
print('-----------------------')
print('') recall_accs = []
for iteration, indices in enumerate(fold, start=1):
lr = LogisticRegression(C = c_param, penalty='l1') #放入参数,权重模式为l1
print('indices', indices)
#建立模型并训练
lr.fit(x_train_data.iloc[indices[0], :], y_train_data.iloc[indices[0], :].values.ravel())
y_pred_undersample = lr.predict(x_train_data.iloc[indices[1], :].values)
print(y_pred_undersample)
#计算回归得分
recall_acc = recall_score(y_train_data.iloc[indices[1],:].values, y_pred_undersample)
recall_accs.append(recall_acc)
print('Iteration', iteration, ': recall score=', recall_acc) #求得平均的值
results_table.ix[j, 'Mean recall score'] = np.mean(recall_accs)
j += 1
print('')
print('Mean recall score', np.mean(recall_accs))
print('')
# 数据类型进行转换
results_table['Mean recall score'] = results_table['Mean recall score'].astype('float64')
# 求得Mean recall score 对应的最大的C_parameter值
best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']
print('*********************************************************************************')
print('Best model to choose from cross validation is with C parameter = ', best_c)
print('*********************************************************************************') return best_c #执行程序
best_c = printing_Kfold_socres(X_train_undersample, y_train_undersample)
跟我学算法-Logistic回归的更多相关文章
- 【机器学习】分类算法——Logistic回归
一.LR分类器(Logistic Regression Classifier) 在分类情形下,经过学习后的LR分类器是一组权值w0,w1, -, wn,当测试样本的数据输入时,这组权值与测试数据按照线 ...
- 机器学习算法-logistic回归算法
Logistic回归算法调试 一.算法原理 Logistic回归算法是一种优化算法,主要用用于只有两种标签的分类问题.其原理为对一些数据点用一条直线去拟合,对数据集进行划分.从广义上来讲这也是一种多元 ...
- Logistic回归(逻辑回归)和softmax回归
一.Logistic回归 Logistic回归(Logistic Regression,简称LR)是一种常用的处理二类分类问题的模型. 在二类分类问题中,把因变量y可能属于的两个类分别称为负类和正类, ...
- 《机器学习实战》-逻辑(Logistic)回归
目录 Logistic 回归 本章内容 回归算法 Logistic 回归的一般过程 Logistic的优缺点 基于 Logistic 回归和 Sigmoid 函数的分类 Sigmoid 函数 Logi ...
- 常见算法(logistic回归,随机森林,GBDT和xgboost)
常见算法(logistic回归,随机森林,GBDT和xgboost) 9.25r早上面网易数据挖掘工程师岗位,第一次面数据挖掘的岗位,只想着能够去多准备一些,体验面这个岗位的感觉,虽然最好心有不甘告终 ...
- 神经网络、logistic回归等分类算法简单实现
最近在github上看到一个很有趣的项目,通过文本训练可以让计算机写出特定风格的文章,有人就专门写了一个小项目生成汪峰风格的歌词.看完后有一些自己的小想法,也想做一个玩儿一玩儿.用到的原理是深度学习里 ...
- Logistic回归分类算法原理分析与代码实现
前言 本文将介绍机器学习分类算法中的Logistic回归分类算法并给出伪代码,Python代码实现. (说明:从本文开始,将接触到最优化算法相关的学习.旨在将这些最优化的算法用于训练出一个非线性的函数 ...
- 第三集 欠拟合与过拟合的概念、局部加权回归、logistic回归、感知器算法
课程大纲 欠拟合的概念(非正式):数据中某些非常明显的模式没有成功的被拟合出来.如图所示,更适合这组数据的应该是而不是一条直线. 过拟合的概念(非正式):算法拟合出的结果仅仅反映了所给的特定数据的特质 ...
- 机器学习之Logistic 回归算法
1 Logistic 回归算法的原理 1.1 需要的数学基础 我在看机器学习实战时对其中的代码非常费解,说好的利用偏导数求最值怎么代码中没有体现啊,就一个简单的式子:θ= θ - α Σ [( hθ( ...
随机推荐
- 线性回归 Linear regression(1)线性回归的基本算法与求解
本系列内容大部分来自Standford公开课machine learning中Andrew老师的讲解,附加自己的一些理解,编程实现和学习笔记. 第一章 Linear regression 1.线性回归 ...
- POJ1733 Parity game 【带权并查集】*
POJ1733 Parity game Description Now and then you play the following game with your friend. Your frie ...
- jquery ajax 超时设置
自:jquery ajax超时设置 var ajaxTimeoutTest = $.ajax({ url:'', //请求的URL timeout : 1000, //超时时间设置,单位毫秒 typ ...
- 重温CLR(十一) 枚举类型、位标志和数组
枚举类型 枚举类型(enumerated types)定义了一组"符号名称/值"配对.例如,以下Color类型定义了一组符号,每个符号都标识一种颜色: internal enum ...
- Buy Tickets(线段树单点更新,逆向思维)
题目大意:有n个的排队,每一个人都有一个val来对应,每一个后来人都会插入当前队伍的某一个位置pos.要求把队伍最后的状态输出. 个人心得:哈哈,用链表写了下,果不其然超时了,后面转念一想要用静态数组 ...
- 【DUBBO】Dubbo原理解析-Dubbo内核实现之SPI简单介绍
Dubbo采用微内核+ 插件体系,使得设计优雅,扩展性强.那所谓的微内核+插件体系是如何实现的呢!大家是否熟悉spi(service providerinterface)机制,即我们定义了服务接口标准 ...
- centos6.5 ifconfig没有ipv4地址
进入/etc/sysconfig/network-scripts/目录中,可以看到ifcfg-eth0文件, vi ifcfg-eth0编辑文件, 将“ONBOOT=no” 选项改成“ONBOOT=y ...
- Mybatis新增返回主键的两种方法 (mysql)
1.自增:LAST_INSERT_ID (自动返回最后一个INSERT或 UPDATE 问询为 AUTO_INCREMENT列设置的第一个 发生的值.) <!-- mysql的自增ID :LAS ...
- bzoj 4815 [Cqoi2017]小Q的表格——反演+分块
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4815 大概就是推式子的时候注意有两个边界都是 n ,考虑变成 2*... 之类的. 分块维护 ...
- bzoj1087互不侵犯King(状压)
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1087 简单的状压dp.但是wa了好几发.注意long long. 注意0和0的连边.而且不能 ...