states = [] # 正式训练 for epoch in range(10): train_loss = 0 model.train() # 将模型改为训练模式 for batch_x, batch_y in train_loader: batch_x = batch_x.to(device) batch_y = batch_y.to(device) state = model(batch_x) states.append(state) # 将state收集放到列表states中 loss = criterion(state, batch_y) optimizer.zero_grad() loss.backward() optimizer.step() print(states[epoch].shape) # torch.Size([16, 4]) print(len[states])
结果报错:TypeError: 'builtin_function_or_method' object is not subscriptable
错误原因:这个错误可能是因为你尝试对len()
函数使用了下标操作,但是len()
函数不支持下标操作。
简单来说:打印列表states长度的时候,用错括弧了,[ ]是下标操作,应该改为( )
处理方法:把 print(len[states]) 换成 print(len(states))