我正在使用household_power_consumption.txt数据集解决一个多变量时间序列预测问题,并实现了一个1D CNN模型。数据加载的批量大小为64,序列长度为50,有7个特征。预处理完成。下面提供了模型代码。请帮助我解决模型维度不匹配的问题。
class CNN_ForecastNet(nn.Module):
def __init__(self):
super(CNN_ForecastNet,self).__init__()
self.conv1d = nn.Conv1d(50,200,kernel_size=1)
self.relu = nn.ReLU(inplace=True)
self.drop_out = nn.Dropout(0.5)
self.max_pooling = nn.MaxPool1d(1)
self.fc1 = nn.Linear(200,100)
self.fc2 = nn.Linear(100,1)
def forward(self,x):
x = self.conv1d(x)
x = self.relu(x)
x = self.drop_out(x)
x = self.max_pooling(x)
x = x.view(x.size(0),-1)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
model = CNN_ForecastNet()
train_losses = []
valid_losses = []
def Train():
running_loss = .0
model.train()
for idx, (inputs,labels) in enumerate(train_loader):
optimizer.zero_grad()
preds = model(inputs.float())
loss = criterion(preds,labels)
loss.backward()
optimizer.step()
running_loss += loss
train_loss = running_loss/len(train_loader)
train_losses.append(train_loss.detach().numpy())
print(f'train_loss {train_loss}')
def Valid():
running_loss = .0
model.eval()
with torch.no_grad():
for idx, (inputs, labels) in enumerate(test_loader):
optimizer.zero_grad()
preds = model(inputs.float())
loss = criterion(preds,labels)
running_loss += loss
valid_loss = running_loss/len(test_loader)
valid_losses.append(valid_loss.detach().numpy())
print(f'valid_loss {valid_loss}')
epochs = 10
for epoch in range(epochs):
if epoch % 2==0:
print('epochs {}/{}'.format(epoch+1,epochs))
Train()
Valid()
gc.collect()
字符串
错误如下所示
Traceback (most recent call last):
Cell In[15], line 73
Train()
Cell In[15], line 41 in Train
preds = model(inputs.float())
File ~\anaconda3\Lib\site-packages\torch\nn\modules\module.py:1501 in _call_impl
return forward_call(*args, **kwargs)
Cell In[15], line 17 in forward
x = self.fc1(x)
File ~\anaconda3\Lib\site-packages\torch\nn\modules\module.py:1501 in _call_impl
return forward_call(*args, **kwargs)
File ~\anaconda3\Lib\site-packages\torch\nn\modules\linear.py:114 in forward
return F.linear(input, self.weight, self.bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x1400 and 200x100)
型
1条答案
按热度按时间2lpgd9681#
看起来RuntimeError是由于尺寸不匹配造成的。要解决此错误,您必须将
self.fc1
中的输入特征(in_features)更改为1400。希望它能解决你的问题。谢谢!