达叔机器学习笔记1_逻辑回归建立一般流程
碎碎念:达叔说 逻辑回归相当于小型的神经网络 就是没有隐含层嘛
先简单介绍一下需要做的事情 共分为7步,接下来将达叔作业里的所有程序 粘贴出来
1.,导入数据集,查看数据格式
操作:train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
train_set_x_orig.shape
一般会得到四个值(n,num_px,num_px,3) n 是训练集的个数,如 100张猫咪的训练照片, num_px 是图片的长宽?比如 64,64 代表一张64×64的图片 3 代表 RGB三个值
2.reshape
操作:train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
X_flatten=X.shape(X.shape[0],-1).T 此操作可以将(a,b,c,d)的矩阵转化为(b*c*d,a)的二维矩阵
将(n,num_px,num_px,3)维度的数据reshape成(num_px×num_px×3,n)样子的数据,如(12288,n)12288行,n列。每一列是一张图片,每张图片有12288个特征。n代表 共有n张图片。这样所有训练集的维度就是一样的了
同时不要忘记对测试集也进行相同的操作
3.预处理(归一化)
操作:train_set_x = train_set_x_flatten/255.
一般来说 预处理包含center 去中心化和standardize标准化两步,但是因为这里每个12288个值,其实每一值代表图片上64×64个点中的RGB中的一个值,所以每个值得范围是(0,255)。所以每个值除以255就ok了
4.初始化参数
操作:w = np.zeros((dim, 1))
b = 0
一般来说有多少个输入特征,行数 这里是12288 一般就有多少个w
5.代价函数最小化(利用梯度下降法)
参考公式
操作: m = X.shape[1]
A = sigmoid(np.dot(w.T, X) + b) # compute activation 因为w是一个与X的行数一样,一列的向量 ,所以求点积时,需要转置再求
cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A)) # compute cost
dw = 1 / m * np.dot(X, (A - Y).T)
db = 1 / m * np.sum(A - Y)
w = w - learning_rate * dw
b = b - learning_rate * db
6.更换学习率 α 画图观察不同学习率下的 cost变化情况 得到算法的正确率
操作:learning_rates = [0.01, 0.001, 0.0001]
plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"])
7.得出结论
一步一步定义函数,然后定义模型,在模型中调用函数,画图观察cost 确定合适的学习率α
程序部分
#逻辑回归的整个过程
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
#1 导入数据
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
#1 检查数据的shape
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
#2.reshape 统一shape
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
#3 预处理 数据标准化
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.
#4分别定义了 sigmoid函数 sigmoid导数 初始化参数 正向传播 梯度下降法等函数
def sigmoid(z):
s = 1 / (1 + np.exp(-z))
return s
def sigmoid_derivative(x):
s = sigmoid(x)
ds = s * (1 - s)
return ds
def initialize_with_zeros(dim):
w = np.zeros((dim, 1))
b = 0
return w, b
def propagate(w, b, X, Y):
m = X.shape[1]
A = sigmoid(np.dot(w.T, X) + b) # compute activation
cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))
dw = 1 / m * np.dot(X, (A - Y).T)
db = 1 / m * np.sum(A - Y)
cost = np.squeeze(cost)
grads = {"dw": dw,
"db": db}
return grads, cost
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
#通过梯度下降法实现w,b的更新
costs = []
for i in range(num_iterations):
# Cost and gradient calculation (≈ 1-4 lines of code)
grads, cost = propagate(w, b, X, Y)
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
w = w - learning_rate * dw
b = b - learning_rate * db
if i % 100 == 0:
costs.append(cost)
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, costs
# 定义了 查看算法正确率的函数
def predict(w, b, X):
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)
for i in range(A.shape[1]):
# Convert probabilities A[0,i] to actual predictions p[0,i]
if A[0, i] <= 0.5:
Y_prediction[0, i] = 0
else:
Y_prediction[0, i] = 1
return Y_prediction
#5 将以上所有函数结合在一起形成一个model 来实现逻辑回归
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
#print_cost -- Set to true to print the cost every 100 iterations
D={}
w, b = initialize_with_zeros(X_train.shape[0])
parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
w = parameters["w"]
b = parameters["b"]
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)
print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test))))
D={"costs": costs,
"Y_prediction_test": Y_prediction_test,
"Y_prediction_train": Y_prediction_train,
"w" : w,
"b" : b,
"learning_rate" : learning_rate,
"num_iterations": num_iterations}
return D
#5 调用model函数 求解 一些列值
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)
#6.可视化 把学习率为0.05 情况下的cost 图画出来
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show()
#更换不同学习率 查看不同学习率下的cost变化
learning_rates = [0.01, 0.001, 0.0001]
models = {}
for i in learning_rates:
print ("learning rate is: " + str(i))
models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)
print ('\n' + "-------------------------------------------------------" + '\n')
for i in learning_rates:
plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"]))
plt.ylabel('cost')
plt.xlabel('iterations')
legend = plt.legend(loc='upper center', shadow=True)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()
达叔机器学习笔记1_逻辑回归建立一般流程相关推荐
- 机器学习笔记-基于逻辑回归的分类预测
天池学习笔记:AI训练营机器学习-阿里云天池 基于逻辑回归的分类预测 1 逻辑回归的介绍和应用 1.1 逻辑回归的介绍 逻辑回归(Logistic regression,简称LR)虽然其中带有&quo ...
- 机器学习笔记(5)——逻辑回归
上一篇:机器学习笔记(4)--多变量线性回归 逻辑回归实际是一种有监督学习中的分类算法,称为回归是历史原因 前言 前面我们已经学习了线性回归,线性回归适用于预测一个连续值,就是说预测值可能的范围存在连 ...
- python逻辑回归训练预测_[Python] 机器学习笔记 基于逻辑回归的分类预测
导学问题 什么是逻辑回归(一),逻辑回归的推导(二 3),损失函数的推导(二 4) 逻辑回归与SVM的异同 逻辑回归和SVM都用来做分类,都是基于回归的概念 SVM的处理方法是只考虑 support ...
- 吴恩达《机器学习》学习笔记七——逻辑回归(二分类)代码
吴恩达<机器学习>学习笔记七--逻辑回归(二分类)代码 一.无正则项的逻辑回归 1.问题描述 2.导入模块 3.准备数据 4.假设函数 5.代价函数 6.梯度下降 7.拟合参数 8.用训练 ...
- 吴恩达《机器学习》学习笔记八——逻辑回归(多分类)代码
吴恩达<机器学习>笔记八--逻辑回归(多分类)代码 导入模块及加载数据 sigmoid函数与假设函数 代价函数 梯度下降 一对多分类 预测验证 课程链接:https://www.bilib ...
- 吴恩达《机器学习》学习笔记五——逻辑回归
吴恩达<机器学习>学习笔记五--逻辑回归 一. 分类(classification) 1.定义 2.阈值 二. 逻辑(logistic)回归假设函数 1.假设的表达式 2.假设表达式的意义 ...
- 吴恩达机器学习课后习题——逻辑回归
机器学习课后作业-逻辑回归 逻辑回归 逻辑回归算法,是一种给分类算法,这个算法的实质是:它输出值永远在0到 1 之间. 将要构建一个逻辑回归模型来预测,某个学生是否被大学录取.设想你是大学相关部分的管 ...
- 机器学习算法 03 —— 逻辑回归算法(精确率和召回率、ROC曲线和AUC指标、过采样和欠采样)
文章目录 系列文章 逻辑回归 1 逻辑回归介绍 1.1 逻辑回归原理 输入 激活函数 1.2 损失以及优化 2 逻辑回归API介绍 3 案例:肿瘤良性恶性预测 4 分类模型的评估 4.1 分类评估方法 ...
- 机器学习:基于逻辑回归对航空公司乘客满意度的因素分析
机器学习:基于逻辑回归对航空公司乘客满意度的因素分析 作者:i阿极 作者简介:数据分析领域优质创作者.多项比赛获奖者:博主个人首页
- 斯坦福大学吴恩达机器学习教程中文笔记——week3——逻辑回归,正则化
第3周 文章目录 第3周 @[toc] 六.逻辑回归(Logistic Regression) 6.1 分类问题 6.2 假说表示 6.3 判定边界 6.4 代价函数 6.5 简化的成本函数和梯度下降 ...
最新文章
- 堆栈的应用——用JavaScript描述数据结构
- 异步提交表单插件jquery.form.min.js的使用实例
- CodeForces - 1486E Paired Payment(分层图最短路)
- 微型计算机开机密码丢失,校诡实录微机教室攻略 电脑密码是多少[多图]
- 分区式存储管理c++_分区机要变形缝,纵横交接卫浴厨:防火阀参数的高效记忆口诀...
- 当自己颓废的时候怎么激励自己?深度好文!!!
- [Nginx] 事件模型
- 查看redis安装目录
- 第03讲- 第一个Android项目
- 米家扩展程序初始化超时_Home · MiEcosystem/miot-plugin-sdk Wiki · GitHub
- cdr三角形转化为圆角_cdr怎么把直角变成圆角
- 单目3D目标检测之入门
- CSAPP实验记录(二)Bomb Lab
- 2017年度全球一级市场“投资龙虎榜”发布 | 钛媒体Pro独家
- 计算机综合布线考试试题A,综合布线试题A
- 秀才还是野兽(规划还是探索)
- 今日分享-ios蓝牙
- 快速导向滤波 matlab,导向滤波小结:从导向滤波(guided filter)到快速导向滤波(fast guide filter)的原理,应用及opencv实现代码...
- 理解下DSO/ADSO
- 常见的均值不等式的使用技巧