CBOW 更新[通俗易懂]

CBOW 更新[通俗易懂]代码:importtorchimporttorch.nnasnnimportnumpyasnpdefmake_context_vector(context,word_to_ix):idxs=[word_to_ix[w]forwincontext]returntorch.tensor(idxs,dtype=torch.long)…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

代码:

import torch
import torch.nn as nn
import numpy as np


def make_context_vector(context, word_to_ix):
    idxs = [word_to_ix[w] for w in context]
    return torch.tensor(idxs, dtype=torch.long)


def get_index_of_max(input):
    index = 0
    for i in range(1, len(input)):
        if input[i] > input[index]:
            index = i
    return index


def get_max_prob_result(input, ix_to_word):
    return ix_to_word[get_index_of_max(input)]


CONTEXT_SIZE = 2  # 2 words to the left, 2 to the right
EMDEDDING_DIM = 100

word_to_ix = {}
ix_to_word = {}

raw_text = """We are about to study the idea of a computational process.
Computational processes are abstract beings that inhabit computers.
As they evolve, processes manipulate other abstract things called data.
The evolution of a process is directed by a pattern of rules
called a program. People create programs to direct processes. In effect,
we conjure the spirits of the computer with our spells.""".split()

# By deriving a set from `raw_text`, we deduplicate the array
vocab = set(raw_text)
vocab_size = len(vocab)

for i, word in enumerate(vocab):
    word_to_ix[word] = i
    ix_to_word[i] = word

data = []
for i in range(2, len(raw_text) - 2):
    context = [raw_text[i - 2], raw_text[i - 1],
               raw_text[i + 1], raw_text[i + 2]]
    target = raw_text[i]
    data.append((context, target))


class CBOW(torch.nn.Module):

    def __init__(self, vocab_size, embedding_dim):
        super(CBOW, self).__init__()

        # out: 1 x emdedding_dim
        self.embeddings = nn.Embedding(vocab_size, embedding_dim)

        self.linear1 = nn.Linear(embedding_dim, 128)

        self.activation_function1 = nn.ReLU()

        # out: 1 x vocab_size
        self.linear2 = nn.Linear(128, vocab_size)

        self.activation_function2 = nn.LogSoftmax(dim=-1)

    def forward(self, inputs):
        embeds = sum(self.embeddings(inputs)).view(1, -1)
        out = self.linear1(embeds)
        out = self.activation_function1(out)
        out = self.linear2(out)
        out = self.activation_function2(out)
        return out

    def get_word_emdedding(self, word):
        word = torch.LongTensor([word_to_ix[word]])
        return self.embeddings(word).view(1, -1)


model = CBOW(vocab_size, EMDEDDING_DIM)

loss_function = nn.NLLLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)

for epoch in range(50):
    total_loss = 0
    for context, target in data:
        context_vector = make_context_vector(context, word_to_ix)
        model.zero_grad()
        log_probs = model(context_vector)
        loss = loss_function(log_probs, torch.tensor([word_to_ix[target]], dtype=torch.long))
        loss.backward()
        optimizer.step()

        total_loss += loss.data

# ====================== TEST
context = ['People', 'create', 'to', 'direct']
context_vector = make_context_vector(context, word_to_ix)
a = model(context_vector).data.numpy()
print('Raw text: {}\n'.format(' '.join(raw_text)))
print('Context: {}\n'.format(context))
print('Prediction: {}'.format(get_max_prob_result(a[0], ix_to_word)))

结果:

Context: ['People', 'create', 'to', 'direct']

Prediction: programs

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/197603.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Kotlin学习之路(1)环境介绍及安装

    Kotlin学习之路(1)环境介绍及安装

    2021年3月12日
    145
  • win10应用商店错误代码0x8000FFFF_错误代码0xc000007b

    win10应用商店错误代码0x8000FFFF_错误代码0xc000007b控制面板内打开网络和Internet Internet选项 连接 设置 自动检测设置

    2022年9月2日
    4
  • 文本挖掘的介绍

    文本挖掘的介绍1、文本挖掘的定义文本挖掘是指从大量文本的集合C中发现隐含的模式p。如果将C看作输入,将p看作输出,那么文本挖掘的过程就是从输入到输出的一个映射ξ:C→p。2、文本挖掘过程包含的技术文本特征的提取、信息检索、自然语言处理、文本挖掘、文本分类、文本聚类、关联分析等等3、文本挖掘的一般过程3.1 数据预处理技术预处理技术主要包括Stemming(英文)/分词(中文

    2022年6月29日
    20
  • mysql时区重启后失效_mysql时区问题

    mysql时区重启后失效_mysql时区问题背景插入 timestamp 类型与 datetime 类型数据比预计结果早 14 小时原因如果说相差 8 小时不够让人惊讶 那相差 13 小时可能会让很多人摸不着头脑 出现这个问题的原因是 JDBC 与 MySQL 对 CST 时区协商不一致 因为 CST 时区是一个很混乱的时区 有四种含义 美国中部时间 CentralStand USA UTC 05 00 或 UTC 06 00 澳大利亚中部时间 Cen

    2025年9月29日
    0
  • js对象(2)「建议收藏」

    js对象(2)「建议收藏」1.JavaScript原型如果所有对象都有私有字段[[prototype]],就是对象的原型;读一个属性,如果对象本身没有,则会继续访问对象的原型,直到原型为空或者找到为止。操作原型的三种方法:Object.create根据指定的原型创建新对象,原型可以是null;Object.getPrototypeOf获得一个对象的原型;Object.setPrototypeOf设置一个对象的原型。varcat={say(){

    2022年7月23日
    13
  • python pip 换源_python添加pip环境变量

    python pip 换源_python添加pip环境变量你好,我是悦创。我接下来,把所有Pythonpip换源的方法,都整理下来。第一种方法打开appdata文件夹,在资源管理器的地址栏输入%appdata%后回车:2.新建一个pip文件夹,在pip文件夹里面新建一个配置文件pip.ini:3.在配置文件中输入如下内容后保存即可:[global]timeout=6000index-url=https://pypi.tuna.tsinghua.edu.cn/simpletrusted-host=py

    2025年6月15日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号