FTRL实战之LR+FTRL(代码采用的稠密数据)

article/2025/9/27 9:56:15

理解要点:主要是梯度更新的方法使用了FTRL。即更改了梯度的update函数。       

相关参考:https://github.com/wan501278191/OnlineLearning_BasicAlgorithm/blob/master/FTRL.py

FTRL(Follow The Regularized Leader)是一种优化方法,就如同SGD(Stochastic Gradient Descent)一样。这里直接给出用FTRL优化LR(Logistic Regression)的步骤:

       其中pt=σ(Xt⋅w)是LR的预测函数,求出pt的唯一目的是为了求出目标函数(在LR中采用交叉熵损失函数作为目标函数)对参数w的一阶导数g,gi=(pt−yt)xi。上面的步骤同样适用于FTRL优化其他目标函数,唯一的不同就是求次梯度g(次梯度是左导和右导之间的集合,函数可导--左导等于右导时,次梯度就等于一阶梯度)的方法不同。

一、先查看一下数据

二、构建FTRL模型

# %load FTRL.py
# Date: 2018-08-17 9:47
# Author: Enneng Yang
# Abstract:ftrl ref:http://www.cnblogs.com/zhangchaoyang/articles/6854175.htmlimport sys
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
import numpy as np
import tensorflow as tf# logistic regression
class LR(object):@staticmethoddef fn(w, x):''' sigmod function '''return 1.0 / (1.0 + np.exp(-w.dot(x)))@staticmethoddef loss(y, y_hat):'''cross-entropy loss function'''return np.sum(np.nan_to_num(-y * np.log(y_hat) - (1-y)*np.log(1-y_hat)))@staticmethoddef grad(y, y_hat, x):'''gradient function'''return (y_hat - y) * xclass FTRL(object):def __init__(self, dim, l1, l2, alpha, beta, decisionFunc=LR):self.dim = dimself.l1 = l1self.l2 = l2self.alpha = alphaself.beta = betaself.decisionFunc = decisionFuncself.z = np.zeros(dim)self.q = np.zeros(dim)self.w = np.zeros(dim)def predict(self, x):return self.decisionFunc.fn(self.w, x)def update(self, x, y):self.w = np.array([0 if np.abs(self.z[i]) <= self.l1else (np.sign(self.z[i]) * self.l1 - self.z[i]) / (self.l2 + (self.beta + np.sqrt(self.q[i]))/self.alpha)for i in range(self.dim)])y_hat = self.predict(x)g = self.decisionFunc.grad(y, y_hat, x)sigma = (np.sqrt(self.q + g*g) - np.sqrt(self.q)) / self.alphaself.z += g - sigma * self.wself.q += g*greturn self.decisionFunc.loss(y,y_hat)def training(self, trainSet, max_itr):n = 0all_loss = []all_step = []while True:for var in trainSet:x= var[:4]y= var[4:5]loss = self.update(x, y)all_loss.append(loss)all_step.append(n)print("itr=" + str(n) + "\tloss=" + str(loss))n += 1if n > max_itr:print("reach max iteration", max_itr)return all_loss, all_step

 三、训练

if __name__ ==  '__main__':d = 4trainSet = np.loadtxt('Data/FTRLtrain.txt')ftrl = FTRL(dim=d, l1=0.001, l2=0.1, alpha=0.1, beta=1e-8)all_loss, all_step = ftrl.training(trainSet,  max_itr=100000)w = ftrl.wprint(w)testSet = np.loadtxt('Data/FTRLtest.txt')correct = 0wrong = 0for var in testSet:x = var[:4]y = var[4:5]y_hat = 1.0 if ftrl.predict(x) > 0.5 else 0.0if y == y_hat:correct += 1else:wrong += 1print("correct ratio:", 1.0 * correct / (correct + wrong), "\t correct:", correct, "\t wrong:", wrong)plt.title('FTRL')plt.xlabel('training_epochs')plt.ylabel('loss')plt.plot(all_step, all_loss)plt.show()
打印如下:
itr=99996	loss=6.573507715996819e-05
itr=99997	loss=0.004460476965465843
itr=99998	loss=0.27559826174822016
itr=99999	loss=0.49269693073256776
itr=100000	loss=0.00031078609741847434
reach max iteration 100000
[ 4.40236724  1.98715805 11.66128074  3.37851271]
correct ratio: 0.994 	 correct: 994 	 wrong: 6

