import torch
from torch import nn, optim
from torch.autograd import Variable
import torch.nn.functional as F CONTEXT_SIZE = 2 # 2 words to the left, 2 to the right
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(' ') vocab = set(raw_text)
word_to_idx = {word: i for i, word in enumerate(vocab)} data = []
for i in range(CONTEXT_SIZE, len(raw_text)-CONTEXT_SIZE):
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(nn.Module):
def __init__(self, n_word, n_dim, context_size):
super(CBOW, self).__init__()
self.embedding = nn.Embedding(n_word, n_dim)
self.linear1 = nn.Linear(2*context_size*n_dim, 128)
self.linear2 = nn.Linear(128, n_word) def forward(self, x):
x = self.embedding(x)
x = x.view(1, -1)
x = self.linear1(x)
x = F.relu(x, inplace=True)
x = self.linear2(x)
x = F.log_softmax(x)
return x model = CBOW(len(word_to_idx), 100, CONTEXT_SIZE)
if torch.cuda.is_available():
model = model.cuda() criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=1e-3) for epoch in range(100):
print('epoch {}'.format(epoch))
print('*'*10)
running_loss = 0
for word in data:
context, target = word
context = Variable(torch.LongTensor([word_to_idx[i] for i in context]))
target = Variable(torch.LongTensor([word_to_idx[target]]))
if torch.cuda.is_available():
context = context.cuda()
target = target.cuda()
# forward
out = model(context)
loss = criterion(out, target)
running_loss += loss.data[0]
# backward
optimizer.zero_grad()
loss.backward()
optimizer.step()
print('loss: {:.6f}'.format(running_loss / len(data)))

PyTorch学习笔记之CBOW模型实践的更多相关文章

  1. [PyTorch 学习笔记] 3.1 模型创建步骤与 nn.Module

    本章代码:https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson3/module_containers.py 这篇文章来看下 ...

  2. [PyTorch 学习笔记] 7.1 模型保存与加载

    本章代码: https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson7/model_save.py https://githu ...

  3. PyTorch学习笔记之n-gram模型实现

    import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as ...

  4. 操作系统学习笔记----进程/线程模型----Coursera课程笔记

    操作系统学习笔记----进程/线程模型----Coursera课程笔记 进程/线程模型 0. 概述 0.1 进程模型 多道程序设计 进程的概念.进程控制块 进程状态及转换.进程队列 进程控制----进 ...

  5. V-rep学习笔记:机器人模型创建3—搭建动力学模型

    接着之前写的V-rep学习笔记:机器人模型创建2—添加关节继续机器人创建流程.如果已经添加好关节,那么就可以进入流程的最后一步:搭建层次结构模型和模型定义(build the model hierar ...

  6. V-rep学习笔记:机器人模型创建2—添加关节

    下面接着之前经过简化并调整好视觉效果的模型继续工作流,为了使模型能受控制运动起来必须在合适的位置上添加相应的运动副/关节.一般情况下我们可以查阅手册或根据设计图纸获得这些关节的准确位置和姿态,知道这些 ...

  7. ArcGIS模型构建器案例学习笔记-字段处理模型集

    ArcGIS模型构建器案例学习笔记-字段处理模型集 联系方式:谢老师,135-4855-4328,xiexiaokui@qq.com 由四个子模型组成 子模型1:判断字段是否存在 方法:python工 ...

  8. springmvc学习笔记--Interceptor机制和实践

    前言: Spring的AOP理念, 以及j2ee中责任链(过滤器链)的设计模式, 确实深入人心, 处处可以看到它的身影. 这次借项目空闲, 来总结一下SpringMVC的Interceptor机制, ...

  9. java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)

    java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessCo ...

随机推荐

  1. python列表中的深浅copy

    列表中的赋值和平常的赋值是不一样的,看下面的代码: In [1]: a = 1 In [2]: b = a In [3]: a Out[3]: 1 In [4]: b Out[4]: 1 In [5] ...

  2. vscode设置让鼠标滚动改变字体大小

    打开settings.json文件 输入"editor.mouseWheelZoom": true, 这样比较方面,比默认的放大缩小来的快捷

  3. HDU 4871 Shortest-path tree 最短路 + 树分治

    题意: 输入一个带权的无向连通图 定义以顶点\(u\)为根的最短路生成树为: 树上任何点\(v\)到\(u\)的距离都是原图最短的,如果有多条最短路,取字典序最小的那条. 然后询问生成树上恰好包含\( ...

  4. Mac 之 STF 搭建(淘宝源安装)

    参考链接:https://www.jianshu.com/p/5fe8cb7d214f (MAC直接安装STF)https://www.jianshu.com/p/c5c298486dbd(homeb ...

  5. Vue简单了解

    目录 1. 前端概览 2. 现代前端开发方式 3. MVVM开发核心 4. Vue核心 5. Vue优点 6. Vue难点 7. Vue与非Vue项目结合 8. Vue调试 9. Vue与SEO 今天 ...

  6. Leetcode3--->无重复字符的最长子串长度

    题目:给定一个字符串string,找出string中无重复字符的最长子串. 举例: Given "abcabcbb", the answer is "abc", ...

  7. day05_05 for循环、break语句

    1.0 输入用户名,密码练习 _user = "alex" _passwd = "abc123" username = input("Username ...

  8. Welcome-to-Swift-10属性 (Properties)

    属性将值跟特定的类.结构或枚举关联.存储属性存储常量或变量作为实例的一部分,计算属性计算(而不是存储)一个值.计算属性可以用于类.结构体和枚举里,存储属性只能用于类和结构体. 存储属性和计算属性通常用 ...

  9. 天气预报接口:SmartWeather API中key的计算方法

    这个代码大家都蛮感兴趣,我在git开源了一个用于收集天气信息的系统,基于python语言的,请大家参考: https://github.com/BerlinSun/WeatherForecast -- ...

  10. 【Luogu】P1169棋盘制作(单调栈)

    题目链接 唉……这种题放在NOIP以前我是会做的……但是为什么现在反而不会了…… 单调栈.预处理每个点向上能扩展的最大距离,左右用两遍单调栈扫一遍.注意边界. #include<cstdio&g ...