【Pytorch】--- 用word2vec的(.bin)文件初始化卷积层方法

在 Pytorch 中, 用预训练好的word2vec权值文件(.bin)来初始化卷积层的权重的方法

import torch
import torch.nn as nn
from gensim import models

model = models.KeyedVectors.load_word2vec_format('./file_name.bin', binary=True)
weight = torch.FloatTensor(model.vectors)

# 前提是file_name.bin中包含的权重的维度是[11352, 300, 1, 1]
conv1 = nn.Conv2d(in_channels=11352, out_channels=300, kernel_size=1, stride=1, padding=0, bias=True)

conv1.weight = torch.nn.Parameter(weight)

你可能感兴趣的:(Python)