import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets.samples_generator import make_classification def initialize_params(dims):
w = np.zeros((dims, 1))
b = 0
return w, b def sigmoid(x):
z = 1 / (1 + np.exp(-x))
return z def logistic(X, y, w, b):
num_train = X.shape[0]
y_hat = sigmoid(np.dot(X, w) + b)
loss = -1 / num_train * np.sum(y * np.log(y_hat) + (1-y) * np.log(1-y_hat))
cost = -1 / num_train * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))
dw = np.dot(X.T, (y_hat - y)) / num_train
db = np.sum(y_hat - y) / num_train
return y_hat, cost, dw, db def linear_train(X, y, learning_rate, epochs):
# 参数初始化
w, b = initialize_params(X.shape[1]) loss_list = []
for i in range(epochs):
# 计算当前的预测值、损失和梯度
y_hat, loss, dw, db = logistic(X, y, w, b)
loss_list.append(loss) # 基于梯度下降的参数更新
w += -learning_rate * dw
b += -learning_rate * db # 打印迭代次数和损失
if i % 10000 == 0:
print("epoch %d loss %f" % (i, loss)) # 保存参数
params = {
'w': w,
'b': b
} # 保存梯度
grads = {
'dw': dw,
'db': db
} return loss_list, loss, params, grads def predict(X, params):
w = params['w']
b = params['b']
y_pred = sigmoid(np.dot(X, w) + b)
return y_pred if __name__ == "__main__":
# 生成数据
X, labels = make_classification(n_samples=100,
n_features=2,
n_informative=2,
n_redundant=0,
random_state=1,
n_clusters_per_class=2)
print(X.shape)
print(labels.shape) # 生成伪随机数
rng = np.random.RandomState(2)
X += 2 * rng.uniform(size=X.shape) # 划分训练集和测试集
offset = int(X.shape[0] * 0.9)
X_train, y_train = X[:offset], labels[:offset]
X_test, y_test = X[offset:], labels[offset:]
y_train = y_train.reshape((-1, 1))
y_test = y_test.reshape((-1, 1))
print('X_train=', X_train.shape)
print('y_train=', y_train.shape)
print('X_test=', X_test.shape)
print('y_test=', y_test.shape) # 训练
loss_list, loss, params, grads = linear_train(X_train, y_train, 0.01, 100000)
print(params) # 预测
y_pred = predict(X_test, params)
print(y_pred[:10])

