neural-network - 如何使用神经网络减少张量的维数
问题描述
我有一个大小为 [100,70,42](batch, seq_len, features)的 3D 张量,我想通过使用基于线性变换的神经网络(nn. Pytorch 中的线性)。
我已经实现了以下代码
class Network(nn.Module):
def __init__(self):
super(Network, self).__init__()
self.fc1 = nn.Linear(42, 120)
self.fc2 = nn.Linear(120,1)
def forward(self, input):
model = nn.Sequential(self.fc1,
nn.ReLU(),
self.fc2)
output = model(input)
return output
然而,在训练时,这只会给我一个形状 [100,70,1] 的输出,这不是我们想要的。
谢谢!
解决方案
nn.Linear
仅作用于最后一个轴。如果要在最后两个维度上应用线性,则必须重塑输入张量:
class Network(nn.Module):
def __init__(self):
super(Network, self).__init__()
self.fc1 = nn.Linear(70 * 42, 120) # notice input shape
self.fc2 = nn.Linear(120,1)
def forward(self, input):
input = input.reshape((-1, 70 * 42)) # added reshape
model = nn.Sequential(self.fc1,
nn.ReLU(),
self.fc2)
output = model(input)
output = output.reshape((-1, 1, 1)) # OP asked for 3-dim output
return output
推荐阅读
- python - 套接字错误:111 [.connect((host, port))]
- json - HttpMessageNotReadableException:JSON 解析错误
- spring - 可以使用弹簧数据弹性搜索的可扩展弹性搜索模块吗?
- r - 总结——它依赖于顺序吗?
- python - 如何在将键值与列名匹配的同时将字典添加到数据框中?
- mysql - 使用SQL合并两个表以更改单行中的列数据
- postgresql - 通过查询优化的 SQL 分区
- python - 如何使用python拟合多条指数曲线
- r - 在 R 中将日期 2008-10-26 02:00:00 转换为 POSIXct 时出现问题
- javascript - React Native FlatList 不在 flexbox UI 中滚动