一:线性logistic 回归

代码如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.optimize as opt
import seaborn as sns #读取数据集
path = 'ex2data1.txt'
data = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted']) #将正负数据集分开
positive = data[data['Admitted'].isin([1])]
negative = data[data['Admitted'].isin([0])] '''
#查看分布
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(positive['Exam 1'], positive['Exam 2'], s=60, c='b', marker='o', label='Admitted')
ax.scatter(negative['Exam 1'], negative['Exam 2'], s=50, c='r', marker='x', label='UnAdmitted')
ax.legend()
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')
plt.show()
''' #sigmoid函数实现
def sigmoid(h):
return 1 / (1 + np.exp(-h)) '''
#测试sigmoid函数
nums = np.arange(-10, 11, step=1)
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(nums, sigmoid(nums), 'k')
plt.show()
''' #计算损失函数值
def cost(theta, X, y):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y) part1 = np.multiply(-y, np.log(sigmoid(X * theta.T)))
part2 = np.multiply((1-y), np.log(1-sigmoid(X * theta.T)))
return np.sum(part1-part2) / len(X) #在原矩阵第1列前加一列全1
data.insert(0, 'ones', 1) cols = data.shape[1] X = data.iloc[:, 0:cols-1]
y = data.iloc[:, cols-1:cols] X = np.array(X.values)
y = np.array(y.values)
theta = np.zeros(3) #这里是一个行向量 #返回梯度向量,注意是向量
def gradient(theta, X, y):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y) parameters = theta.ravel().shape[1]
grad = np.zeros(parameters) error = sigmoid(X * theta.T) - y grad = error.T.dot(X)
grad = grad / len(X)
return grad #通过高级算法计算出最好的theta值
result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args=(X, y)) #print(cost(result[0], X, y)) #测试所得theta的性能
#计算原数据集的预测情况
def predict(theta, X):
theta = np.matrix(theta)
X = np.matrix(X) probability = sigmoid(X * theta.T)
return [1 if i > 0.5 else 0 for i in probability] theta_min = result[0]
predictions = predict(theta_min, X) correct = [1 if((a == 1 and b == 1) or(a == 0 and b == 0)) else 0 for(a, b) in zip(predictions, y)]
accuracy = (sum(map(int, correct)) % len(correct))
print('accuracy = {0}%'.format(accuracy))#训练集测试准确度89% # 作图
theta_temp = theta_min
theta_temp = theta_temp / theta_temp[2] x = np.arange(130, step=0.1)
y = -(theta_temp[0] + theta_temp[1] * x)
#画出原点
sns.set(context='notebook', style='ticks', font_scale=1.5)
sns.lmplot('Exam 1', 'Exam 2', hue='Admitted', data=data,
size=6,
fit_reg=False,
scatter_kws={"s": 25}
)
#画出分界线
plt.plot(x, y, 'grey')
plt.xlim(0, 130)
plt.ylim(0, 130)
plt.title('Decision Boundary')
plt.show()

二:非线性logistic 回归(正则化)

代码如下:

import pandas as pd
import numpy as np
import scipy.optimize as opt
import matplotlib.pyplot as plt path = 'ex2data2.txt'
data = pd.read_csv(path, header=None, names=['Test 1', 'Test 2', 'Accepted']) positive = data[data['Accepted'].isin([1])]
negative = data[data['Accepted'].isin([0])] '''
#显示原始数据的分布
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(positive['Test 1'], positive['Test 2'], s=50, c='b', marker='o', label='Accepted')
ax.scatter(negative['Test 1'], negative['Test 2'], s=50, c='r', marker='x', label='Unaccepted')
ax.legend() #显示右上角的Accepted 和 Unaccepted标签
ax.set_xlabel('Test 1 Score')
ax.set_ylabel('Test 2 Score')
plt.show()
'''
degree = 5
x1 = data['Test 1']
x2 = data['Test 2']
#在data的第三列插入一列全1
data.insert(3, 'Ones', 1) #创建多项式特征值,最高阶为4
for i in range(1, degree):
for j in range(0, i):
data['F' + str(i) + str(j)] = np.power(x1, i-j) * np.power(x2, j) #删除原数据中的test 1和test 2两列
data.drop('Test 1', axis=1, inplace=True)
data.drop('Test 2', axis=1, inplace=True) #sigmoid函数实现
def sigmoid(h):
return 1 / (1 + np.exp(-h)) def cost(theta, X, y, learnRate):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y) first = np.multiply(-y, np.log(sigmoid(X * theta.T)))
second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))
reg = (learnRate / (2 * len(X))) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2))
return np.sum(first - second) / len(X) + reg learnRate = 1
cols = data.shape[1] X = data.iloc[:, 1:cols]
y = data.iloc[:, 0:1] X = np.array(X)
y = np.array(y)
theta = np.zeros(X.shape[1]) #计算原数据集的预测情况
def predict(theta, X):
theta = np.matrix(theta)
X = np.matrix(X) probability = sigmoid(X * theta.T)
return [1 if i > 0.5 else 0 for i in probability] def gradientReg(theta, X, y, learnRate):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y) paramates = int(theta.ravel().shape[1])
grad = np.zeros(paramates) grad = (sigmoid(X * theta.T) - y).T * X / len(X) + (learnRate / len(X)) * theta[:, i]
grad[0] = grad[0] - (learnRate / len(X)) * theta[:, i]
return grad result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradientReg, args=(X, y, learnRate))
print(result) theta_min = np.matrix(result[0])
predictions = predict(theta_min, X)
correct = [1 if((a == 1 and b == 1) or(a == 0 and b == 0)) else 0 for(a, b) in zip(predictions, y)]
accuracy = (sum(map(int, correct)) % len(correct)) print('accuracy = {0}%'.format(accuracy))