Python实现机器学习算法:逻辑回归的更多相关文章

  1. Python机器学习算法 — 逻辑回归(Logistic Regression)

    逻辑回归--简介 逻辑回归(Logistic Regression)就是这样的一个过程:面对一个回归或者分类问题,建立代价函数,然后通过优化方法迭代求解出最优的模型参数,然后测试验证我们这个求解的模型 ...

  2. 100天搞定机器学习|Day8 逻辑回归的数学原理

    机器学习100天|Day1数据预处理 100天搞定机器学习|Day2简单线性回归分析 100天搞定机器学习|Day3多元线性回归 100天搞定机器学习|Day4-6 逻辑回归 100天搞定机器学习|D ...

  3. 机器学习二 逻辑回归作业、逻辑回归(Logistic Regression)

    机器学习二 逻辑回归作业   作业在这,http://speech.ee.ntu.edu.tw/~tlkagk/courses/ML_2016/Lecture/hw2.pdf 是区分spam的. 57 ...

  4. 分布式机器学习:逻辑回归的并行化实现(PySpark)

    1. 梯度计算式导出 我们在博客<统计学习:逻辑回归与交叉熵损失(Pytorch实现)>中提到,设\(w\)为权值(最后一维为偏置),样本总数为\(N\),\(\{(x_i, y_i)\} ...

  5. 【机器学习】逻辑回归(Logistic Regression)

    注:最近开始学习<人工智能>选修课,老师提纲挈领的介绍了一番,听完课只了解了个大概,剩下的细节只能自己继续摸索. 从本质上讲:机器学习就是一个模型对外界的刺激(训练样本)做出反应,趋利避害 ...

  6. 机器学习 (三) 逻辑回归 Logistic Regression

    文章内容均来自斯坦福大学的Andrew Ng教授讲解的Machine Learning课程,本文是针对该课程的个人学习笔记,如有疏漏,请以原课程所讲述内容为准.感谢博主Rachel Zhang 的个人 ...

  7. 机器学习:逻辑回归(OvR 与 OvO)

    一.基础理解 问题:逻辑回归算法是用回归的方式解决分类的问题,而且只可以解决二分类问题: 方案:可以通过改造,使得逻辑回归算法可以解决多分类问题: 改造方法: OvR(One vs Rest),一对剩 ...

  8. 机器学习之逻辑回归(Logistic)笔记

    在说逻辑回归之前,可以先说一说逻辑回归与线性回归的区别: 逻辑回归与线性回归在学习规则形式上是完全一致的,它们的区别在于hθ(x(i))为什么样的函数 当hθ(x(i))=θTx(i)时,表示的是线性 ...

  9. python sklearn库实现逻辑回归的实例代码

    Sklearn简介 Scikit-learn(sklearn)是机器学习中常用的第三方模块,对常用的机器学习方法进行了封装,包括回归(Regression).降维(Dimensionality Red ...

  10. 机器学习之逻辑回归(Logistic Regression)

    1. Classification 这篇文章我们来讨论分类问题(classification problems),也就是说你想预测的变量 y 是一个离散的值.我们会使用逻辑回归算法来解决分类问题. 之 ...

随机推荐

  1. 开源词袋模型DBow3原理&源码(一)整体结构

    前人摘树,后人乘凉. 源码在github有CMakeLists,代码下下来可以直接编译. 泡泡机器人有个很详细的分析,结合浅谈回环检测中的词袋模型,配合高翔的回环检测应用,基本上就可以串起来了. tf ...

  2. WIN7系统怎样增加C盘空间

    具体操作参考:https://jingyan.baidu.com/article/215817f78e05c01eda142385.html

  3. javamail发送邮件及错误解决方法javax.mail.AuthenticationFailedException: failed to connect, no password specified?

    javamail发送邮件及错误解决方法javax.mail.AuthenticationFailedException: failed to connect, no password specifie ...

  4. Python+OpenCV图像处理(三)—— Numpy数组操作图片

    一.改变图片每个像素点每个通道的灰度值 (一) 代码如下: #遍历访问图片每个像素点,并修改相应的RGB import cv2 as cv def access_pixels(image): prin ...

  5. 使用Wisdom RESTClient自动化测试REST API,如何取消对返回的body内容的校验?

    使用Wisdom RESTClient V1.1 自动化测试API,默认是对返回HTTP状态码和body内容进行校验的. 如果您的API返回body内容是变化的,可以通过设置来取消对body内容的校验 ...

  6. Censor SCU - 4438

    frog is now a editor to censor so-called sensitive words (敏感词). She has a long text (p). Her job is ...

  7. amoeba_mysql 读写分离

    环境 amoeba需要java环境,配置:略. MySQL主从配置:略. 基本架构 MySQL主:192.168.31.140 MySQL从:192.168.31.150 MySQL代理:192.16 ...

  8. git clone 报错Unable to negotiate with xxx.xxx.xxx.xxx port 12345: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1

    在执行git clone命令报错 Unable to negotiate with xxx.xxx.xxx.xxx port 12345: no matching key exchange metho ...

  9. encodeURI、encodeURIComponent

    encodeURI是对整个uri进行编码的,而encodeURIComponent是对uri中部分内容进行编码. 在进行url的字符串拼接时,需要进行两次encodeURI. 只进行一次encodeU ...

  10. gcc对c++标准的支持

    GCC 4.8.1完全支持c++11核心部分,对应的glibc为2.17 gcc 4.9支持c++11正则表达式,卧槽...4.8.5会报terminate called after throwing ...