其他参考:

# coding=utf-8
__author__ = "orisun"import numpy as npclass LR(object):@staticmethoddef fn(w, x):'''决策函数为sigmoid函数'''return 1.0 / (1.0 + np.exp(-w.dot(x)))@staticmethoddef loss(y, y_hat):'''交叉熵损失函数'''return np.sum(np.nan_to_num(-y * np.log(y_hat) - (1 - y) * np.log(1 - y_hat)))@staticmethoddef grad(y, y_hat, x):'''交叉熵损失函数对权重w的一阶导数'''return (y_hat - y) * xclass FTRL(object):def __init__(self, dim, l1, l2, alpha, beta, decisionFunc=LR):self.dim = dimself.decisionFunc = decisionFuncself.z = np.zeros(dim)self.n = np.zeros(dim)self.w = np.zeros(dim)self.l1 = l1self.l2 = l2self.alpha = alphaself.beta = betadef predict(self, x):return self.decisionFunc.fn(self.w, x)def update(self, x, y):self.w = np.array([0 if np.abs(self.z[i]) <= self.l1 else (np.sign(self.z[i]) * self.l1 - self.z[i]) / (self.l2 + (self.beta + np.sqrt(self.n[i])) / self.alpha) for i in range(self.dim)])y_hat = self.predict(x)g = self.decisionFunc.grad(y, y_hat, x)sigma = (np.sqrt(self.n + g * g) - np.sqrt(self.n)) / self.alphaself.z += g - sigma * self.wself.n += g * greturn self.decisionFunc.loss(y, y_hat)def train(self, trainSet, verbos=False, max_itr=100000000, eta=0.01, epochs=100):itr = 0n = 0while True:for x, y in trainSet:loss = self.update(x, y)if verbos:print ("itr=" + str(n) + "\tloss=" + str(loss))if loss < eta:itr += 1else:itr = 0if itr >= epochs:  # 损失函数已连续epochs次迭代小于etaprint ("loss have less than", eta, " continuously for ", itr, "iterations")returnn += 1if n >= max_itr:print ("reach max iteration", max_itr)returnclass Corpus(object):def __init__(self, file, d):self.d = dself.file = filedef __iter__(self):with open(self.file, 'r') as f_in:for line in f_in:arr = line.strip().split()if len(arr) >= (self.d + 1):yield (np.array([float(x) for x in arr[0:self.d]]), float(arr[self.d]))if __name__ == '__main__':d = 4#corpus = Corpus("train.txt", d)corpus = Corpus("./Data/FTRLtrain.txt", d)ftrl = FTRL(dim=d, l1=1.0, l2=1.0, alpha=0.1, beta=1.0)ftrl.train(corpus, verbos=False, max_itr=100000, eta=0.01, epochs=100)w = ftrl.wprint (w)correct = 0wrong = 0for x, y in corpus:y_hat = 1.0 if ftrl.predict(x) > 0.5 else 0.0if y == y_hat:correct += 1else:wrong += 1print ("correct ratio", 1.0 * correct / (correct + wrong))

 打印如下:

reach max iteration 100000
[ 4.0726218   1.8432749  10.83822051  3.11898096]
correct ratio 0.9944444444444445

当把参数调为λ1=0,λ2=0,α=0.5,β=1λ1=0,λ2=0,α=0.5,β=1时,准确率能达到0.9976。

train.txt文件前4列是特征,第5列是标签。内容形如:

复制代码

-0.567811945258 0.899305436215 0.501926599477 -0.222973905568 1.0
-0.993964260114 0.261988294216 -0.349167046026 -0.923759536056 0.0
0.300707261785 -0.90855090557 -0.248270600228 0.879134142054 0.0
-0.311566995194 -0.698903141283 0.369841040784 0.175901270771 1.0
0.0245841670644 0.782128080056 0.542680482068 0.44897929707 1.0
0.344387543846 0.297686731698 0.338210312887 0.175049733038 1.0

