【深度学习】优化算法-Ftrl

article/2025/9/27 8:30:01

脑图

在这里插入图片描述

代码实现

'''DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSEVersion 2, December 2004Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSETERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION0. You just DO WHAT THE FUCK YOU WANT TO.
'''from datetime import datetime
from csv import DictReader
from math import exp, log, sqrt# TL; DR, the main training process starts on line: 250,
# you may want to start reading the code from there##############################################################################
# parameters #################################################################
############################################################################### A, paths
# path to training file
train = '/Users/avazu/avazu-ctr-prediction/train'               
# path to testing file
test = '/Users/avazu/avazu-ctr-prediction/test'
# path of to be outputted submission file
submission = '/Users/avazu/avazu-ctr-prediction/sampleSubmission_myself'  # B, model
alpha = .1  # learning rate
beta = 1.   # smoothing parameter for adaptive learning rate
L1 = 1.     # L1 regularization, larger value means more regularized
L2 = 1.     # L2 regularization, larger value means more regularized# C, feature/hash trick
D = 2 ** 20             # Hash分桶的数量 number of weights to use
interaction = False     # whether to enable poly2 feature interactions# D, training/validation
epoch = 1       # learn training data for N passes
holdafter = 22   # data after date N (exclusive) are used as validation
holdout = None  # use every N training instance for holdout validation##############################################################################
# class, function, generator definitions #####################################
############################################################################### ftrl实现逻辑
class ftrl_proximal(object):''' Our main algorithm: Follow the regularized leader - proximalIn short,this is an adaptive-learning-rate sparse logistic-regression withefficient L1-L2-regularizationReference:http://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf'''def __init__(self, alpha, beta, L1, L2, D, interaction):# parametersself.alpha = alphaself.beta = betaself.L1 = L1self.L2 = L2# feature related parametersself.D = Dself.interaction = interaction# model# n: squared sum of past gradients# z: weights# w: lazy weightsself.n = [0.] * Dself.z = [0.] * Dself.w = {}def _indices(self, x):''' A helper generator that yields the indices in xThe purpose of this generator is to make the followingcode a bit cleaner when doing feature interaction.'''# first yield index of the bias termyield 0# then yield the normal indicesfor index in x:yield index# now yield interactions (if applicable)if self.interaction:D = self.DL = len(x)x = sorted(x)for i in range(L):for j in range(i+1, L):# one-hot encode interactions with hash trickyield abs(hash(str(x[i]) + '_' + str(x[j]))) % Ddef predict(self, x):''' Get probability estimation on xINPUT:x: featuresOUTPUT:probability of p(y = 1 | x; w)'''# parametersalpha = self.alphabeta = self.betaL1 = self.L1L2 = self.L2# modeln = self.nz = self.zw = {}# wTx is the inner product of w and xwTx = 0.for i in self._indices(x):sign = -1. if z[i] < 0 else 1.  # get sign of z[i]# build w on the fly using z and n, hence the name - lazy weights# we are doing this at prediction instead of update time is because# this allows us for not storing the complete wif sign * z[i] <= L1:# w[i] vanishes due to L1 regularizationw[i] = 0.else:# apply prediction time L1, L2 regularization to z and get ww[i] = (sign * L1 - z[i]) / ((beta + sqrt(n[i])) / alpha + L2)wTx += w[i]# cache the current w for update stageself.w = w# bounded sigmoid function, this is the probability estimation# 做SIGMOD函数return 1. / (1. + exp(-max(min(wTx, 35.), -35.)))#反向传导计算def update(self, x, p, y):''' Update model using x, p, yINPUT:x: feature, a list of indicesp: click probability prediction of our modely: answerMODIFIES:self.n: increase by squared gradientself.z: weights'''# parameteralpha = self.alpha# modeln = self.nz = self.zw = self.w# gradient under loglossg = p - y# update z and nfor i in self._indices(x):sigma = (sqrt(n[i] + g * g) - sqrt(n[i])) / alphaz[i] += g - sigma * w[i]n[i] += g * gdef logloss(p, y):''' FUNCTION: Bounded loglossINPUT:p: our predictiony: real answerOUTPUT:logarithmic loss of p given y'''p = max(min(p, 1. - 10e-15), 10e-15)return -log(p) if y == 1. else -log(1. - p)def data(path, D):''' GENERATOR: Apply hash-trick to the original csv rowand for simplicity, we one-hot-encode everythingINPUT:path: path to training or testing fileD: the max index that we can hash toYIELDS:ID: id of the instance, mainly uselessx: a list of hashed and one-hot-encoded 'indices'we only need the index since all values are either 0 or 1y: y = 1 if we have a click, else we have y = 0'''for t, row in enumerate(DictReader(open(path))):# process idID = row['id']del row['id']# process clicksy = 0.if 'click' in row:if row['click'] == '1':y = 1.del row['click']# extract datedate = int(row['hour'][4:6])# turn hour really into hour, it was originally YYMMDDHHrow['hour'] = row['hour'][6:]# build xx = []for key in row:value = row[key]# one-hot encode everything with hash trickindex = abs(hash(key + '_' + value)) % Dx.append(index)yield t, date, ID, x, y##############################################################################
# start training #############################################################
##############################################################################start = datetime.now()# initialize ourselves a learner
learner = ftrl_proximal(alpha, beta, L1, L2, D, interaction)# start training
for e in range(epoch):loss = 0.count = 0for t, date, ID, x, y in data(train, D):  # data is a generator#    t: just a instance counter# date: you know what this is#   ID: id provided in original data#    x: features#    y: label (click)# step 1, get prediction from learnerp = learner.predict(x)if (holdafter and date > holdafter) or (holdout and t % holdout == 0):# step 2-1, calculate validation loss#           we do not train with the validation data so that our#           validation loss is an accurate estimation## holdafter: train instances from day 1 to day N#            validate with instances from day N + 1 and after## holdout: validate with every N instance, train with othersloss += logloss(p, y)count += 1else:# step 2-2, update learner with label (click) informationlearner.update(x, p, y)print('Epoch %d finished, validation logloss: %f, elapsed time: %s' % (e, loss/count, str(datetime.now() - start)))##############################################################################
# start testing, and build Kaggle's submission file ##########################
##############################################################################with open(submission, 'w') as outfile:outfile.write('id,click\n')for t, date, ID, x, y in data(test, D):p = learner.predict(x)outfile.write('%s,%s\n' % (ID, str(p)))

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

