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)
上一篇 2025年8月31日 下午5:43
下一篇 2025年8月31日 下午6:15


相关推荐

  • 白帽子讲web安全 pdf_白帽子讲web安全适合初学者看吗

    白帽子讲web安全 pdf_白帽子讲web安全适合初学者看吗第一篇:世界观安全第一章:我的安全世界观一个网站的数据库,在没有任何保护的情况下,数据库服务端口是允许任何人随意连接的;在有了防火墙的保护后,通过ACL可以控制只允许信任来源的访问。这些措施在很大程度上保证了系统软件处于信任边界之内,从而杜绝了绝大部分的攻击来源。1.1.3Web安全的兴起常见攻击:SQL注入,XSS(跨站脚本攻击)“破坏往往比建设容易”,但凡事都不是绝对的。一般来说,白帽子选择的方

    2025年11月22日
    4
  • 通过PyCharm 把Python 程序打包为exe

    通过PyCharm 把Python 程序打包为exe很多人应该都是使用 PyCharm 编写 python 程序的吧 虽然都是用 pyinstaller 来打包 python 程序为 exe 但是由于 PyCharm 用了虚拟环境 venv 所有一些参数是有区别的 网上查询了很久没有查到这方面的信息 下面这些都是我自己探索出来的 lin49940 步骤一 点击进入 PyCharm 的输入终端 Terminal 步骤二 输入下面的语句 mypython py 替换为你自己的程序名称 pyinstaller c Fmypython py pE d

    2026年3月27日
    2
  • 科大讯飞拟再募资40亿,强化星火大模型与算力平台,抢占AI红利新赛道

    科大讯飞拟再募资40亿,强化星火大模型与算力平台,抢占AI红利新赛道

    2026年3月14日
    2
  • ListView 使用方法(Asp.Net)

    ListView 使用方法(Asp.Net)

    2021年12月30日
    47
  • Java Manifest

    Java ManifestJavaManifest直接使用Javaclass文件来运行程序,但一般发布和运行JAR(JavaArchive)文件,JAR文件是class文件的ZIP压缩存档。Manifest描述了Jar文件的打包、运行信息。JDK提供了用于处理Manifest信息的API,详细的信息请见java.util.jar包,通过给JarFile传递jar文件的路径,然后调用JarFile的

    2025年6月15日
    9
  • CDN技术详解及实现原理「建议收藏」

    CDN技术详解及实现原理「建议收藏」CDN技术详解一本好的入门书是带你进入陌生领域的明灯,《CDN技术详解》绝对是带你进入CDN行业的那盏最亮的明灯。因此,虽然只是纯粹的重点抄录,我也要把《CDN技术详解》的精华放上网。公诸同好。第

    2022年7月2日
    52

发表回复

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

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