logistics回归是一种二分类问题,采用的激活函数是sigmoid函数,使得输出值转换为(0,1)之间的概率

A = sigmoid(np.dot(w.T, X) + b ) 表示预测函数

dz = A - Y , A 表示的是预测结果, y 表示的是实际结果

cost = -y*logA - (1-y)*log(1-A)  #表示损失函数

dw = np.dot(X, dz.T)/m

db = np.sum(dz)/m

w := w - a*dw   # 更新w,a 表示学习率

b : = b - a*db     #更新b

第一步: 定义lr_utils.py 导入数据

import numpy as np
import h5py def load_dataset():
train_dataset = h5py.File('datasets/train_catvnoncat.h5', 'r')
train_set_x_orig = np.array(train_dataset['train_set_x'][:])
train_set_y = np.array(train_dataset['train_set_y'][:]) test_dataset = h5py.File('datasets/test_catvnoncat.h5', 'r')
test_set_x_orig = np.array(test_dataset['test_set_x'][:])
test_set_y = np.array(test_dataset['test_set_y'][:]) # 对矩阵预测值的维度构造成(1, train_set_x_orig.shape[0]) 即一张照片一个预测值
train_set_y = train_set_y.reshape((1, train_set_x_orig.shape[0]))
test_set_y = test_set_y.reshape((1, test_set_x_orig.shape[0])) classes = np.array(test_dataset["list_classes"][:]) return train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes

第二步:调用函数,进行数据导入

import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset() # 查看图片
index = 7
plt.imshow(train_set_x_orig[7])
plt.show() #训练集的图片个数
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
# 图片的尺寸
num_px = train_set_x_orig.shape[1] # 对每张图片的像素点进行一个竖直排列[x1, x2, x3, x4]
train_set_x_flatten = train_set_x_orig.reshape(m_train, -1).T
test_set_x_flatten = test_set_x_orig.reshape(m_test, -1).T # 进行像素点归一化
train_set_x = train_set_x_flatten / 255
test_set_x = test_set_x_flatten / 255

第三步:定义sigmoid函数和进行参数初始化

def sigmoid(z):
return 1/(1+np.exp(-z)) s = sigmoid(np.array([[0, 2]])) def initialize_with_zeros(dim): w = np.zeros((dim, 1), dtype=float)
b = 0.0 return w, b

第四步:定义反向传播函数

def propgate(w, b, X, Y):
m = X.shape[1]
# 预测函数
A = sigmoid(np.dot(w.T, X) + b)
# 预测函数与真实值之差
dz = A - Y
# A与w的导数
dw = 1/m * np.dot(X, dz.T)
# b与w的导数
db = 1/m * np.sum(dz, axis=1)
#损失函数
cost = np.sum(-Y * np.log(A) - (1 - Y) * np.log(1 - A), axis=1) / m
#更新参数的幅度
grade = {'dw':dw, 'db':db}
#损失函数
cost = np.squeeze(cost) return cost, grade

第5步:通过反向传播函数, 训练样本

# 迭代优化

def optimize(w, b, X, Y, num_iteration, learning_rate, print_cost):

# w, b 为初始参数, X, Y为训练集的变量和标签, num_iteration为训练次数, learning_rate为学习率, print_cost为是否打印
now_num_iteration = 0
costs = []
for i in range(num_iteration): cost, grade = propgate(w, b, X, Y) dw = grade['dw']
db = grade['db'] w = w - learning_rate*dw
b = b - learning_rate*db
now_num_iteration += 1 if i%100 == 0:
costs.append(cost) if print_cost and i%100:
print(cost, i) param = {'w':w,
'b':b}
grade = {'dw':dw,
'db':db}

第6步:定义预测函数,使用的是前向传播函数

def predict(w, b, X):
# w,b表示参数,X表示的是输入的图片,y轴表示图片的数目
# m表示预测的图片的数目
m = X.shape[1]
Y_prediction = np.zeros((1, m))
w = w.reshape(X.shape[0], 1)
A = sigmoid(np.dot(w.T, X) + b)
# 概率大于0.5,预测结果为1
for i in range(A.shape[1]):
if A[0, i] > 0.5:
Y_prediction[0, i] = 1 return Y_prediction

第7步:定义最终的训练模型, 输出训练的准确度

def model(train_set_x, train_set_y, test_set_x, test_set_y, num_iteration, learning_rate, print_cost):

    m = train_set_x.shape[0]
# 创建初始值
w, b = initialize_with_zeros(m)
costs, param, grade = optimize(w, b,train_set_x, train_set_y,
num_iteration, learning_rate, print_cost)
w = param['w']
b = param['b'] Y_train_prediciton = predict(w, b, train_set_x)
Y_test_prediction = predict(w, b, test_set_x)
# 输出训练的准确度
print('train_accuracy {}'.format(100 - np.mean(np.abs(Y_train_prediciton - train_set_y))*100))
print('test_accuracy {}'.format(100 - np.mean(np.abs(Y_test_prediction - test_set_y ))*100)) d = {'costs':costs,
'Y_train_prediciton':Y_train_prediciton,
'Y_test_prediction':Y_test_prediction,
'w':w,
'b':b,
'learning_rate':learning_rate,
'num_iteration': num_iteration} return d

第8步:我们挑选一张猫的图片进行预测

# 预测图片
my_image = "cat_1.jpg" # change this to the name of your image file
## END CODE HERE ## # We preprocess the image to fit your algorithm.
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
# 重构模型大小, 使得模型的shape为(:,1)
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T
# 输出预测的结果
my_predicted_image = predict(d['w'], d['b'], my_image)
plt.imshow(image)
print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")