相关文章

谷歌13年提出来的类似于lr的算法 - ftrl论文翻译(七)

论文链接&#xff1a;https://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/41159.pdf 概要 预测广告点击率&#xff08;CTR&#xff09;是一个巨大的规模学习问题&#xff0c;是在线广告业数十亿美元的核心问题。 我们从最近的实验中选择出…

FTRL 算法

本文会尝试总结FTRL的发展由来&#xff0c;总结从LR -> SGD -> TG -> FOBOS -> RDA -> FTRL 的发展历程。本文的主要目录如下&#xff1a; 一、 反思魏则西事件。 二、 LR模型 三、 SGD算法 四、 TG算法 五、 FOBOS算法 六、 RDA算法 七、 FTRL算法 注&…

排序模型进阶-FMFTRL

日萌社 人工智能AI&#xff1a;Keras PyTorch MXNet TensorFlow PaddlePaddle 深度学习实战&#xff08;不定时更新&#xff09; 5.8 排序模型进阶-FM&FTRL 学习目标 目标 无应用 无 5.8.1 问题 在实际项目的时候&#xff0c;经常会遇到训练数据非常大导致一些算法实际…

以我视角深入理解FTRL模型原理

以我视角深入理解FTRL模型原理 FTRL算法是吸取了FOBOS算法和RDA算法的优点而衍生而来的算法。 1.FOBOS算法 小结&#xff1a; 2. RDA算法 RDA也叫正则对偶平均算法&#xff0c;特征权重更新如下&#xff1a; 小结&#xff1a; 3.FTRL算法原理 从loss function的形式来看&am…

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

理解要点&#xff1a;主要是梯度更新的方法使用了FTRL。即更改了梯度的update函数。 相关参考&#xff1a;https://github.com/wan501278191/OnlineLearning_BasicAlgorithm/blob/master/FTRL.py FTRL&#xff08;Follow The Regularized Leader&#xff09;是一种优化…

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