问题遇到的现象和发生背景
基于pytorch 建立一个lstm的五分类模型
可是报错,初学者查了半天不知道怎么改
问题相关代码,请勿粘贴截图
def get_train_data():
x_data = data_SD_Loc_2D[:,0:300].astype(float) # X_data SD
y_data = data_SD_Loc_2D[:,[-1]].astype(float) # Y_data Loc
def get_tensor_from_np(data_SD_Loc_2D) -> torch.Tensor:
return torch.tensor(data_SD_Loc_2D)
# 生成训练数据x并做归一化后,再转换为tensor格式
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(data_SD_Loc_2D[:, 0:300]) #降维归一化
return get_tensor_from_np(data_normalized).float()
class LSTM(nn.Module):
def __init__(self, input_size=300, hidden_layer_size=100, output_size=5):
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=30, # 每块的大小
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)