week4(2021.10.9~2021.10.15)

阅读: 评论:0

week4(2021.10.9~2021.10.15)

week4(2021.10.9~2021.10.15)

Step1 总结

Step2 接上周Step6的 (未完待续)

三.文本情感分类

        1.数据集的准备    2.模型构建   3.模型训练   4.模型评估

# 数据准备
import torch
from torch.utils.data import DataLoader, Dataset
import os
import redef tokenlize(content):content = re.sub("<.*?>", " ", content)fileters = [".", 't', 'n', 'x97', 'x96', '#', '$', '%', '&']content = re.sub("|".join(fileters), " ", content)tokens = [i.strip().lower() for i in content.split()]return tokensclass ImdbDataset(Dataset):def __init__(self, train=True):ain_data_path = r"D:1aaa_aaaclImdb_v1aclImdbtrain&#st_data_path = r"D:1aaa_aaaclImdb_v1aclImdbtest"data_path = ain_data_path if train st_data_path# 把所有的文件名放入列表# pos和neg是 train下面的文件夹,放到这个列表里temp_data_path = [os.path.join(data_path, "pos"), os.path.join(data_path, "neg")]al_file_path = []  # 所有的评论文件的路径for path in temp_data_path:file_name_list = os.listdir(path)file_path_list = [os.path.join(path, i) for i in file_name_list dswith(".txt")]al_d(file_path_list)def __getitem__(self, index):file_path = al_file_path[index]# 获取labellabel_str = file_path.split("\")[-2]label = 0 if label_str == "neg" else 1# 获取内容tokens = tokenlize(open(file_path).read())return tokens, labelprint(label_str)def __len__(self):return al_file_path)def get_dataloader(train=True):imdb_dataset = ImdbDataset(train)data_loader = DataLoader(imdb_dataset, batch_size=2, shuffle=True)return data_loaderif __name__ == '__main__':for idx, (input, target) in enumerate(get_dataloader()):print(idx)print(input)print(target)break

添加collate fn(加入collate_fn类,修改get_dataloader类)

def collate_fn(batch):content, label = list(zip(*batch))return content, labeldef get_dataloader(train=True):imdb_dataset = ImdbDataset(train)data_loader = DataLoader(imdb_dataset, batch_size=2, shuffle=True,
collate_fn=collate_fn)return data_loader

Step3 逻辑回归

import torch
import matplotlib.pyplot as plt
 as nn
from torch.optim import SGDimport os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'# 生成一批数据样本,并分为2类
cluster = s(500, 2)              # 生成 500行 2列 元素值为1 的张量
data0 = al(4 * cluster, 2)      # 设置data0为均值4,标准差2的正态分布(就是让500行2列的张量数据服从规定的正态分布)
data1 = al(-4 * cluster, 2)
label0 = s(500)                 # 500个0的数组(一维张量)
label1 = s(500)x = torch.cat((data0, data1), ).type(torch.FloatTensor)                    # data0和data1拼接在一起,竖着拼,同时维度增加。也可以写成torch.cat((A,B),0)   另一种:torch.cat((A,B),1)就是横着拼
y = torch.cat((label0, label1), ).type(torch.LongTensor)plt.scatter(x.numpy()[:, 0], x.numpy()[:, 1], c=y.numpy(), s=10, lw=0, cmap='RdYlGn')   # X[:,0]就是取所有行的第0个数据,  X[:,1]就是取所有行的第1个数据
plt.show()                                                                              #  c=y.numpy()是将y转化为数组(降维)# s代表每个点的粗细,lw是每个点所占面积的大小,cmap是颜色设置
# 定义神经网络Net
class Net(nn.Module):def __init__(self):super(Net, self).__init__()self.linear = nn.Linear(2, 2)  # 2,2表示输入二维张量大小,输出二维张量大小def forward(self, x):x = self.linear(x)x = torch.sigmoid(x)return xinputs = x
target = y# 优化器:随机梯度下降
net = Net()
optimizer = SGD(net.parameters(), 0.02)  # 学习率lr为0.02
criterion = nn.CrossEntropyLoss()  # 交叉熵函数def draw(output):output = torch.max((output), 1)[1]           #output = torch.max(input, dim), input是输入的tensor,dim(0/1)是每列/行的最大值,输出1.每行最大值并构成数组 2.输出索引(即第几列的数) [1]代表了2.输出索引pred_y = output.data.numpy().squeeze()       #可以删除数组形状中的单维度条目,即把shape中为1的维度去掉target_y = y.numpy()plt.scatter(x.numpy()[:, 0], x.numpy()[:, 1], c=y.numpy(), s=10, lw=0, cmap='RdYlGn')  #前边已经解释了accuracy = sum(pred_y == target_y) / 1000.0    #表示一个bool数组,如果预测类别和样本类别相同,该位置置1,否则置0   除以1000后,accuracy就表示精度了(1.5, -4, 'Accuracy=%s' % (accuracy), fontdict={'size': 20, 'color': 'red'})     #打印出精度值,设定参数plt.pause(0.1)                               #暂停0.1秒#训练模型
def train(model, criterion, optimizer, epochs):    #定义训练(神经网络,交叉熵函数,优化器模型,循环次数)for epoch in range(epochs):output = model(inputs)              #定义output,来自model(也就是run),inputs是x(前边有提到)loss = criterion(output, target)    #定义损失函数(交叉熵函数&#_grad()               #清零loss.backward()                     #反向传播optimizer.step()                    #前向传播if epoch % 40 == 0:draw(output)                    #运行draw类train(net, criterion, optimizer, 1000)

一.解释代码

二.运行结果

几个模糊的概念解析:

        1.深度学习中关于张量的阶、轴和形状的解释​​​​​​深度学习中关于张量的阶、轴和形状的解释 | Pytorch系列(二) - 云+社区 - 腾讯云 (tencent)

        2.nn.Linear()解释

PyTorch的nn.Linear()详解 - douzujun - 博客园 (cnblogs).

        3.numpy 数组X[:,0]和X[:,1]的详解

numpy 数组X[:,0]和X[:,1]的详解_doubledog1112的专栏-CSDN博客

        4.Pytorch中的torch.cat()函数

Pytorch中的torch.cat()函数_荷叶田田-CSDN博客_python torch.cat

        5.zeros()函数

zeros() 函数——MATLAB - 坤元居士 - 博客园 (cnblogs)

        al()的用法

        7.torch.optim 优化器

PyTorch 笔记(18)— torch.optim 优化器的使用_wohu1104的专栏-CSDN博客

        8.torch.max()使用

torch.max()使用讲解 - 简书 (jianshu)

本文发布于:2024-02-05 09:15:14,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170728568265223.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23