相关参考:

FTRL代码实 https://www.cnblogs.com/zhangchaoyang/articles/6854175.html

在线学习算法:https://blog.csdn.net/kyq156518/article/details/83860804?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task


http://chatgpt.dhexx.cn/article/i6C1J4vv.shtml

相关文章

DL基本知识(七)FTRL优化器

契机 最近工作方向为缩减模型规模&#xff0c;切入点为L1正则化&#xff0c;选择该切入点的理由如下&#xff0c; 众所周知&#xff0c;L1正则化能令权重矩阵更稀疏。在推荐系统中特征多为embedding&#xff0c;权重矩阵稀疏意味着一些embedding_weight为0&#xff0c;模型部…

FTRL算法详解

一、算法原理 二、算法逻辑 三、个人理解 从loss function的形式来看&#xff1a;FTRL就是将RDA-L1的“梯度累加”思想应用在FOBOS-L1上&#xff0c;并施加一个L2正则项。【PS&#xff1a;paper上是没有加L2正则项的】这样达到的效果是&#xff1a; 累积加和限定了新的迭代结果…

FTRL算法理解

本文主要是对FTRL算法来源、原理、应用的总结和自己的思考。 解决的问题 1、训练数据层面&#xff1a;数据量大、特征规模大 2、常用的LR和FM这类模型的参数学习&#xff0c;传统的学习算法是batch learning算法&#xff0c;无法有效地处理大规模的数据集&#xff0c;也无法…

ftrl 流式更新 java_深入理解FTRL

FTRL算法是吸取了FOBOS算法和RDA算法的两者优点形成的Online Learning算法。读懂这篇文章&#xff0c;你需要理解LR、SGD、L1正则。 FOBOS算法 前向后向切分(FOBOS&#xff0c;Forward Backward Splitting)是 John Duchi 和 Yoran Singer 提出的。在该算法中&#xff0c;权重的…

排序模型-FTRL

排序模型进阶-FTRL 1 问题 在实际项目的时候&#xff0c;经常会遇到训练数据非常大导致一些算法实际上不能操作的问题。比如在推荐行业中&#xff0c;因为DSP的请求数据量特别大&#xff0c;一个星期的数据往往有上百G&#xff0c;这种级别的数据在训练的时候&#xff0c;直接…

FTRL代码实现

FTRL&#xff08;Follow The Regularized Leader&#xff09;是一种优化方法&#xff0c;就如同SGD&#xff08;Stochastic Gradient Descent&#xff09;一样。这里直接给出用FTRL优化LR&#xff08;Logistic Regression&#xff09;的步骤&#xff1a; 其中ptσ(Xt⋅w)ptσ(X…

FTRL算法

概述 GBDT算法是业界比较好用筛选特征的算法&#xff0c;在线学习考虑效率和数据量&#xff0c;经常用GBDT离线筛选特征&#xff0c;输入到在线模型进行实时训练&#xff0c;如今比较好用的方法是GBDTLR&#xff0c;而FTRL是另外一种很高效的算法&#xff0c;与其类似的有OGD&…

FTRL-Proximal

Ad Click Prediction: a View from the Trenches ABSTRACT 广告点击率预测是一个大规模的学习问题&#xff0c;对数十亿美元的在线广告行业至关重要。我们从部署的CTR预测系统的设置中提供了一些案例研究和从最近的实验中提取的话题&#xff0c;包括基于FTRL-Proximal在线学习…

FTRL

一、算法原理 二、算法逻辑 三、个人理解 从loss function的形式来看:FTRL就是将RDA-L1的“梯度累加”思想应用在FOBOS-L1上,并施加一个L2正则项。【PS:paper上是没有加L2正则项的】 这样达到的效果是: 累积加和限定了新的迭代结果W**不要离“已迭代过的解”太远**; 因为…

在线学习算法FTRL基本原理

