30.10 Deep Factorization Machines
A second-order factorization machine assigns a structured coefficient to each feature pair, but its score contains no interaction involving three or more feature values at once. An MLP applied to all field embeddings can represent such joint dependence, although it does not preserve the FM's explicit pairwise term. DeepFM (Guo et al., 2017) combines these two inductive biases and shares the embedding table between them.
The distinction is architectural, not a guarantee that one branch learns only “low-order” effects and the other only “high-order” effects. Their learned roles depend on the data, regularization, and optimization.
30.10.1 Model Architectures#
Suppose an example contains one categorical value from each of fields. A shared lookup table maps those values to embeddings . The FM branch uses the embeddings in its pairwise inner products. In parallel, the deep branch concatenates them:
Let be the FM logit and the deep-branch logit. Their sum determines the click probability:
DeepFM uses one field-embedding table in two branches. The FM branch computes linear and pairwise terms; the MLP branch transforms the concatenated embeddings. Adding their logits before the sigmoid produces the click probability.
DeepFM is one of several ways to combine explicit interaction terms with learned nonlinear features; another applies nonlinear layers directly to interaction features (He and Chua, 2017).
import os30.10.2 Implementation of DeepFM#
The implementation of DeepFM is similar to that of FM. We keep the FM part unchanged and use an MLP block with relu as the activation function. Dropout is also used to regularize the model. The number of neurons of the MLP can be adjusted with the mlp_dims hyperparameter.
class DeepFM(nn.Module):
def __init__(self, field_dims, num_factors, mlp_dims, drop_rate=0.1):
super().__init__()
num_inputs = int(sum(field_dims))
self.embedding = nn.Embedding(num_inputs, num_factors)
self.fc = nn.Embedding(num_inputs, 1)
self.linear_layer = nn.Linear(1, 1)
input_dim = self.embed_output_dim = len(field_dims) * num_factors
mlp_layers = []
for dim in mlp_dims:
mlp_layers.append(nn.Linear(input_dim, dim))
mlp_layers.append(nn.ReLU())
mlp_layers.append(nn.Dropout(p=drop_rate))
input_dim = dim
mlp_layers.append(nn.Linear(input_dim, 1))
self.mlp = nn.Sequential(*mlp_layers)
def forward(self, x):
embed_x = self.embedding(x)
square_of_sum = embed_x.sum(dim=1) ** 2
sum_of_square = (embed_x ** 2).sum(dim=1)
inputs = embed_x.reshape(-1, self.embed_output_dim)
x = self.linear_layer(self.fc(x).sum(dim=1)) \
+ 0.5 * (square_of_sum - sum_of_square).sum(dim=1, keepdim=True) \
+ self.mlp(inputs)
return x30.10.3 Training and Evaluating the Model#
The data loading process is the same as that of FM. We set the MLP component of DeepFM to a three-layered dense network with a pyramid structure (30-20-10). All other hyperparameters remain the same as FM.
batch_size = 2048
data_dir = d2l.download_extract('ctr')
train_data = d2l.CTRDataset(os.path.join(data_dir, 'train.csv'))
test_data = d2l.CTRDataset(os.path.join(data_dir, 'test.csv'),
feat_mapper=train_data.feat_mapper,
defaults=train_data.defaults)
field_dims = train_data.field_dims
train_iter = torch.utils.data.DataLoader(
train_data, shuffle=True, drop_last=True, batch_size=batch_size,
num_workers=d2l.get_dataloader_workers())
test_iter = torch.utils.data.DataLoader(
test_data, shuffle=False, drop_last=True, batch_size=batch_size,
num_workers=d2l.get_dataloader_workers())
devices = d2l.try_all_gpus()
net = DeepFM(field_dims, num_factors=10, mlp_dims=[30, 20, 10])
def init_weights(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
if type(m) == nn.Embedding:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
lr, num_epochs = 0.01, 30
optimizer = torch.optim.Adam(net.parameters(), lr=lr)
loss = nn.BCEWithLogitsLoss(reduction='none')
d2l.train_ch13(net, train_iter, test_iter, loss, optimizer, num_epochs, devices)loss 0.009, train acc 0.996, test acc 0.932
241492.0 examples/sec on [device(type='cuda', index=0)]
On this particular split and optimization setting, the plotted DeepFM run reaches a lower loss sooner than the FM run. This is an illustrative comparison, not evidence that DeepFM dominates FM across datasets or matched hyperparameter searches.
30.10.4 Summary#
- DeepFM adds the logits of an FM branch and an MLP branch that share field embeddings.
- The FM supplies explicit pairwise terms; the MLP permits joint nonlinear dependence among all embedded fields.
30.10.5 Exercises#
- Write the FM pairwise term as a quadratic form in the concatenated embeddings and give . A ReLU MLP computes a piecewise linear function of . Show that the largest error of any such function as an approximation of the pairwise term on the ball of radius grows at least proportionally to as . What does this suggest about adding the explicit FM term to the MLP?
- The
FMrun of the previous section uses and a learning rate of 0.02, while the DeepFM run uses and 0.01. Rerun both with and a learning rate of 0.01, and add a third model that keeps the linear term and the MLP but drops the pairwise term. Report the lowest test log loss of each across epochs. Does the comparison stated after the training run hold when the settings match? - DeepFM feeds the same embeddings to both branches, while NeuMF gives its
two branches separate tables. Modify
DeepFMso that the MLP has its own embedding table, and report the number of parameters and the lowest test log loss of both versions with the settings above. What does sharing the table constrain? - An embedding row of a feature value that occurs in training
impressions receives a gradient from the data only in minibatches that
contain one of them, while every weight of the MLP receives one in every
minibatch. With 15,000 training impressions, batches of 2,048, and
incomplete final batches dropped, compute the expected number of minibatches per epoch
that update the row of a value with , the default
min_threshold. How does the default row of each field, which collects all rare values, differ? Which of the two kinds of parameters benefits more from Adam's per-coordinate step size? - Train DeepFM with
mlp_dimsset to[30, 20, 10],[100, 100], and[400, 400, 400], the setting of (Guo et al., 2017). For each, report the number of MLP parameters and the training and lowest test log loss. Which setting overfits the 15,000 training impressions, and does a dropout rate of 0.5 change the answer?