经典的lstm(Embedding)的例子

 

 

from torch.autograd import Variable as V
import torch as t
from torch import nn

n, d, m = 3, 5, 7
embedding = nn.Embedding(n, d, max_norm=True)
W = t.randn((m, d), requires_grad=True)
idx = t.tensor([1, 2])
a = embedding.weight.clone() @ W.t()  # weight must be cloned for this to be differentiable
b = embedding(idx) @ W.t()  # modifies weight in-place
out = (a.unsqueeze(0) + b.unsqueeze(1))
print(a.unsqueeze(0).shape, b.unsqueeze(1).shape)
# with t.no_grad():
print(a.unsqueeze(0), "\n", b.unsqueeze(1), "\n", (a.unsqueeze(0) + b.unsqueeze(1)).shape)
print( (a.unsqueeze(0) + b.unsqueeze(1)))
loss = out.sigmoid().prod()
loss.backward()
/home/wangbin/anaconda3/envs/deep_learning/bin/python3.7 /home/wangbin/anaconda3/envs/deep_learning/project/main.py
torch.Size([1, 3, 7]) torch.Size([2, 1, 7])
tensor([[[ 1.0560, -0.3363,  1.9043, -0.8517,  0.0666, -0.1867, -0.1422],
         [-1.0370, -0.8827,  0.1464, -0.4847, -0.0349, -0.2626,  0.5775],
         [ 0.8159, -4.3308,  4.8820, -0.4751, -0.0614, -2.5736, -0.6585]]],
       grad_fn=<UnsqueezeBackward0>) 
 tensor([[[-1.0370, -0.8827,  0.1464, -0.4847, -0.0349, -0.2626,  0.5775]],

        [[ 0.3994, -2.1200,  2.3899, -0.2326, -0.0301, -1.2598, -0.3223]]],
       grad_fn=<UnsqueezeBackward0>) 
 torch.Size([2, 3, 7])
tensor([[[ 0.0191, -1.2190,  2.0508, -1.3364,  0.0317, -0.4493,  0.4352],
         [-2.0739, -1.7654,  0.2929, -0.9693, -0.0699, -0.5253,  1.1550],
         [-0.2211, -5.2135,  5.0285, -0.9598, -0.0963, -2.8362, -0.0810]],

        [[ 1.4554, -2.4563,  4.2942, -1.0843,  0.0366, -1.4465, -0.4646],
         [-0.6376, -3.0027,  2.5363, -0.7172, -0.0650, -1.5225,  0.2551],
         [ 1.2152, -6.4508,  7.2719, -0.7077, -0.0915, -3.8334, -0.9808]]],
       grad_fn=<AddBackward0>)

Process finished with exit code 0

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
当使用LSTM时,您需要先定义一个LSTM模型,然后将其编译并拟合到您的数据上。下面是一个简单的LSTM模型的例子,用于对IMDB数据集中的电影评论进行情感分析: ```python from keras.datasets import imdb from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Embedding from keras.layers import LSTM max_features = 20000 # 词汇表大小 maxlen = 80 # 句子的最大长度 batch_size = 32 # 载入IMDB数据集 (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features) # 将序列填充或截断为固定长度 x_train = sequence.pad_sequences(x_train, maxlen=maxlen) x_test = sequence.pad_sequences(x_test, maxlen=maxlen) # 定义LSTM模型 model = Sequential() model.add(Embedding(max_features, 128)) model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2)) model.add(Dense(1, activation='sigmoid')) # 编译模型 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, batch_size=batch_size, epochs=5, validation_data=(x_test, y_test)) ``` 在上面的例子中,我们首先从Keras中导入IMDB数据集,并定义了一些模型的超参数。然后,我们对训练集和测试集进行了序列填充,以使它们具有相同的长度。接下来,我们定义了一个简单的LSTM模型,它包含一个嵌入层,一个LSTM层和一个全连接层。我们使用二元交叉熵作为损失函数,使用Adam优化器进行模型编译,并在训练中使用了一些回调函数(例如,早期停止)。最后,我们使用训练数据拟合模型,并在测试数据上进行评估。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序猿的探索之路

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

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

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

打赏作者

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

抵扣说明:

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

余额充值