机器学习 Logistic 回归
Logistic regression
适用于二分分类的算法,用于估计某事物的可能性。
logistic分布表达式
$ F(x) = P(X<=x)=\frac{1}{1+e^{\frac{-(x-\mu)}{\gamma}}} $
$ f(x) = F{'}(x)=\frac{e{\frac{-(x-\mu)}{\gamma}}}{\gamma(1+e{\frac{-(x-\mu)}{\gamma}}){2}} $
函数图像

分布函数属于逻辑斯谛函数,以点 \((\mu,\frac{1}{2})\) 为中心对称
逻辑回归是一种学习算法,用于有监督学习问题时,输出y都是0或1。逻辑回归的目标是最小化预测和训练数据之间的误差。
公式推导

代码实现
from math import exp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
def create_data():
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
data = np.array(df.iloc[:100, [0, 1, -1]])
return data[:, :2], data[:, -1]
class LogisticRegressionClassifier:
def __init__(self, max_iter=200, learning_rate=0.01, random_state=4):
self.max_iter = max_iter
self.learning_rate = learning_rate
self.weights = None
def sigmoid(self, x):
return 1 / (1 + exp(-x))
def data_matrix(self, X):
data_mat = []
for d in X:
data_mat.append([1.0, *d])
return data_mat
def fit(self, X, y):
data_mat = self.data_matrix(X)
self.weights = np.zeros((len(data_mat[0]), 1), dtype=np.float32)
for iter_ in range(self.max_iter):
for i in range(len(X)):
result = self.sigmoid(np.dot(data_mat[i], self.weights))
error = y[i] - result
self.weights += self.learning_rate * error * np.transpose([data_mat[i]])
print('LogisticRegression Model(learning_rate={},max_iter={})'.format(self.learning_rate, self.max_iter))
def score(self, X_test, y_test):
right = 0
X_test = self.data_matrix(X_test)
for x, y in zip(X_test, y_test):
result = np.dot(x, self.weights)
if (result > 0 and y == 1) or (result < 0 and y == 0):
right += 1
return right / len(X_test)
if __name__ == '__main__':
X, y = create_data()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
lr_clf = LogisticRegressionClassifier()
lr_clf.fit(X_train, y_train)
print('the score = {}'.format(lr_clf.score(X_test, y_test)))
x_ponits = np.arange(4, 8)
y_ = -(lr_clf.weights[1] * x_ponits + lr_clf.weights[0]) / lr_clf.weights[2]
plt.plot(x_ponits, y_)
# lr_clf.show_graph()
plt.scatter(X[:50, 0], X[:50, 1], label='0')
plt.scatter(X[50:, 0], X[50:, 1], label='1')
plt.legend()
plt.show()

LogisticRegression Model(learning_rate=0.01,max_iter=200)
the score = 0.9666666666666667
sklearn中的logistic regression
sklearn.linear_model.LogisticRegression
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, max_iter=200, multi_class='warn',
n_jobs=None, penalty='l2', random_state=None, solver='liblinear',
tol=0.0001, verbose=0, warm_start=False)
solver参数决定了我们对逻辑回归损失函数的优化方法,有四种算法可以选择,分别是:
- a) liblinear:使用了开源的liblinear库实现,内部使用了坐标轴下降法来迭代优化损失函数。
- b) lbfgs:拟牛顿法的一种,利用损失函数二阶导数矩阵即海森矩阵来迭代优化损失函数。
- c) newton-cg:也是牛顿法家族的一种,利用损失函数二阶导数矩阵即海森矩阵来迭代优化损失函数。
- d) sag:即随机平均梯度下降,是梯度下降法的变种,和普通梯度下降法的区别是每次迭代仅仅用一部分的样本来计算梯度,适合于样本数据多的时候。
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(max_iter=200,solver='liblinear')
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))
print(clf.coef_, clf.intercept_)
输出
0.9666666666666667
[[ 1.96863514 -3.31358598]] [-0.36853861]
机器学习 Logistic 回归的更多相关文章
- 机器学习——Logistic回归
1.基于Logistic回归和Sigmoid函数的分类 2.基于最优化方法的最佳回归系数确定 2.1 梯度上升法 参考:机器学习--梯度下降算法 2.2 训练算法:使用梯度上升找到最佳参数 Logis ...
- 机器学习——Logistic回归
参考<机器学习实战> 利用Logistic回归进行分类的主要思想: 根据现有数据对分类边界线建立回归公式,以此进行分类. 分类借助的Sigmoid函数: Sigmoid函数图: Sigmo ...
- 机器学习——logistic回归,鸢尾花数据集预测,数据可视化
0.鸢尾花数据集 鸢尾花数据集作为入门经典数据集.Iris数据集是常用的分类实验数据集,由Fisher, 1936收集整理.Iris也称鸢尾花卉数据集,是一类多重变量分析的数据集.数据集包含150个数 ...
- 机器学习--Logistic回归
logistic回归 很多时候我们需要基于一些样本数据去预测某个事件是否发生,如预测某事件成功与失败,某人当选总统是否成功等. 这个时候我们希望得到的结果是 bool型的,即 true or fals ...
- coursera机器学习-logistic回归,正则化
#对coursera上Andrew Ng老师开的机器学习课程的笔记和心得: #注:此笔记是我自己认为本节课里比较重要.难理解或容易忘记的内容并做了些补充,并非是课堂详细笔记和要点: #标记为<补 ...
- 机器学习-- Logistic回归 Logistic Regression
转载自:http://blog.csdn.net/linuxcumt/article/details/8572746 1.假设随Tumor Size变化,预测病人的肿瘤是恶性(malignant)还是 ...
- 吴恩达-机器学习+Logistic回归分类方案
- 机器学习简易入门(四)- logistic回归
摘要:使用logistic回归来预测某个人的入学申请是否会被接受 声明:(本文的内容非原创,但经过本人翻译和总结而来,转载请注明出处) 本文内容来源:https://www.dataquest.io/ ...
- 机器学习(4)之Logistic回归
机器学习(4)之Logistic回归 1. 算法推导 与之前学过的梯度下降等不同,Logistic回归是一类分类问题,而前者是回归问题.回归问题中,尝试预测的变量y是连续的变量,而在分类问题中,y是一 ...
随机推荐
- django学习~forms
一 简介 今天咱们来聊聊 django强大的表单功能二 Froms作用 1 自动生成HTML表单元素 2 检查表单数据的合法性 3 如果验证错误,重新显示表单(数据不会重置) 4 数据 ...
- 【Udacity并行计算课程笔记】- Lesson 2 The GPU Hardware and Parallel Communication Patterns
本小节笔记大纲: 1.Communication patterns gather,scatter,stencil,transpose 2.GPU hardware & Programming ...
- Debian Linux Error “Driver 'pcspkr' is already registered, aborting...”
问题: Error: Driver ‘pcspkr’ is already registered, aborting… 解决: [root@reistlin.com ~]# echo "bl ...
- nodejs 在线学习课堂
http://ww***/class/5359f6f6ec7452081a7873d8
- Spring的Aspect切面类不能拦截Controller中的方法
根本原因在于<aop:aspectj-autoproxy />这句话是在spring的配置文件内,还是在springmvc的配置文件内.如果是在spring的配置文件内,则@Control ...
- centos 报错 “Job for iptables.service failed because the control process exited with error code.”的解决办法
原因:因为centos7默认的防火墙是firewalld防火墙,不是使用iptables,因此需要先关闭firewalld服务,或者干脆使用默认的firewalld防火墙. 操作步骤: 关闭防火墙 1 ...
- 1. let 和 const 命令
一.简单认识 1. 用let来声明变量,变量作用域就在{}(块级作用域)中 2. 用const声明变量,变量值不可更改 3. 增加了let以后,在声明变量时应该多考虑一下变量的用途,是否希望只在当前代 ...
- OracleOCP认证 之 Linux基础
Linux 基础 一.SHELL 1: Shell 简介 shell 是用户和Linux 操作系统之间的接口.Linux 中有多种shell, 其中缺省使用的是bash. Linux 系统的shell ...
- mysql批量插入数据优化
一.问题 很早以前做了一个更新功能,就是将A表中的数据全部查找出来,相对B表中改变的数据更新B表,B表中没有的数据插入B表. 最近发现该功能执行速率减慢,有时还跑超时.原来是A表中数据渐渐变多,就有了 ...
- 你需要知道的 .NET
1. 简述private.protected.public.internal 修饰符的访问权限. 答. private : 私有成员, 在类的内部才可以访问. protected : 保护成员,该类内 ...