跟我学算法-吴恩达老师的logsitic回归的更多相关文章

  1. 跟我学算法-吴恩达老师(超参数调试, batch归一化, softmax使用,tensorflow框架举例)

    1. 在我们学习中,调试超参数是非常重要的. 超参数的调试可以是a学习率,(β1和β2,ε)在Adam梯度下降中使用, layers层数, hidden units 隐藏层的数目, learning_ ...

  2. 跟我学算法-吴恩达老师(mini-batchsize,指数加权平均,Momentum 梯度下降法,RMS prop, Adam 优化算法, Learning rate decay)

    1.mini-batch size 表示每次都只筛选一部分作为训练的样本,进行训练,遍历一次样本的次数为(样本数/单次样本数目) 当mini-batch size 的数量通常介于1,m 之间    当 ...

  3. 机器学习爱好者 -- 翻译吴恩达老师的机器学习课程字幕 http://www.ai-start.com/

    机器学习爱好者 -- 翻译吴恩达老师的机器学习课程字幕 GNU Octave    开源  MatLab http://www.ai-start.com/ https://zhuanlan.zhihu ...

  4. 吴恩达讲了干货满满的一节全新AI课,全程手写板书充满诚意非常干货

    吴恩达讲了干货满满的一节全新AI课,全程手写板书充满诚意非常干货 摘要: 目前,AI技术做出的经济贡献几乎都来自监督学习,也就是学习从A到B,从输入到输出的映射.现在,监督学习.迁移学习.非监督学习. ...

  5. 吴恩达最新TensorFlow专项课程开放注册,你离TF Boy只差这一步

    不需要 ML/DL 基础,不需要深奥数学背景,初学者和软件开发者也能快速掌握 TensorFlow.掌握人工智能应用的开发秘诀. 以前,吴恩达的机器学习课程和深度学习课程会介绍很多概念与知识,虽然也会 ...

  6. 吴恩达(Andrew Ng)——机器学习笔记1

    之前经学长推荐,开始在B站上看Andrew Ng的机器学习课程.其实已经看了1/3了吧,今天把学习笔记补上吧. 吴恩达老师的Machine learning课程共有113节(B站上的版本https:/ ...

  7. 吴恩达深度学习第1课第4周-任意层人工神经网络(Artificial Neural Network,即ANN)(向量化)手写推导过程(我觉得已经很详细了)

    学习了吴恩达老师深度学习工程师第一门课,受益匪浅,尤其是吴老师所用的符号系统,准确且易区分. 遵循吴老师的符号系统,我对任意层神经网络模型进行了详细的推导,形成笔记. 有人说推导任意层MLP很容易,我 ...

  8. 吴恩达深度学习 反向传播(Back Propagation)公式推导技巧

    由于之前看的深度学习的知识都比较零散,补一下吴老师的课程希望能对这块有一个比较完整的认识.课程分为5个部分(粗体部分为已经看过的): 神经网络和深度学习 改善深层神经网络:超参数调试.正则化以及优化 ...

  9. Coursera课程《Machine Learning》吴恩达课堂笔记

    强烈安利吴恩达老师的<Machine Learning>课程,讲得非常好懂,基本上算是无基础就可以学习的课程. 课程地址 强烈建议在线学习,而不是把视频下载下来看.视频中间可能会有一些问题 ...

随机推荐

  1. PHP:第五章——字符串的概念

    <?php header("Content-Type:text/html;charset=utf-8"); //字符串概念: //1.单引号.//里面的变量不会被解释 //例 ...

  2. 软件工程firstblood

    https://github.com/happyeven/WC 项目要求 wc.exe 是一个常见的工具,它能统计文本文件的字符数.单词数和行数.这个项目要求写一个命令行程序,模仿已有wc.exe 的 ...

  3. Xilinx SDK使用教程

    本文参考 Xilinx SDK软件内置的教程,打开方法:打开SDK->Help->Cheet Sheets...->Xilinx SDK Tutorials,这里有6篇文档.本文详细 ...

  4. 集成学习之Boosting —— Gradient Boosting原理

    集成学习之Boosting -- AdaBoost原理 集成学习之Boosting -- AdaBoost实现 集成学习之Boosting -- Gradient Boosting原理 集成学习之Bo ...

  5. Python 傅里叶分析

    0. 一维序列卷积 np.convolve,注意 same/valid参数下(默认为 full),序列卷积出的结果的长度: >> np.convolve([1, 2, 3], [0, 1, ...

  6. 20155313 2016-2017-2 《Java程序设计》第八周学习总结

    20155313 2016-2017-2 <Java程序设计>第八周学习总结 教材内容学习 十四章 NIO与NIO2 1.认识NIO NIO使用频道(Channel)来衔接数据节点,在处理 ...

  7. python requests 设置headers 和 post请求体x-www-form-urlencoded

    1.application/json:是JSON格式提交的一种识别方式.在请求头里标示.2.application/x-www-form-urlencoded : 这是form表单提交的时候的表示方式 ...

  8. 重新学习之spring第二个程序,配置AOP面向切面编程

    第一步:在配置好的ioc容器的基础上,导入面向切面编程所需要的jar包 (本案例用的是spring3.2.4,由于spring3.2.4的官网jar包中不再有依赖包,所以依赖包都是从网上找的) 第二步 ...

  9. SQL优化之索引分析

    索引的重要性 数据库性能优化中索引绝对是一个重量级的因素,可以说,索引使用不当,其它优化措施将毫无意义. 聚簇索引(Clustered Index)和非聚簇索引 (Non- Clustered Ind ...

  10. GNU Radio: Synchronization and MIMO Capability with USRP Devices

    Application Note Synchronization and MIMO Capability with USRP Devices Ettus Research Introduction S ...