跟我学算法-吴恩达老师的logsitic回归
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回归的更多相关文章
- 跟我学算法-吴恩达老师(超参数调试, batch归一化, softmax使用,tensorflow框架举例)
1. 在我们学习中,调试超参数是非常重要的. 超参数的调试可以是a学习率,(β1和β2,ε)在Adam梯度下降中使用, layers层数, hidden units 隐藏层的数目, learning_ ...
- 跟我学算法-吴恩达老师(mini-batchsize,指数加权平均,Momentum 梯度下降法,RMS prop, Adam 优化算法, Learning rate decay)
1.mini-batch size 表示每次都只筛选一部分作为训练的样本,进行训练,遍历一次样本的次数为(样本数/单次样本数目) 当mini-batch size 的数量通常介于1,m 之间 当 ...
- 机器学习爱好者 -- 翻译吴恩达老师的机器学习课程字幕 http://www.ai-start.com/
机器学习爱好者 -- 翻译吴恩达老师的机器学习课程字幕 GNU Octave 开源 MatLab http://www.ai-start.com/ https://zhuanlan.zhihu ...
- 吴恩达讲了干货满满的一节全新AI课,全程手写板书充满诚意非常干货
吴恩达讲了干货满满的一节全新AI课,全程手写板书充满诚意非常干货 摘要: 目前,AI技术做出的经济贡献几乎都来自监督学习,也就是学习从A到B,从输入到输出的映射.现在,监督学习.迁移学习.非监督学习. ...
- 吴恩达最新TensorFlow专项课程开放注册,你离TF Boy只差这一步
不需要 ML/DL 基础,不需要深奥数学背景,初学者和软件开发者也能快速掌握 TensorFlow.掌握人工智能应用的开发秘诀. 以前,吴恩达的机器学习课程和深度学习课程会介绍很多概念与知识,虽然也会 ...
- 吴恩达(Andrew Ng)——机器学习笔记1
之前经学长推荐,开始在B站上看Andrew Ng的机器学习课程.其实已经看了1/3了吧,今天把学习笔记补上吧. 吴恩达老师的Machine learning课程共有113节(B站上的版本https:/ ...
- 吴恩达深度学习第1课第4周-任意层人工神经网络(Artificial Neural Network,即ANN)(向量化)手写推导过程(我觉得已经很详细了)
学习了吴恩达老师深度学习工程师第一门课,受益匪浅,尤其是吴老师所用的符号系统,准确且易区分. 遵循吴老师的符号系统,我对任意层神经网络模型进行了详细的推导,形成笔记. 有人说推导任意层MLP很容易,我 ...
- 吴恩达深度学习 反向传播(Back Propagation)公式推导技巧
由于之前看的深度学习的知识都比较零散,补一下吴老师的课程希望能对这块有一个比较完整的认识.课程分为5个部分(粗体部分为已经看过的): 神经网络和深度学习 改善深层神经网络:超参数调试.正则化以及优化 ...
- Coursera课程《Machine Learning》吴恩达课堂笔记
强烈安利吴恩达老师的<Machine Learning>课程,讲得非常好懂,基本上算是无基础就可以学习的课程. 课程地址 强烈建议在线学习,而不是把视频下载下来看.视频中间可能会有一些问题 ...
随机推荐
- UVALive-3645 Objective: Berlin (最大流:时序模型)
题目大意:有n个城市,m条航班.已知每条航班的起点和终点,还有每条航班的载客量.出发时间.到达时间.并且要求在任何一个城市(起点.终点除外)都至少要有30分钟的中转时间,求起点到终点的最大客流量. 题 ...
- MyBatise代码自动生成时候Oralce的number类型BigDecimal问题
使用MyBatise的代码自动生成工具时候,即便在配置文件中定义了 <javaTypeResolver> <property name="forceBigDecimals& ...
- https wireshark抓包——要解密出原始数据光有ssl 证书还不行,还要有浏览器内的pre-master-secret(内存里)
基于wireshark抓包的分析 首先使用wireshark并且打开浏览器,打开百度(百度使用的是HTTPS加密),随意输入关键词浏览. 我这里将抓到的包进行过滤.过滤规则如下 ip.addr == ...
- 设置mysql的字符集
ALTER DATABASE test DEFAULT CHARACTER SET utf8; show variables like 'char%';
- CF 148D Bag of mice 概率dp 难度:0
D. Bag of mice time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...
- Webroot SecureAnywhere AntiVirus 2014 – 免费6个月
Webroot SecureAnywhere 是由webroot推出的一款云安全软件,除了能够清除病毒外,特点是体积小.强力查杀木马.间谍软件.Rootkit 等等,为你的个人私隐信息提供全面的保护. ...
- 第12课:HTML+CSS的基础用法
1. html之head部分的常用标签的使用 <!--指定html是标准的html还是其它的html--> <!DOCTYPE html> <html lang=&quo ...
- how to play
陷入难以言说的深深的绝望 无力,无助,暗无天日,看不到光明,看不到未来,不知道何去何从 但我依然坚信这道坎一定可以过去,黎明前的夜总是黑暗的,属于我的光明终将来临 沼泽中的旅行者,只要还没死掉,就还没 ...
- Linux的发行版之间的联系和区别
转载:https://blog.csdn.net/suixin788/article/details/52555558 联系 Linux的内核源代码和Linux的应用程序都可以自由获得,因此很多公司组 ...
- oracle之 Got minus one from a read call 与 ORA-27154: post/wait create failed
在部署应用的时候,有时候应用可以直接启动,但偶尔应用却无法启动,报错信息是: java.sql.SQLRecoverableException: IO Error: Got minus one fro ...