logistic 回归(线性和非线性)的更多相关文章

  1. 浅谈Logistic回归及过拟合

    判断学习速率是否合适?每步都下降即可.这篇先不整理吧... 这节学习的是逻辑回归(Logistic Regression),也算进入了比较正统的机器学习算法.啥叫正统呢?我概念里面机器学习算法一般是这 ...

  2. 机器学习公开课笔记(3):Logistic回归

    Logistic 回归 通常是二元分类器(也可以用于多元分类),例如以下的分类问题 Email: spam / not spam Tumor: Malignant / benign 假设 (Hypot ...

  3. Logistic回归总结

    原文:http://blog.csdn.net/dongtingzhizi/article/details/15962797  Logistic回归总结 作者:洞庭之子 微博:洞庭之子-Bing (2 ...

  4. 机器学习(4)之Logistic回归

    机器学习(4)之Logistic回归 1. 算法推导 与之前学过的梯度下降等不同,Logistic回归是一类分类问题,而前者是回归问题.回归问题中,尝试预测的变量y是连续的变量,而在分类问题中,y是一 ...

  5. Logistic回归(逻辑回归)和softmax回归

    一.Logistic回归 Logistic回归(Logistic Regression,简称LR)是一种常用的处理二类分类问题的模型. 在二类分类问题中,把因变量y可能属于的两个类分别称为负类和正类, ...

  6. logistic回归学习

    logistic回归是一种分类方法,用于两分类的问题,其基本思想为: 寻找合适的假设函数,即分类函数,用来预测输入数据的结果: 构造损失函数,用来表示预测的输出结果与训练数据中实际类别之间的偏差: 最 ...

  7. Logistic回归和SVM的异同

    这个问题在最近面试的时候被问了几次,让谈一下Logistic回归(以下简称LR)和SVM的异同.由于之前没有对比分析过,而且不知道从哪个角度去分析,一时语塞,只能不知为不知. 现在对这二者做一个对比分 ...

  8. 机器学习-- Logistic回归 Logistic Regression

    转载自:http://blog.csdn.net/linuxcumt/article/details/8572746 1.假设随Tumor Size变化,预测病人的肿瘤是恶性(malignant)还是 ...

  9. 【转载】logistic回归

    原文地址:https://www.cnblogs.com/zichun-zeng/p/3824745.html 1. logistic回归与一般线性回归模型的区别: (1)     线性回归的结果变量 ...

随机推荐

  1. bay——RAC 表空间时数据文件误放置到本地文件系统-介质恢复.txt

    RAC添加新表空间时数据文件误放置到本地文件系统的修正 于是我想11G 也兼容这些操作的方法,但是11G的新特性有一点就是可以直接支持ASM文件系统直接可以和本地文件系统进行文件的拷贝了,也就是有三种 ...

  2. gcc-stack-protector机制【转】

    转自:https://blog.csdn.net/lhl_blog/article/details/70193865 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上 ...

  3. Less(4)

    1.先判断注入类型 (1)首先看到要求,要求传一个ID参数,并且要求是数字型的:?id=1 (2)再输入?id=1' 界面无变化 (3)再输入?id=1'' 界面还是无变化, (4)再输入?id=1 ...

  4. 201871010112-梁丽珍《面向对象程序设计(java)》第十六周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  5. flask之web网关、三件套、配置、路由(参数、转化器及自定义转化器)、cbv、模板语言、session

    目录 1.wsgiref.py 2.werzeug.py 3.三件套 4.配置文件 5.路由本质 6.cbv.py 7.路由转化器 8.自定义转化器 9.模板语言 10.session原理 11.te ...

  6. python爬虫之csv文件

     一.二维数据写入csv文件 题目要求: 读入price2016.csv文件,将其中的数据读出,将数字部分计算百分比后输出到price2016out.csv文件中 知识点: 对于列表中存储的二维数据, ...

  7. [java 基础]反射入门

    原文 概况 使用java的反射,可以让我们检查(或者修改)类,接口,字段,方法的特性.当你在编译期不知道他们的名字的时候非常有用. 除此之外,可以使用反射来创建实例,调用方法或者get/set 字段值 ...

  8. IT兄弟连 Java语法教程 数组 数组的声明

    Java语言支持两种语法格式来定义数组: type[] arrayName; type arrayName[]; 对这两种语法格式而言,通常推荐使用第一种格式,因为第一种格式不仅具有更好的语义,而且具 ...

  9. 解决centos下tomcat启动太慢 & JDBC连接oracle太慢的问题

    近期遇到一个非常奇怪的问题,也不知道改了什么,tomcat启动非常慢,以前几秒就启动好了,现在要30秒左右. 而且,通过jdbc连接oracle数据库也非常慢,以前建立一个连接只要几十毫秒,现在也要1 ...

  10. Python 十大装 X 语法(二)

    Python 是一种代表简单思想的语言,其语法相对简单,很容易上手.不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了.本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并 ...