You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#|exportdefget_enc_embs(X, enc_learn, module=None, cpu=False, average_seq_dim=True,
to_numpy=True, bs=None):
""" (From deepvats https://github.com/vrodriguezf/deepvats/blob/master/nbs/encoder.ipynb) Get the embeddings of X from an encoder, passed in `enc_learn as a fastai learner. By default, the embeddings are obtained from the last layer before the model head, although any layer can be passed to `model`. Input - `cpu`: Whether to do the model inference in cpu of gpu (GPU recommended) - `average_seq_dim`: Whether to aggregate the embeddings in the sequence dimensions - `to_numpy`: Whether to return the result as a numpy array (if false returns a tensor) - `bs`: Batch size to use for the inference (if None, uses the batch size of the validation dataloader of `enc_learn`) """ifcpu:
enc_learn.dls.cpu()
enc_learn.cpu()
else:
enc_learn.dls.cuda()
enc_learn.cuda()
aux_dl=enc_learn.dls.valid.new_dl(X=X)
# Set batch size for aux_dlifbsisnotNone:
aux_dl.bs=bselifenc_learn.dls.bs>0:
aux_dl.bs=enc_learn.dls.bselse:
aux_dl.bs=64module=nested_attr(enc_learn.model,
AE_EMBS_MODULE_NAME[type(enc_learn.model)]) \
ifmoduleisNoneelsemoduledefembs_generator():
forbinaux_dl:
emb=get_acts_and_grads(model=enc_learn.model,
modules=module,
x=b[0], cpu=cpu)[0]
ifto_numpy:
emb=emb.numpy() ifcpuelseemb.cpu().numpy()
yieldembembs=list(embs_generator())
embs=np.concatenate(embs, axis=0) ifto_numpyelseto_concat(embs)
ifembs.ndim==3andaverage_seq_dim: embs=embs.mean(axis=2)
returnembs
The text was updated successfully, but these errors were encountered:
This is a working code:
The text was updated successfully, but these errors were encountered: