一开始我只print那个名为loss_axis的list结果发现它先print出来许多空[](我对loss_axis的定义就是空list),最后才print出来了完整的loss_axis。为什么会这样
附上完整的代码
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
filepath = 'c:\\Users\\dell\\Desktop\\code\\diabetes.csv'
epoch_len = 5
count = 0
loss_axis = []
class DiabetesDataset(Dataset):
def __init__(self, filepath):
xy = np.loadtxt(filepath, delimiter = ',', dtype = np.float32)
self.len = xy.shape[0]
self.x_data = torch.from_numpy(xy[:, :-1])
self.y_data = torch.from_numpy(xy[:, [-1]])
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
def __len__(self):
return self.len
dataset = DiabetesDataset('diabetes.csv')
train_loader = DataLoader(dataset = dataset, batch_size = 32, shuffle = True, num_workers = 2)
class Model(torch.nn.Module):
def __init__(self):
super(Model ,self).__init__()
self.linear1 = torch.nn.Linear(8, 6)
self.linear2 = torch.nn.Linear(6, 4)
self.linear3 = torch.nn.Linear(4, 1)
self.sigmoid = torch.nn.Sigmoid()
def forward(self, x):
x = self.sigmoid(self.linear1(x))
x = self.sigmoid(self.linear2(x))
x = self.sigmoid(self.linear3(x))
return x
model = Model()
criterion = torch.nn.BCELoss(reduction = 'mean')
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)
if __name__ == '__main__':
for epoch in range(epoch_len):
for i, data in enumerate(train_loader, 0):
count = count + 1
#prepare data
inputs, labels = data
#forward
y_pred = model(inputs)
loss = criterion(y_pred, labels)
loss_axis.append(loss.item())
#print(epoch, i, loss.item())
#backward
optimizer.zero_grad()
loss.backward()
#update
optimizer.step()
print(loss_axis)
print("1")
# epoch_axis = np.linspace(1, epoch_len, count)
# plt.figure(num = 'loss', figsize = (8, 5))
# plt.plot(epoch_axis, loss_axis, color = 'red')
# plt.xlim((0, epoch_len))
# # plt.ylim((0, loss_axis[0]))
# plt.xlabel('epoch')
# plt.ylabel('loss')
# plt.grid()
# plt.show()