笔记

GPU使用

查询GPU状态:

nvidia-smi

使用给定编号的GPU:

方法一:

import torch
device = torch.device('cuda:1' if torch.cuda.is_available() else 'cpu')

方法二:

import torch
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
device = torch.device('cuda:1' if torch.cuda.is_available() else 'cpu')

Word-Embedding fine-tune

例如用GloVe,对文本单词生成对应的Word-Embedding,这是一个矩阵。在神经网络中,会有一个Embedding层:

self.embedding = nn.Embedding(len(vocab), embed_size)

这个Word-Embedding矩阵便是self.embedding层的参数。也就是说,对Word-Embedding进行微调,便是对self.embedding层的参数进行更新。

net.embedding.weight.data.copy_(load_pretrained_embedding(vocab.itos, glove))
net.embedding.weight.requires_grad = False # False表示不更新参数,即不进行fine-tune;True表示更新参数,进行fine-tune

更为简便的方法是,将得到的GloVe编码矩阵,存储在self.config.pretrained_embeddings中,并将该参数传入self.embedding层中。

self.embedding = nn.Embedding.from_pretrained(torch.from_numpy(self.config.pretrained_embeddings))
self.embedding.requieres_grad = True # 进行fine-tune

你可能感兴趣的:(python)