30.9 Factorization Machines
A linear model assigns a separate weight to every feature but cannot change the contribution of one feature according to another. Explicitly assigning a parameter to every feature pair is usually infeasible for sparse, high-dimensional inputs. A second-order factorization machine (FM) (Rendle, 2010) gives each feature a -dimensional vector and uses vector inner products as pairwise coefficients. This low-rank parameterization shares statistical strength across pairs and admits a computation linear in the number of active features.
30.9.1 2-Way Factorization Machines#
For an input , a second-order FM has score
Here is an intercept, contains the linear coefficients, and the rows of determine the pairwise coefficients. The coefficient for is not free: it must equal . For one-hot user and item features, this pairwise term contains the matrix-factorization score as a special case. Higher-order FMs require additional parameterizations; they do not follow from the second-order equation merely by increasing .
30.9.2 An Efficient Optimization Criterion#
Directly summing all feature pairs costs for a dense input. For latent coordinate , expand : its cross terms count every unordered pair twice, while contains the diagonal terms. Subtracting the diagonal and dividing by two gives
The two inner sums can be accumulated in one pass. The cost is therefore for a dense vector and when only nonzero entries are visited.
To learn the FM model, we can use the MSE loss for regression task, the cross-entropy loss for classification tasks, and the BPR loss for ranking task. Standard optimizers such as stochastic gradient descent and Adam are viable for optimization.
import os30.9.3 Model Implementation#
The implementation computes the linear term and the square-of-sum identity separately. It returns logits; a loss that combines the sigmoid and binary cross-entropy avoids explicitly taking logarithms of probabilities near zero or one.
In PyTorch this loss is BCEWithLogitsLoss.
class FM(nn.Module):
def __init__(self, field_dims, num_factors):
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)
def forward(self, x):
square_of_sum = self.embedding(x).sum(dim=1) ** 2
sum_of_square = (self.embedding(x) ** 2).sum(dim=1)
x = self.linear_layer(self.fc(x).sum(dim=1)) \
+ 0.5 * (square_of_sum - sum_of_square).sum(dim=1, keepdim=True)
return x30.9.4 Load the Advertising Dataset#
We use the CTR data wrapper from the last section to load the online advertising dataset.
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)
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())30.9.5 Train the Model#
Afterwards, we train the model. The learning rate is set to 0.02 and the embedding size is set to 20 by default. The Adam optimizer and the loss that combines the sigmoid and binary cross-entropy are used for model training.
devices = d2l.try_all_gpus()
net = FM(train_data.field_dims, num_factors=20)
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.02, 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.006, train acc 1.000, test acc 0.932
192108.8 examples/sec on [device(type='cuda', index=0)]
30.9.6 Summary#
- A second-order FM parameterizes every pair coefficient as an inner product of feature vectors, sharing parameters across sparse feature pairs.
- Its pairwise score costs using the square-of-sum identity.
30.9.7 Exercises#
- For an input with a one-hot user field and a one-hot item field, show that the FM score is , matrix factorization with biases and a global offset. Add a third one-hot field for the hour of the day, write out the pairwise terms, and count the parameters of the FM with for field sizes 943, 1,682, and 24. Compare with a model that has a free weight for every pair of features from different fields.
- Show that the derivative of the pairwise term with respect to is . Explain how the sums computed in the forward pass give the gradient for all active embedding coordinates in time.
train_ch13reports accuracy only. Record the training and test log loss after every epoch and find the epoch at which the test log loss is lowest. Then train with and a model without the pairwise term, which is logistic regression on the same features, and report the lowest test log loss of each. How much does the pairwise term improve on logistic regression on this dataset?- Encode MovieLens 100K as two fields, user and item, with the offset scheme
of
CTRDataset, trainFMwith the squared loss on theseq-awaresplit, and compare its test RMSE with that ofMFon the same split. Use the first problem to explain why the two values should be close. Which additional field derived from the MovieLens data could make them differ? - Show that no second-order FM, for any , represents the three-way interaction of three binary features exactly on all eight inputs. A third-order term fixes this. Using the identity for the third elementary symmetric polynomial of numbers , where , compute this term in time.