python-pytorch 利用word2vec实现lstm模型预测中文文本输出0.1.00
- 前言
- 源数据
- 导入包
- 加载数据分析后写入新文件
- word2vec训练词向量
- 保存word2vec训练词模型
- 保存word2vec词向量
- 加载保存word2vec的模型
- 将分词好的句子依次导入数组中
- 获取word2index、word2index
- 获取word2index、index2ve
- 查看词分布情况
- 词表大小
- 生成训练数据
- 设置超参数和实例化模型
- 训练模型
- 预测
前言
使用pretrained word embeddings word2vec 替代nn.Embedding,过程还存在问题,最明显的是预测会不停循环一句话
- 要使用替代word2vec,核心代码两步
sentences = LineSentence(dataset_path)
model = word2vec.Word2Vec(sentences, sg=1, window=5, min_count=1, workers=4,epochs=2000)
- 要使用到LineSentence函数,文本格式有要求
一是,需要文本内容是使用空格分好,内容如:ZooKeeper 定义 的 存储 目录 不 正确 或 ZooKeeper 的 存储 规划 变化 时
二是,一行一个句子
源数据
一篇新闻:https://news.sina.com.cn/c/2024-04-12/doc-inarqiev0222543.shtml
导入包
import logging
import sys
import gensim.models as word2vec
from gensim.models.word2vec import LineSentence, logger
import jiebaimport torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as Data
from torch.autograd import Variable
加载数据分析后写入新文件
要把源文件一行一行的,使用jieba分词后用空格分开,才能使用word2vec的LineSentence
with open("./howtousercbow/data/news.txt","r",encoding="utf-8") as f:lines=f.readlines()for line in lines:jiebacutresult=list(jieba.cut(line.replace(",","").replace("。","").replace("\n","").replace(",","").replace("、","").replace("?","").replace(":",""),False))sttr=""for jb in jiebac