pytorch构建LSTM处理二分类任务

构造训练数据

def get_train_data():
    """得到训练数据,这里使用随机数生成训练数据,由此导致最终结果并不好"""

    def get_tensor_from_pd(dataframe_series) -> torch.Tensor:
        return torch.tensor(data=dataframe_series.values)

    import numpy as np
    import pandas as pd
    from sklearn import preprocessing
    # 生成训练数据x并做标准化后,构造成dataframe格式,再转换为tensor格式
    df = pd.DataFrame(data=preprocessing.StandardScaler().fit_transform(np.random.randint(0, 10, size=(200, 5))))
    y = pd.Series(np.random.randint(0, 2, 200))
    return get_tensor_from_pd(df).float(), get_tensor_from_pd(y).float()

构造LSTM模型

class LSTM(nn.Module):
    def __init__(self, input_size=5, hidden_layer_size=100, output_size=1):
        """
        LSTM二分类任务
        :param input_size: 输入数据的维度
        :param hidden_layer_size:隐层的数目
        :param output_size: 输出的个数
        """
        super().__init__()
        self.hidden_layer_size = hidden_layer_size
        self.lstm = nn.LSTM(input_size, hidden_layer_size)
        self.linear = nn.Linear(hidden_layer_size, output_size)
        self.sigmoid = nn.Sigmoid()

    def forward(self, input_x):
        input_x = input_x.view(len(input_x), 1, -1)
        hidden_cell = (torch.zeros(1, 1, self.hidden_layer_size),  # shape: (n_layers, batch, hidden_size)
                       torch.zeros(1, 1, self.hidden_layer_size))
        lstm_out, (h_n, h_c) = self.lstm(input_x, hidden_cell)
        linear_out = self.linear(lstm_out.view(len(input_x), -1))  # =self.linear(lstm_out[:, -1, :])
        predictions = self.sigmoid(linear_out)
        return predictions

全部代码

import torch
import torch.nn as nn
import torch.utils.data as Data


def get_train_data():
    """得到训练数据,这里使用随机数生成训练数据,由此导致最终结果并不好"""

    def get_tensor_from_pd(dataframe_series) -> torch.Tensor:
        return torch.tensor(data=dataframe_series.values)

    import numpy as np
    import pandas as pd
    from sklearn import preprocessing
    # 生成训练数据x并做标准化后,构造成dataframe格式,再转换为tensor格式
    df = pd.DataFrame(data=preprocessing.StandardScaler().fit_transform(np.random.randint(0, 10, size=(200, 5))))
    y = pd.Series(np.random.randint(0, 2, 200))
    return get_tensor_from_pd(df).float(), get_tensor_from_pd(y).float()


class LSTM(nn.Module):
    def __init__(self, input_size=5, hidden_layer_size=100, output_size=1):
        """
        LSTM二分类任务
        :param input_size: 输入数据的维度
        :param hidden_layer_size:隐层的数目
        :param output_size: 输出的个数
        """
        super().__init__()
        self.hidden_layer_size = hidden_layer_size
        self.lstm = nn.LSTM(input_size, hidden_layer_size)
        self.linear = nn.Linear(hidden_layer_size, output_size)
        self.sigmoid = nn.Sigmoid()

    def forward(self, input_x):
        input_x = input_x.view(len(input_x), 1, -1)
        hidden_cell = (torch.zeros(1, 1, self.hidden_layer_size),  # shape: (n_layers, batch, hidden_size)
                       torch.zeros(1, 1, self.hidden_layer_size))
        lstm_out, (h_n, h_c) = self.lstm(input_x, hidden_cell)
        linear_out = self.linear(lstm_out.view(len(input_x), -1))  # =self.linear(lstm_out[:, -1, :])
        predictions = self.sigmoid(linear_out)
        return predictions


if __name__ == '__main__':
    # 得到数据
    x, y = get_train_data()
    train_loader = Data.DataLoader(
        dataset=Data.TensorDataset(x, y),  # 封装进Data.TensorDataset()类的数据,可以为任意维度
        batch_size=20,  # 每块的大小
        shuffle=True,  # 要不要打乱数据 (打乱比较好)
        num_workers=2,  # 多进程(multiprocess)来读数据
    )
    # 建模三件套:loss,优化,epochs
    model = LSTM()  # 模型
    loss_function = nn.BCELoss()  # loss
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)  # 优化器
    epochs = 150
    # 开始训练
    model.train()
    for i in range(epochs):
        for seq, labels in train_loader:
            optimizer.zero_grad()
            y_pred = model(seq).squeeze()  # 压缩维度:得到输出,并将维度为1的去除
            single_loss = loss_function(y_pred, labels)
            # 若想要获得类别,二分类问题使用四舍五入的方法即可:print(torch.round(y_pred))
            single_loss.backward()
            optimizer.step()
            print("Train Step:", i, " loss: ", single_loss)
    # 开始验证
    model.eval()
    for i in range(epochs):
        for seq, labels in train_loader:  # 这里偷个懒,就用训练数据验证哈!
            y_pred = model(seq).squeeze()  # 压缩维度:得到输出,并将维度为1的去除
            single_loss = loss_function(y_pred, labels)
            print("EVAL Step:", i, " loss: ", single_loss)
  • 20
    点赞
  • 133
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 25
    评论
PyTorch多语句RNN(循环神经网络)二分类模型可以用来处理多语言文本分类任务。下面将简述基本流程。 首先,我们需要将文本数据进行预处理。预处理的步骤包括分词、去除停用词(如and、the等)、删除标点符号等。之后,我们将每个句子转换为一个数值向量,通常使用词嵌入技术,例如Word2Vec或者GloVe。这样,我们就可以用数值表示每个单词。 接着,我们需要构建RNN模型。一个常用的RNN模型是LSTM(长短期记忆网络)。LSTM可以捕捉句子中的时间序列信息,并更好地处理长期依赖问题。我们可以使用PyTorch提供的nn.LSTM模块来构建LSTM网络。 在构建模型时,我们需要定义网络的结构。通常,我们将词嵌入向量输入到LSTM中,并通过最后一个时间步的输出来进行分类。可以添加全连接层来将LSTM输出转换为二分类的结果。最后,我们使用sigmoid函数将输出映射到[0, 1]的范围内,以获取概率结果。 模型构建完成后,需要定义损失函数和优化器。对于二分类模型,我们可以使用二元交叉熵作为损失函数,优化器可以选择Adam或者SGD等。 在模型训练阶段,我们将数据分为训练集和验证集,并按照批量大小(batch size)将数据加载到模型中。通过向前传播和反向传播来计算损失和更新模型的参数。 在模型训练完毕后,可以对测试集进行预测,并评估模型的性能。可以计算准确率、精确率、召回率和F1值等指标来评估模型的效果。 总之,PyTorch提供了丰富的工具和模块,用于构建和训练多语句RNN二分类模型。通过适当的预处理、模型构建和训练,我们可以高效地处理多语言文本分类任务,从而取得良好的结果。
评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌的代Ma

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值