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. LeetCode(238) Product of Array Except Self

    题目 Given an array of n integers where n > 1, nums, return an array output such that output[i] is ...

  2. MediaStore类的使用

    安卓系统会在每次开机之后扫描所有文件并分类整理存入数据库,记录在MediaStore这个类里,通过这个类就可以快速的获得相应类型的文件. 当然这个类只是给你一个uri,提取文件的操作还是要通过Curo ...

  3. flask_关注者

    表的模型实现 class Follow(db.Model): __tablename__ = 'follows' follower_id = db.Column(db.Integer,db.Forei ...

  4. POJ 2763 树链剖分 线段树 Housewife Wind

    单个边的权值修改以及询问路径上的权值之和. 数据量比较大,用vector存图会超时的. #include <iostream> #include <cstdio> #inclu ...

  5. (转)全网最!详!细!tarjan算法讲解

    byhttp://www.cnblogs.com/uncle-lu/p/5876729.html 全网最详细tarjan算法讲解,我不敢说别的.反正其他tarjan算法讲解,我看了半天才看懂.我写的这 ...

  6. python 学习分享-文件操作篇

    文件操作 f_open=open('*.txt','r')#以只读的方式(r)打开*.txt文件(需要与py文件在同一目录下,如果不同目录,需写全路径) f_open.close()#关闭文件 打开文 ...

  7. HDU——2087剪花布条

    剪花布条 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submi ...

  8. JSON树节点的增删查改

    最近了解到使用json字符串存到数据库的一种存储方式,取出来的json字符串可以进行相应的节点操作 故借此机会练习下递归,完成对json节点操作对应的工具类. 介绍一下我使用的依赖 复制代码 < ...

  9. 归并排序,时间复杂度nlogn

    思路: /*   考点:   1. 快慢指针:2. 归并排序.   此题经典,需要消化吸收.   复杂度分析:              T(n)            拆分 n/2, 归并 n/2 ...

  10. java面试题之如何实现处理线程的返回值?

    有三种实现方式: 主线程等待法: 使用Thread类的join方法阻塞当前线程以等待子线程处理完毕: 通过Callable接口实现,通过FutureTask 或者线程池: