首先复制上一篇博客的完整代码,代码如下:

注:如果有不明白的地方请参考上一篇博客——torchtext处理文本数据——构造dataset读取文本(学习一)

数据源和解释都在上一篇博客中

from torchtext import data


def split_tokenize(x):  # 传入的x就是一个格子的文本
    return x.split(' ')  # 按空格切分


def country_tokenize(x):  # 这是专门处理国家字段,不分词直接返回结果
    return x  # 比如传入United Kingdom,我们不要切分成['United', 'Kingdom'],这是干嘛呀,我们就直接返回国家名就行


NAME = data.Field()  # 不传tokenize,默认会按照空格分开
COUNTRY = data.Field(tokenize=country_tokenize)
Comment = data.Field(tokenize=split_tokenize, init_token='<SOS>', eos_token='<EOS>')
fields = [('name', NAME), ('country', COUNTRY), ('age', None), ('comment', Comment)]
train = data.TabularDataset.splits(
    path='./',
    train='my_csv_text.csv',
    format='csv',
    skip_header=True,
    fields=fields)
train = train[0]
print("分词结果:", train.examples[0].comment)
# =========================以上内容解释请参考:https://blog.csdn.net/weixin_35757704/article/details/119976681=========================

构建词表

在此基础上,我们构建词表build_vocab,构建词表的最终目的是:

  • 输入:[word1,word2,word3,]
  • 输出:
    [
    [word1对应的词向量],
    [word2对应的词向量],
    [word3对应的词向量],
    ]
    我们之后的操作便是为此做准备,顺着上面的代码,后续代码是:
# =========================步骤0:训练一个word2vec模型=========================
from gensim.models import Word2Vec


def train_word2vec(sentences):
    model = Word2Vec(sentences, vector_size=256, min_count=1, window=5, sg=0)
    return model


word2vec_model = train_word2vec([train.examples[0].comment, train.examples[1].comment])  # 这里训练了一个超级差劲的word2vec模型,但是意思就是这个意思
word2vec_model.wv.save_word2vec_format('my_word2vec_format.txt')
# =========================步骤1:构建全部词表=========================
from torchtext.vocab import Vectors

vectors = Vectors(name='my_word2vec_format.txt')

# =========================步骤2:构建词典=========================
Comment.build_vocab(train, vectors=vectors)

# =========================步骤3:得到想要的东西=========================
print(len(Comment.vocab))  # 词表里有12个单词
print(Comment.vocab.itos)  # 不同词的编号 int编号:词
print(Comment.vocab.stoi)  # 不同词的编号 词:int编号

print(Comment.vocab.stoi['love'])  # 根据词获得int编号,得到"love"对应的编号为6
print(Comment.vocab.itos[6])  # 根据编号得到词,得到编号6对应的词"love"
print(Comment.vocab.vectors[6])  # 根据编号得到对应的词向量

其实到这里,我们就可以自己去构建一些方法,得到一个句子的词向量了,但是torchtext构造了一些可以内置的方法,以便我们更方便的写代码,之后的内容请参考下一篇博客

目前为止的完整代码

from torchtext import data


def split_tokenize(x):  # 传入的x就是一个格子的文本
    return x.split(' ')  # 按空格切分


def country_tokenize(x):  # 这是专门处理国家字段,不分词直接返回结果
    return x  # 比如传入United Kingdom,我们不要切分成['United', 'Kingdom'],这是干嘛呀,我们就直接返回国家名就行


NAME = data.Field()  # 不传tokenize,默认会按照空格分开
COUNTRY = data.Field(tokenize=country_tokenize)
Comment = data.Field(tokenize=split_tokenize, init_token='<SOS>', eos_token='<EOS>')
fields = [('name', NAME), ('country', COUNTRY), ('age', None), ('comment', Comment)]
train = data.TabularDataset.splits(
    path='./',
    train='my_csv_text.csv',
    format='csv',
    skip_header=True,
    fields=fields)
train = train[0]
print("分词结果:", train.examples[0].comment)
# =========================以上内容解释请参考:https://blog.csdn.net/weixin_35757704/article/details/119976681=========================
# =========================步骤0:训练一个word2vec模型=========================
from gensim.models import Word2Vec


def train_word2vec(sentences):
    model = Word2Vec(sentences, vector_size=256, min_count=1, window=5, sg=0)
    return model


word2vec_model = train_word2vec([train.examples[0].comment, train.examples[1].comment])  # 这里训练了一个超级差劲的模型,但是意思就是这个意思
word2vec_model.wv.save_word2vec_format('my_word2vec_format.txt')
# =========================步骤1:构建全部词表=========================
from torchtext.vocab import Vectors

vectors = Vectors(name='my_word2vec_format.txt')

# =========================步骤2:构建词典=========================
Comment.build_vocab(train, vectors=vectors)

# =========================步骤3:得到想要的东西=========================
print(len(Comment.vocab))  # 词表里有12个单词
print(Comment.vocab.itos)  # 不同词的编号 int编号:词
print(Comment.vocab.stoi)  # 不同词的编号 词:int编号

print(Comment.vocab.stoi['love'])  # 根据词获得int编号,得到"love"对应的编号为6
print(Comment.vocab.itos[6])  # 根据编号得到词,得到编号6对应的词"love"
print(Comment.vocab.vectors[6])  # 根据编号得到对应的词向量
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