赞
踩
写在前面:
pycharm内存问题没有解决,以下代码均在jupyter notebook实现
像batch_size, 数据条数,循环次数, print_every一类的参数,可以修改尝试,为了解决memoryerror一类的问题,修改过多次。
- 解压bz2压缩文件
import bz2 train_file = bz2.BZ2File('data/train.ft.txt.bz2') test_file = bz2.BZ2File('data/test.ft.txt.bz2')
- 文件中二进制存储,由输出中 b''看出
b'__label__2 Stuning even for the non-gamer: This sound track was beautiful! It paints the senery in your mind so well I would recomend it even to people who hate vid. game music! I have played the game Chrono Cross but out of all of the games I have ever played it has the best music! It backs away from crude keyboarding and takes a fresher step with grate guitars and soulful orchestras. It would impress anyone who cares to listen! ^_^\n'
- decode成'utf-8'
train_file = [x.decode('utf-8') for x in train_file[:train_num]] test_file = [x.decode('utf-8') for x in test_file[:test_num]]
由尝试输出的train_file中看出,数据集的标签和数据是在一起的,label_1为态度差,设为1, label_2 为态度好,设为2
for i, sen in enumerate(train_data)
解释 i
- #分词
- words = Counter()
- for i, sen in enumerate(train_data):
- # print(i)
- words_ = nltk.word_tokenize(sen)
- words.update(words_)#更新词频列表
当调用 `Counter` 对象的 `update` 方法时,它会接受一个可迭代对象作为参数,然后将这个可迭代对象中的元素作为键,以及对应元素出现的次数作为值,更新到 `Counter` 对象中。
在上面的代码中,传递给 `update` 方法的参数 `words_` 是一个单词列表,遍历该列表,将每个单词添加到 `Counter` 对象 `words` 中,并且每次出现一个单词,对应的计数值会增加1。
_PAD:表示填充,因为后续会固定所有句子长度。过长的句子进行阶段,过短的句子使用该单词进行填充
re.sub 正则表达式:
([^ ]
:这是一个字符集合,匹配除了空格以外的任意字符。?<=\.[a-z]{3}))
:这是一个正向断言,表示匹配前面的模式之后满足括号内条件的内容。具体来说:(?<=
:开启一个正向断言。\. :
匹配一个点号。[a-z]{3}
:匹配三个连续的小写字母。)
:结束正向断言。
为了方便构建模型,需要固定所有句子的长度,自定义句子的固定长度,对于长度不够的句子,在前面填充0
(_PAD
),超出长度的句子进行从后面截断
- import nltk
- from collections import Counter
- import numpy as np
- import bz2
-
- #处理数据
- train_file = bz2.BZ2File('data/train.ft.txt.bz2')
- test_file = bz2.BZ2File('data/test.ft.txt.bz2')
- train_file = train_file.readlines()
- test_file = test_file.readlines()
- print(train_file[0])
-
- #8:2划分数据集
- train_num = 8000
- test_num = 2000
-
- train_file = [x.decode('utf-8') for x in train_file[:train_num]]
- test_file = [x.decode('utf-8') for x in test_file[:test_num]]
-
- # print(train_file[0])
- #差 0 好 1
- #去掉 \n [:-1]
- train_labels = [0 if x.split(' ')[0] == '__label__1' else 1 for x in train_file]
- train_data = [x.split(' ', 1)[1][: -1].lower() for x in train_file]
-
- test_labels = [0 if x.split(' ')[0] == '__label__1' else 1 for x in test_file]
- test_data = [x.split(' ', 1)[1][: -1].lower() for x in test_file]
-
- #sub 正则表达式
- for i in range(len(train_data)):
- train_data[i] = re.sub('\d','0',train_data[i])
-
- for i in range(len(test_data)):
- test_data[i] = re.sub('\d','0',test_data[i])
-
- for i in range(len(train_data)):
- if 'www.' in train_data[i] or 'http:' in train_data[i] or 'https:' in train_data[i] or '.com' in train_data[i]:
- train_data[i] = re.sub(r"([^ ]+(?<=\.[a-z]{3}))", "<url>", train_data[i])
-
- for i in range(len(test_data)):
- if 'www.' in test_data[i] or 'http:' in test_data[i] or 'https:' in test_data[i] or '.com' in test_data[i]:
- test_data[i] = re.sub(r"([^ ]+(?<=\.[a-z]{3}))", "<url>", test_data[i])
-
- #! 映射词典
- #分词
- words = Counter()
- for i, sen in enumerate(train_data):
- # print(i)
- words_ = nltk.word_tokenize(sen)
- words.update(words_)#更新词频列表
- train_data[i] = words_
-
- print("100% done")
-
- # words 从大到小排列顺序
- words = sorted(words, key=words.get, reverse=True)
- words = ['_PAD'] + words
-
- #对单词进行编码,将单词映射为数字,(单词所对应索引下标)
- word2idx = {x: i for i, x in enumerate(words)}
- idx2word = {i: o for i, o in enumerate(words)}
-
- #将train_data, test_data中的单词转为数字
- for i, sen in enumerate(train_data):
- train_data[i] = [word2idx[word] if word in word2idx else 0 for word in sen]
- for i, sen in enumerate(test_data):
- test_data[i] = [word2idx[word.lower()] if word.lower() in word2idx else 0 for word in nltk.word_tokenize(sen)]
-
- #固定长度
- def pad_input(sentences, seq_len):
- features = np.zeros((len(sentences), seq_len),dtype=int)
- for ii, review in enumerate(sentences):
- if len(review) != 0:
- features[ii, -len(review):] = np.array(review)[:seq_len]
- return features
-
- # 固定测试数据集和训练数据集的句子长度
- train_data = pad_input(train_data, 200)
- test_data = pad_input(test_data, 200)
-
- train_labels = np.array(train_labels)
- test_labels = np.array(test_labels)
重头戏
from torch.utils.data import TensorDataset, DataLoader
这段代码导入了PyTorch库中的`TensorDataset`和`DataLoader`模块。这两个模块提供了对数据集的封装和加载,用于在训练和测试神经网络模型时方便地处理数据。
- x_data = TensorDataset(torch.from_numpy(train_data), torch.from_numpy(train_labels))
- y_data = TensorDataset(torch.from_numpy(test_data), torch.from_numpy(test_labels))
通过torch.from_numpy将他们转换成pytorch张量,train_data是用于训练的特征张良,train_labels 是相应的标签向量。
- train_loader = DataLoader(x_data, shuffle=True, batch_size=batch_size)
- test_loader = DataLoader(y_data, shuffle=True, batch_size=batch_size)
`shuffle=True`表示在每个epoch开始时,数据加载器会对数据进行洗牌,以增加模型的泛化能力。`batch_size`参数指定了每个批次中的样本数量。通过调整`batch_size`的大小,可以在训练时有效利用显存,提高模型训练的速度。
`DataLoader`对象可以迭代地返回每个批次的数据。
device = torch.device('cuda') if torch.cuda.is_available() else torch.device("cpu")
- class SensationNet(nn.Module):
- def __init__(self, vocab_size):
- super(SensationNet, self).__init__()
- embedding_dim = embedding_dim = 200 #词向量维度
- self.hidden_dim=hidden_dim = 128 #隐藏层神经元 LSTM输出的隐状态
- self.num_layers = num_layers = 2 #隐藏层层数
- dropout_keep_prob = 0.8 #dropout保存比例
-
- #定义embedding,数字 词向量,将单词索引转化成对应的词向量
- self.embedding = nn.Embedding(vocab_size, embedding_dim)
-
- #lstm 层
- self.lstm = nn.LSTM(embedding_dim,
- hidden_dim,
- num_layers,
- dropout=dropout_keep_prob,
- batch_first=True)
-
- #全连接层
- self.fc = nn.Linear(in_features=hidden_dim, out_features=1)
-
- #激活函数 sigmoid
- self.sigmoid = nn.Sigmoid()
- self.dropout = nn.Dropout(dropout_keep_prob)
-
- #前向传播函数
- def forward(self, x, hidden):
- batch_size = x.size(0)
-
- x = x.long()
- #(, , hidden_dim)
- embeds = self.embedding(x)#编码后的词向量
- # hidden 上一时刻隐状态
- lstm_out, hidden = self.lstm(embeds, hidden)
- #hidden 包含隐状态、细胞状态,两者维度都是(num_layers, batch_size, hidden_dim)
- #lstm_out(batch_size, 词长度, hidden_dim)
-
- #为了进入全连接层,三层张量->二层
- lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)
- out = self.dropout(lstm_out)
- out = self.fc(out)
- out =self.sigmoid(out)#一维
- #一维张量->二维张量,即每个单词都对应一个输出
- out = out.view(batch_size, -1)
- #只关注最后一个时间步的输出即最后一个单词的输出
- out = out[:, -1]
-
- return out, hidden
- """
- 初始化隐状态,第一次送入LSTM没有隐状态,所以要初始化,一般全部赋值为0,
- 这里之所以是tuple,是因为LSTM需要接受两个隐状态hidden state和cell state
- """
- def init_hidden(self, batch_size):
- hidden = (torch.zeros(self.num_layers, batch_size, self.hidden_dim).to(device),
- torch.zeros(self.num_layers, batch_size, self.hidden_dim).to(device)
- )
- return hidden
删除单维度条目
- #评估
- test_losses = []
- num_correct = 0#正确预测数量
- h_f = model.init_hidden(batch_size)#初始化
- model.eval()
-
- for inputs, labels in test_loader:
- h_f = tuple([e.data for e in h_f])
- inputs, labels = inputs.to(device), labels.to(device)
- output, h_f = model(inputs, h_f)
- # print(output)
-
- #为什么要加squeeze(), 上面那个没加
- test_loss = criterion(output.squeeze(), labels.float())
- test_losses.append(test_loss.item())
- pred = torch.round(output.squeeze())
- correct_tensor = pred.eq(labels.float().view_as(pred))
- correct = np.squeeze(correct_tensor.cpu().numpy())
- num_correct += np.sum(correct)
-
- print("Test loss: {:.3f}".format(np.mean(test_losses)))
- test_acc = num_correct/len(test_loader.dataset)
- print("Test accuracy: {:.3f}%".format(test_acc*100))
chatgpt:是的,LSTM模型通常包含一个或多个隐藏层。隐藏层可以帮助模型捕捉输入序列中的时间相关性,并存储和传递状态信息。每个隐藏层中都有许多LSTM单元(也称为LSTM块或LSTM单元),并且每个单元都具有自己的隐藏状态和记忆状态。
chatgpt:大多数神经网络模型通常将批处理维度放在第一个维度上。将LSTM的输入与其他模型保持一致,可以更容易地与其他模型进行结合。可以直接使用这些数据处理库,无需进行额外的维度转换。
chatgpt:因为GPU主要用于加速大规模的并行计算。在深度学习中,模型的训练和预测通常都是在CPU上进行的,因为CPU的单核性能比较高,适合处理复杂的逻辑和大量的数学运算。
有些问题还待更新,欢迎评论区解答
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/653154
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。