Hi! When I first met this same problem,I fixed it accordding to the below reply. But When I run the program , after it finishe one epoch, the same error appear again and I don’t know the cause, and what I should to do. I askes you, please.the program is below:
from future import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import numpy as np
device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)
def loadtraindata():
“”“加载数据”""
path = r"D:/MNIST_test/train"
trainset = torchvision.datasets.ImageFolder(path,
transform=transforms.Compose([transforms.Resize((32, 32)),  # 将图片缩放到指定大小
transforms.CenterCrop(32),  # 随机裁剪
transforms.ToTensor(),  # 数据类型的转换
transforms.Normalize((0.1307,), (0.3081,))
]))
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
shuffle=True, num_workers=0)
return trainloader
class Net(nn.Module):
“”“搭建网络”""
def init(self):
super(Net, self).init()
# self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
# self.fc1 = nn.Linear(320, 50)
self.fc1 = nn.Linear(500, 32)
# self.fc2 = nn.Linear(50, 10)
self.fc2 = nn.Linear(32, 10)
    # Spatial transformer localization-network
    self.localization = nn.Sequential(
        # nn.Conv2d(1, 8, kernel_size=7),
        nn.Conv2d(3, 8, kernel_size=7),
        nn.MaxPool2d(2, stride=2),
        nn.ReLU(True),
        nn.Conv2d(8, 10, kernel_size=5),
        nn.MaxPool2d(2, stride=2),
        nn.ReLU(True)
    )

    # Regressor for the 3 * 2 affine matrix
    self.fc_loc = nn.Sequential(
        # nn.Linear(10 * 3 * 3, 32),
        nn.Linear(10 * 4 * 4, 32),
        nn.ReLU(True),
        nn.Linear(32, 3 * 2)
    )

    # Initialize the weights/bias with identity transformation
    self.fc_loc[2].weight.data.zero_()
    self.fc_loc[2].bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float))

# Spatial transformer network forward function
def stn(self, x):
    xs = self.localization(x)
    # print(xs.size(0))  # 4
    # xs = xs.view(-1, 10* 3* 3)
    xs = xs.view(xs.size(0), 10 * 4 * 4)  # 64*3*3*10-> 64*90
    theta = self.fc_loc(xs)  # 64*6
    theta = theta.view(-1, 2, 3)  # reshape 64*2*3 Transform matrix

    grid = F.affine_grid(theta, x.size())
    x = F.grid_sample(x, grid)

    return x

def forward(self, x):
    # transform the input
    x = self.stn(x)

    # Perform the usual forward pass
    x = F.relu(F.max_pool2d(self.conv1(x), 2))
    x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
    # print(x.size(0))  # 4
    x = x.view(4, 500)
    print("OK")
    x = F.relu(self.fc1(x))
    print(1)
    x = F.dropout(x, training=self.training)
    print(2)
    x = self.fc2(x)
    print(3)
    return F.log_softmax(x, dim=1)

model = Net().to(device)
print(4)
classes = (‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’)
def train(epoch):
“”“训练模型”""
optimizer = optim.SGD(model.parameters(), lr=0.01)
train_loader = loadtraindata()
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
    optimizer.zero_grad()
    output = model(data)
    loss = F.nll_loss(output, target)
    loss.backward()
    optimizer.step()
    if batch_idx % 500 == 0:
        print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
            epoch, batch_idx * len(data), len(train_loader.dataset),
            100. * batch_idx / len(train_loader), loss.item()))

print('Finished Training')
torch.save(model, 'model.pkl')  # 保存整个神经网络的结构和模型参数
torch.save(model.state_dict(), 'net_params.pkl')  # 只保存神经网络的模型参数

for epoch in range(1, 14):
train(epoch