🔎大家好,我是Sonhhxg_柒,希望你看完之后,能对你有所帮助,不足请指正!共同学习交流🔎
📝个人主页-Sonhhxg_柒的博客_CSDN博客 📃
🎁欢迎各位→点赞👍 + 收藏⭐️ + 留言📝
📣系列专栏 - 机器学习【ML】 自然语言处理【NLP】 深度学习【DL】
🖍foreword
✔说明⇢本人讲解主要包括Python、机器学习(ML)、深度学习(DL)、自然语言处理(NLP)等内容。
如果你对这个系列感兴趣的话,可以关注订阅哟👋
FNN模型是2016提出来的,当时各大公司都还在探索如何将深度学习技术应用于推荐系统,一些头部公司开始了初步的尝试,比如Google应用并发表了Wide&Deep模型,微软在Bing的搜索广告场景尝试了Deep Crossing模型,都是那个时代的代表模型,对业界发展起到了重要作用。不过即使是号称完全自动化特征工程的Deep Crossing模型,也没有做显式特征交叉。那深度学习时代,能否让模型既有像FM那样做显式特征交叉,又具备DNN的隐式高阶交叉和泛化能力呢?FNN就是这样的尝试,试图将FM和DNN结合起来,模型结构如图所示。
模型的核心思想是采用FM训练得到的隐向量作为神经网络第一层权重的初始值,之后是隐藏层,最后是点击率预估的输出。其实是一个Embedding + MLP结构,特殊的是Embedding的初始值是FM模型已经预训练好的结果。FM与Embedding的初始化对应关系如图所示。
由于Embedding的初始值得到了FM的预训练,因此在训练DNN的时候,模型收敛速度更快;并且Embedding包含了组合特征的信息,可以不用做额外的特征工程;DNN在FM的基础上对特征组合做了进一步的高阶特征组合,模型能得到更好的效果。不过由于整个训练过程分成了两阶段,其实不是一个端到端的训练过程,而是一种基于参数的迁移学习。
FNN存在的问题有:
1. Embedding参数受FM的影响,模型能力受限于FM表征能力的上限;
2. 训练过程分两阶段进行,过程较复杂,效率不高;
3. FNN只能学习高阶特征组合,没有对低阶特征建模,但很多特征的高阶交叉是无意义的。
前馈神经网络Pytorch的实现
-
import torch
-
import torch.nn
as nn
-
import torchvision
-
import torchvision.transforms
as transforms
-
-
-
# 设备配置
-
device
= torch.device(
'cuda'
if torch.cuda.
is_available()
else
'cpu')
-
-
# 超参数
-
input_
size
=
784
-
hidden_
size
=
500
-
num_classes
=
10
-
num_epochs
=
5
-
batch_
size
=
100
-
learning_rate
=
0.001
-
-
# MNIST 数据集
-
train_dataset
= torchvision.datasets.MNIST(root
=
'../../data',
-
train
=
True,
-
transform
=transforms.ToTensor(),
-
download
=
True)
-
-
test_dataset
= torchvision.datasets.MNIST(root
=
'../../data',
-
train
=
False,
-
transform
=transforms.ToTensor())
-
-
# 数据加载器
-
train_loader
= torch.utils.
data.DataLoader(dataset
=train_dataset,
-
batch_
size
=batch_
size,
-
shuffle
=
True)
-
-
test_loader
= torch.utils.
data.DataLoader(dataset
=
test_dataset,
-
batch_
size
=batch_
size,
-
shuffle
=
False)
-
-
# 具有一个隐藏层的全连接神经网络
-
class NeuralNet(nn.Module):
-
def __init__(
self,
input_
size, hidden_
size, num_classes):
-
super(NeuralNet,
self).__init__()
-
self.fc
1
= nn.Linear(
input_
size, hidden_
size)
-
self.relu
= nn.ReLU()
-
self.fc
2
= nn.Linear(hidden_
size, num_classes)
-
-
def forward(
self, x):
-
out
=
self.fc
1(x)
-
out
=
self.relu(out)
-
out
=
self.fc
2(out)
-
return out
-
-
model
= NeuralNet(
input_
size, hidden_
size, num_classes).
to(device)
-
-
# 损失和优化器
-
criterion
= nn.CrossEntropyLoss()
-
optimizer
= torch.optim.Adam(model.parameters(), lr
=learning_rate)
-
-
# 训练模型
-
total_step
= len(train_loader)
-
for epoch
in range(num_epochs):
-
for i, (images, labels)
in enumerate(train_loader):
-
#
Move tensors
to the configured device
-
images
= images.reshape(-
1,
28
*
28).
to(device)
-
labels
= labels.
to(device)
-
-
# 前向传播
-
outputs
= model(images)
-
loss
= criterion(outputs, labels)
-
-
# 向后优化
-
optimizer.
zero_grad()
-
loss.backward()
-
optimizer.step()
-
-
if (i
+
1) %
100
=
=
0:
-
print (
'Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
-
.
format(epoch
+
1, num_epochs, i
+
1, total_step, loss.item()))
-
-
# 测试模型
-
#
In
test phase, we don
't need to compute gradients (for memory efficiency)
-
with torch.no_grad():
-
correct = 0
-
total = 0
-
for images, labels in test_loader:
-
images = images.reshape(-1, 28*28).to(device)
-
labels = labels.to(device)
-
outputs = model(images)
-
_, predicted = torch.max(outputs.data, 1)
-
total += labels.size(0)
-
correct += (predicted == labels).sum().item()
-
-
print('Accuracy
of the network
on the
10000
test images: {} %
'.format(100 * correct / total))
-
-
# 保存模型
-
torch.save(model.state_dict(), 'model.ckpt
')