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. L2-006 树的遍历 RTA

    L2-006 树的遍历(25 分) 给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列.这里假设键值都是互不相等的正整数. 输入格式: 输入第一行给出一个正整数N(<=30),是二叉树 ...

  2. poj 3262 牛毁坏花问题 贪心算法

    题意:有n头牛,每头牛回去都需要一定时间,如果呆在原地就会毁坏花朵.问:怎么安排使得毁坏的花朵最少? 思路: 拉走成本最高的. 什么是成本?毁坏花朵的数量. 例如有两种排序   (这里用(a,b)表示 ...

  3. JAVA-基础(一)

    1.一个变量可以声明为final,这样做的目的是阻止它的内容被修改.这意味着在声明final 变量的时候,你必须初始化它(在这种用法上,final类似于C/C++中的const). 例如: final ...

  4. bzoj3039 joyoi1939 玉蟾宫 悬线法

    悬线法 #include <iostream> #include <cstring> #include <cstdio> using namespace std; ...

  5. Leetcode21--->Merge Two Sorted Lists(合并两个排序的单链表)

    题目: 给出两个排序的单链表,合并两个单链表,返回合并后的结果: 解题思路: 解法还是很简单的,但是需要注意以下几点: 1.  如果两个链表都空,则返回null; 2.  如果链表1空,则返回链表2的 ...

  6. 小甲鱼零基础入门PYTHON

     000.愉快的开始 00:17:37 ☆  001.我和Python的第一次亲密接触 00:13:26 ★  002.用Python设计第一个游戏 00:24:00 ★  003.小插曲之变量和字符 ...

  7. seleniumIDE使用

    1.selenium IDE使用:适用于火狐浏览器 2.界面按钮包括录制(右上角的红点),运行脚本(中上页的绿色三角,包括依次运行和单个运行的2个运行按钮) 3.导出文件为.java,在文件选项中

  8. Leetcode 462.最少移动次数使数组元素相等

    最少移动次数使数组元素相等 给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数,其中每次移动可将选定的一个元素加1或减1. 您可以假设数组的长度最多为10000. 例如: 输入: [1,2, ...

  9. Goal Oriented Action Planning for a Smarter AI

    Goal Oriented Action Planning for a Smarter AI by Brent Owens23 Apr 2014 Goal Oriented Action Planni ...

  10. Git的使用小结

    1. git是一种分布式版本控制工具.目前项目中比较常见的版本控制器有SVN.CVS等,这些版本控制工具属于集中式版本控制器.集中式版本控制器,有一个中央服务器,开发人员的开发机从主服务器上下载了项目 ...