文章目录 相关介绍SGD: Stochastic Gradient DescentTG简单加入L1范数简单截断法梯度截断法 FOBOS: Forward Backward Splitting[^4]RDA: Regularized dual averaging[^5] FTRL: Follow-the-Regularized-Leader总结 相关介绍 SGD: Stochastic Gradient Descent 由于批量梯度下…

Lr

二、 逻辑回归 言归正传&#xff0c;因为广告大部分是按照CPC计费的&#xff0c;而我们手里的流量是固定的&#xff0c;因此对每条广告请求我们就需要保证这条广告的展示收益更大。而广告收益是可以根据点击率、广告计费价格、广告质量度均衡决定的&#xff0c;所以我们就需要评…

在线学习FTRL介绍及基于Flink实现在线学习流程

背景 目前互联网已经进入了AI驱动业务发展的阶段&#xff0c;传统的机器学习开发流程基本是以下步骤&#xff1a; 数据收集->特征工程->训练模型->评估模型效果->保存模型&#xff0c;并在线上使用训练的有效模型进行预测。 这种方式主要存在两个瓶颈&#xff1…

FTRL的理解

个人理解&#xff1a;FTRL是针对LR学习器&#xff0c;设计了一种独特的梯度下降更新方法 从Logistic Regression到FTRL Logistic Regression在Linear Regression的基础上&#xff0c;使用sigmoid函数将yθxb的输出值映射到0到1之间&#xff0c;且log(P(y1)/P(y0)) θxb。并且…

2021-09-08FTRL 跟随正确的领导者

2.2.3 FTRL FTRL&#xff08;Follow the Regularized Leader&#xff09;是一种优化算法&#xff0c;在处理诸如逻辑回归 之类的带非光滑正则化项的凸优化问题上性能出色&#xff0c;自 2013 年谷歌发表 FTRL 算 法的工程性实现论文后[17]&#xff0c;业界纷纷上线该算法&…

python编程之np.argmin()用法解析

疑惑 np.argmin()究竟是干嘛用的&#xff1f; 解惑 给出水平方向最小值的下标&#xff1b; list最小的值是3&#xff0c;对应的下标是2&#xff1b; list1展平是9,8,7,66,23,55,4,23,33;最小的值是4&#xff0c;对应的下标是6

关于argmin和argmax的一点说明

一、定义 首先我们应该知道&#xff0c;arg是元素&#xff08;变元&#xff09;argument的英文缩写。 在数学中&#xff0c;arg max的参数是指使函数值最大化的某个函数域的点。与全局最大值相反&#xff0c;其指的是函数的最大输出 &#xff0c;同理&#xff0c;arg min指的是…

clickhouse的argMin()和argMax()函数

1.语法规则 函数语法argMin(arg&#xff0c;val)计算最小值的arg值。如果val的最小值有几个不同的arg值&#xff0c;则遇到的第一个值是输出。argMax(arg&#xff0c;val&#xff09;计算最大值的参数值。如果存在多个不同的arg值来表示val的最大值&#xff0c;则遇到的第一个…

LaTeX 书写 argmax and argmin 公式

LaTeX 书写 argmax and argmin 公式 1. arg max or argmax For a real-valued function f f f with domain S S S, arg ⁡ max ⁡ f ( x ) x ∈ S \underset{x\in S}{{\arg\max} \, f(x)} x∈Sargmaxf(x)​ is the set of elements in S S S that achieve the global maxi…

torch.argmin()的使用举例

参考链接: argmin(dimNone, keepdimFalse) → LongTensor 参考链接: torch.argmin() 代码实验举例: Microsoft Windows [版本 10.0.18363.1256] (c) 2019 Microsoft Corporation。保留所有权利。C:\Users\chenxuqi>conda activate ssd4pytorch1_2_0(ssd4pytorch1_2_0) C:\U…

numpy.argmin()||argmax()结构及用法||详解axis

numpy.argmin(a, axisNone, outNone)官方文档 参数详解 a : array_like 输入数组 axis : int, optional 默认输入数组展平&#xff0c;否则&#xff0c;按照指定的axis方向 按照指定轴&#xff0c;可以理解为将数据投影到这个轴上。 out : array, optional如果设置了某个数…