项目实训 No.17

项目实训 No.17

DNN算法

#导入包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import torch
import torch.nn as nn
from torch.autograd import Variable

import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from sklearn.metrics import confusion_matrix
import time
import io
import pickle
#有GPU,则使用GPU进行运算
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

cuda = True if torch.cuda.is_available() else False

learning_rate = 0.001
num_epochs = 2
batch_size = 100

use_lr_decay = 0
lr_decay = 40
decay_rate = 0.5


root_path = ''
loss_file_name = 'train_loss_epoch'+str(num_epochs)+'_lr'+str(learning_rate)+'_lrdecay'+str(lr_decay)+'b128'
test_loss_file_name = 'test_loss_epoch'+str(num_epochs)+'_lr'+str(learning_rate)+'_lrdecay'+str(lr_decay)+'b128'
#定义数据集类(输入CSV文件,基于fashionMInst代码,进行修改)
#class CifarDataset(Dataset):
#    """User defined class to build a datset using Pytorch class Dataset."""
#    #构造函数,输入数据,转换方式
#    def __init__(self, data, transform=None):
#        """Method to initilaize variables."""
#        self.Cifar = list(data.values)
#        self.transform = transform
#
#        label = []
#        image = []
#
#        for i in self.Cifar:
#            # first column is of labels.
#            label.append(i[0])
#            image.append(i[1:])
#        self.labels = np.asarray(label)
#        # Dimension of Images = 32 * 32 * 3. where height = width = 32 and color_channels = 3.
#        self.images = np.asarray(image).reshape(-1,32, 32, 3).astype('float32')
#
#    #取出一次训练所需要的数据
#    def __getitem__(self, index):
#        label = self.labels[index]
#        image = self.images[index]
#
#        if self.transform is not None:
#            image = self.transform(image)
#
#        return image, label
#    #返回长度
#    def __len__(self):
#        return len(self.images)

#定义CNN模型类
class CifarDataset(Dataset):
    """User defined class to build a datset using Pytorch class Dataset."""

    # 构造函数,输入数据,转换方式
    def __init__(self, mode, transform=None):
        """Method to initilaize variables."""
        self.transform = transform
        if mode is 'train':
            self.batch_1 = np.load('image_reform1.npy')
            self.batch_2 = np.load('image_reform2.npy')
            self.batch_3 = np.load('image_reform3.npy')
            self.batch_4 = np.load('image_reform4.npy')
            self.batch_5 = np.load('image_reform5.npy')
            self.labels_1 = np.load('labels1.npy')
            self.labels_2 = np.load('labels2.npy')
            self.labels_3 = np.load('labels3.npy')
            self.labels_4 = np.load('labels4.npy')
            self.labels_5 = np.load('labels5.npy')
            self.images = np.concatenate([self.batch_1,self.batch_2,self.batch_3,self.batch_4,self.batch_5])
            self.labels = np.concatenate([self.labels_1,self.labels_2,self.labels_3,self.labels_4,self.labels_5])
            print(self.images.shape)





        if mode is 'test':
            self.images = np.load('image_reform_test.npy')
            self.labels = np.load('labels_test.npy')



    # 取出一次训练所需要的数据
    def __getitem__(self, index):
        label = self.labels[index]
        image = self.images[index]

        if self.transform is not None:
            image = self.transform(image)

        return image, label

    # 返回长度
    def __len__(self):
        return len(self.images)

class CifarCNN(nn.Module):

    #构造函数
    def __init__(self):
        super(CifarCNN, self).__init__()

        #第一层:卷积层(输入:32*32*3 输出:32*32*32)
        #       最大池化层(输入:32*32*32 输出:16*16*32)
        #计算:卷积层输出:(W-F+2P)/S+1
        #     池化层输出:(W-F)/S+1
        self.layer1 = nn.Sequential(
            #卷积层
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1),
            #归一化
            nn.BatchNorm2d(32),
            #激活函数
            nn.ReLU(),
            #最大池化层
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        #第二层:卷积层(输入:16*16*32 输出:14*14*64)
        #       最大池化层 (输入:14*14*64 输出:7*7*64)
        self.layer2 = nn.Sequential(
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        #全连接层
        self.fc1 = nn.Linear(in_features=64 * 7 * 7, out_features=600)
        #停止工作概率
        self.drop = nn.Dropout2d(0.25)
        self.fc2 = nn.Linear(in_features=600, out_features=120)
        self.fc3 = nn.Linear(in_features=120, out_features=10)

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.view(out.size(0), -1)
        out = self.fc1(out)
        out = self.drop(out)
        out = self.fc2(out)
        out = self.fc3(out)

        return out


def output_label(label):
    output_mapping = {
                 0: "airplane",
                 1: "automobile",
                 2: "bird",
                 3: "cat",
                 4: "deer",
                 5: "dog",
                 6: "frog",
                 7: "horse",
                 8: "ship",
                 9: "truck"
                 }
    input = (label.item() if type(label) == torch.Tensor else label)
    return output_mapping[input]

"""
#基于CSV格式的数取读取,加载
#读入csv
train_csv = pd.read_csv("data_batch_1.csv")
train_csv2 = pd.read_csv("data_batch_2.csv")
train_csv3 = pd.read_csv("data_batch_3.csv")
train_csv4 = pd.read_csv("data_batch_4.csv")
train_csv5 = pd.read_csv("data_batch_5.csv")
test_csv = pd.read_csv("test_batch.csv")
#定义数据集对象
train_set = CifarDataset(train_csv, transform=transforms.Compose([transforms.ToTensor()]))
train_set2 = CifarDataset(train_csv2, transform=transforms.Compose([transforms.ToTensor()]))
train_set3 = CifarDataset(train_csv3, transform=transforms.Compose([transforms.ToTensor()]))
train_set4 = CifarDataset(train_csv4, transform=transforms.Compose([transforms.ToTensor()]))
train_set5 = CifarDataset(train_csv5, transform=transforms.Compose([transforms.ToTensor()]))
test_set = CifarDataset(test_csv, transform=transforms.Compose([transforms.ToTensor()]))

train_loader = DataLoader(train_set, batch_size=100)
train_loader2 = DataLoader(train_set2, batch_size=100)
train_loader3 = DataLoader(train_set3, batch_size=100)
train_loader4 = DataLoader(train_set4, batch_size=100)
train_loader5 = DataLoader(train_set5, batch_size=100)
test_loader = DataLoader(test_set, batch_size=100)
"""

#循环次数

count = 0
# Lists for visualization of loss and accuracy
#误差
#loss_list = []
#迭代次数
iteration_list = []
#精度
accuracy_list = []
# Lists for knowing classwise accuracy
#predictions_list = []
labels_list = []
test_predictions_list=[]

"""
#定义训练函数,输入迭代器
def train(train_loader):
    global count
    global test_loader
    global iteration_list
    global loss_list
    global accuracy_list
    #对每张图片进行处理
    for images, labels in train_loader:
        # Transfering images and labels to GPU if available
        images, labels = images.to(device), labels.to(device)
        #改变图像大小,注意写成-1,自动计算行数,避免出错
        #train = Variable(images.view(-1, 3, 32, 32))
        #labels = Variable(labels)

        # Forward pass
        outputs = model(images)
        # print(type(outputs))
        # print(type(labels[1]))
        # print(labels)
        #计算误差
        loss = error(outputs, labels.long())

        # Initializing a gradient as 0 so there is no mixing of gradient among the batches
        optimizer.zero_grad()

        # Propagating the error backward
        loss.backward()

        # Optimizing the parameters
        optimizer.step()

        count += 1

        # Testing the model
    if not (count % 50):  # It's same as "if count % 50 == 0"
        total = 0
        correct = 0

        #利用测试集测试训练精度
        for images, labels in test_loader:
            images, labels = images.to(device), labels.to(device)
            labels_list.append(labels)

            #test = Variable(images.view(-1, 3, 32, 32))

            outputs = model(images)

            predictions = torch.max(outputs, 1)[1].to(device)

            predictions_list.append(predictions)
            correct += (predictions == labels).sum()

            total += len(labels)

        # accuracy = correct * 100 / total
        #torch新版本不能直接除
        accuracy = torch.true_divide(correct * 100, total)
        loss_list.append(loss.data)
        iteration_list.append(count)
        accuracy_list.append(accuracy)


    if not (count % 500):
        print("Iteration: {}, Loss: {}, Accuracy: {}%".format(count, loss.data, accuracy))
"""


#模型对象
model = CifarCNN()
if cuda:
    model = model.cuda()
#model.to(device)
#损失函数
error = nn.CrossEntropyLoss()
#学习率

optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

train_set = CifarDataset('train', transform=transforms.Compose([transforms.ToTensor()]))

train_loader = DataLoader(train_set, batch_size)

test_set = CifarDataset('test', transform=transforms.Compose([transforms.ToTensor()]))
test_loader = DataLoader(test_set, batch_size)

#调整学习率
def exp_lr_scheduler(optimizer, epoch, init_lr=0.001, lr_decay=4):
    """Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
    lr = init_lr * (decay_rate**(epoch // lr_decay))

    if epoch % lr_decay == 0:
        print('LR is set to {}'.format(lr))

    for param_group in optimizer.param_groups:
        param_group['lr'] = lr
    #返回改变了学习率的optimizer
    return optimizer


for epoch in range(1,num_epochs+1):
    loss_list = []
    precision_list = []

    if use_lr_decay:
        optimizer = exp_lr_scheduler(optimizer, epoch, learning_rate, lr_decay)

    start_time = time.time()


    # 对每张图片进行处理
 #   for images, labels in train_loader:
        # Transfering images and labels to GPU if available
    for batch_id, [images, labels] in enumerate(train_loader):
        batch_time = time.time()
        if cuda:
            images = images.cuda()
            labels = labels.cuda()
        #images, labels = images.to(device), labels.to(device)
       # Forward pass
        outputs = model(images)
        # 计算误差
        loss = error(outputs, labels.long())
        loss_list.append(loss.item())

        # Initializing a gradient as 0 so there is no mixing of gradient among the batches
        optimizer.zero_grad()

        # Propagating the error backward
        loss.backward()

        # Optimizing the parameters
        optimizer.step()

        count += 1

        # Testing the model
        if not (count % 50):  # It's same as "if count % 50 == 0"
            total = 0
            correct = 0

            # 利用测试集测试训练精度
            for images, labels in test_loader:
                #images, labels = images.to(device), labels.to(device)
                if cuda:
                    images = images.cuda()
                    labels = labels.cuda()
                labels_list.append(labels)

                # test = Variable(images.view(-1, 3, 32, 32))

                outputs = model(images)

                test_predictions = torch.max(outputs, 1)[1].cuda()

                test_predictions_list.append(test_predictions)
                correct += (predictions == labels).sum()

                total += len(labels)

            # accuracy = correct * 100 / total
            # torch新版本不能直接除
            accuracy = torch.true_divide(correct * 100, total)
            #loss_list.append(loss.data)
            iteration_list.append(count)
            accuracy_list.append(accuracy)

        if not (count % 500):
            #print("Iteration: {}, Loss: {}, Accuracy: {}%\n".format(count, loss.data, accuracy))
            with io.open(root_path + test_loss_file_name + '.txt', 'a', encoding='utf-8') as file:
                file.write(
                    "Iteration: {}, Loss: {}, Accuracy: {}%\n".format(count, loss.data, accuracy) )


        predictions = torch.max(outputs, 1)[1]
        hit = (predictions == labels).sum().item()
        precision = hit / len(labels)
        precision_list.append(precision)
        #         import ipdb; ipdb.set_trace()

        print('Train Epoch: {} [{}/{} ({:.0f}%)] | Loss: {:.4f} |  Precision: {:.4f} | Time:{} | Total_Time:{}'.format(
            epoch, (batch_id + 1), len(train_loader), 100. * (batch_id + 1) / len(train_loader),
            loss,
            precision,
            round((time.time() - batch_time), 4),
            round((time.time() - start_time), 4)))

        #     import ipdb; ipdb.set_trace()
        # save epoch-level performance

    with io.open(root_path + loss_file_name + '.txt', 'a', encoding='utf-8') as file:
        if epoch == 0:
            file.write('Epoch {}: start_loss: {:.4f}\n'.format(epoch, loss_list[0]))

        file.write('Epoch {}: Avg_loss: {:.4f} | Avg_precision: {:.4f}\n'.format(epoch, np.array(loss_list).mean(),
                                                                                 np.array(precision_list).mean()))








"""
#画出随迭代次数改变的损失
plt.plot(iteration_list, loss_list)
plt.xlabel("No. of Iteration")
plt.ylabel("Loss")
plt.title("Iterations vs Loss")
plt.show()
"""
#画出随迭代次数改变的误差
plt.plot(iteration_list, accuracy_list)
plt.xlabel("No. of Iteration")
plt.ylabel("Accuracy")
plt.title("Iterations vs Accuracy")
plt.show()


#计算每一类的精度
class_correct = [0. for _ in range(10)]
total_correct = [0. for _ in range(10)]

with torch.no_grad():
    for images, labels in test_loader:
        if cuda:
            images = images.cuda()
            labels = labels.cuda()
        test = Variable(images)
        outputs = model(test)
        predicted = torch.max(outputs, 1)[1]
        c = (predicted == labels).squeeze()

        for i in range(98):
            label = labels[i]
            class_correct[int(label)] += c[i].item()
            total_correct[int(label)] += 1

for i in range(10):
    print("Accuracy of {}: {:.2f}%".format(output_label(i), class_correct[i] * 100 / total_correct[i]))

#输出混淆矩阵
from itertools import chain

predictions_l = [test_predictions_list[i].tolist() for i in range(len(test_predictions_list))]
labels_l = [labels_list[i].tolist() for i in range(len(labels_list))]
predictions_l = list(chain.from_iterable(predictions_l))
labels_l = list(chain.from_iterable(labels_l))

import sklearn.metrics as metrics

confusion_matrix(labels_l, predictions_l)
print("Classification report for CNN :\n%s\n"
      % (metrics.classification_report(labels_l, predictions_l)))

ResNet18

#导入包
import torch
from torch import Tensor
import torch.nn as nn
from collections import OrderedDict

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from torch.autograd import Variable

import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from sklearn.metrics import confusion_matrix
import time
import io
import pickle

#from .utils import load_state_dict_from_url
from typing import Type, Any, Callable, Union, List, Optional
try:
    from torch.hub import load_state_dict_from_url
except ImportError:
    from torch.utils.model_zoo import load_url as load_state_dict_from_url

#有GPU,则使用GPU进行运算
device = torch.device("cpu")

num_epochs = 64
learning_rate = 0.001
batch_size = 2000

use_lr_decay = 0
lr_decay = 40
decay_rate = 0.5

root_path = 'E:\\360MoveData\\Users\\Lenovo\\Documents\\Tencent Files\\1908362588\\FileRecv\\大三下\\机器学习课设\\案例二\\data\\'
loss_file_name = 'Letmet-train_loss_epoch'+str(num_epochs)+'-lr'+str(learning_rate) + '-batch_size'+str(batch_size)
test_loss_file_name = 'Letmet-test_loss_epoch'+str(num_epochs)+'-lr'+str(learning_rate) + '-batch_size'+str(batch_size)

# 实现了不同层数的ResNet模型
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
           'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
           'wide_resnet50_2', 'wide_resnet101_2']

model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    # 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    # 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    # 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    # 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
    # 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
    # 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
    # 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
    # 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
}


def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=dilation, groups=groups, bias=False, dilation=dilation)


def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)


class BasicBlock(nn.Module):
    expansion: int = 1

    def __init__(
        self,
        inplanes: int,
        planes: int,
        stride: int = 1,
        downsample: Optional[nn.Module] = None,
        groups: int = 1,
        base_width: int = 64,
        dilation: int = 1,
        norm_layer: Optional[Callable[..., nn.Module]] = None
    ) -> None:
        super(BasicBlock, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        if groups != 1 or base_width != 64:
            raise ValueError('BasicBlock only supports groups=1 and base_width=64')
        if dilation > 1:
            raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = norm_layer(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = norm_layer(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x: Tensor) -> Tensor:
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
    # while original implementation places the stride at the first 1x1 convolution(self.conv1)
    # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
    # This variant is also known as ResNet V1.5 and improves accuracy according to
    # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.

    expansion: int = 4

    def __init__(
        self,
        inplanes: int,
        planes: int,
        stride: int = 1,
        downsample: Optional[nn.Module] = None,
        groups: int = 1,
        base_width: int = 64,
        dilation: int = 1,
        norm_layer: Optional[Callable[..., nn.Module]] = None
    ) -> None:
        super(Bottleneck, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        width = int(planes * (base_width / 64.)) * groups
        # Both self.conv2 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv1x1(inplanes, width)
        self.bn1 = norm_layer(width)
        self.conv2 = conv3x3(width, width, stride, groups, dilation)
        self.bn2 = norm_layer(width)
        self.conv3 = conv1x1(width, planes * self.expansion)
        self.bn3 = norm_layer(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x: Tensor) -> Tensor:
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out


class ResNet(nn.Module):

    def __init__(
        self,
        block: Type[Union[BasicBlock, Bottleneck]],
        layers: List[int],
        num_classes: int = 1000,
        zero_init_residual: bool = False,
        groups: int = 1,
        width_per_group: int = 64,
        replace_stride_with_dilation: Optional[List[bool]] = None,
        norm_layer: Optional[Callable[..., nn.Module]] = None
    ) -> None:
        super(ResNet, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        self._norm_layer = norm_layer

        self.inplanes = 64
        self.dilation = 1
        if replace_stride_with_dilation is None:
            # each element in the tuple indicates if we should replace
            # the 2x2 stride with a dilated convolution instead
            replace_stride_with_dilation = [False, False, False]
        if len(replace_stride_with_dilation) != 3:
            raise ValueError("replace_stride_with_dilation should be None "
                             "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
        self.groups = groups
        self.base_width = width_per_group
        self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = norm_layer(self.inplanes)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
                                       dilate=replace_stride_with_dilation[0])
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
                                       dilate=replace_stride_with_dilation[1])
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
                                       dilate=replace_stride_with_dilation[2])
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, Bottleneck):
                    nn.init.constant_(m.bn3.weight, 0)  # type: ignore[arg-type]
                elif isinstance(m, BasicBlock):
                    nn.init.constant_(m.bn2.weight, 0)  # type: ignore[arg-type]

    def _make_layer(self, block: Type[Union[BasicBlock, Bottleneck]], planes: int, blocks: int,
                    stride: int = 1, dilate: bool = False) -> nn.Sequential:
        norm_layer = self._norm_layer
        downsample = None
        previous_dilation = self.dilation
        if dilate:
            self.dilation *= stride
            stride = 1
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                norm_layer(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
                            self.base_width, previous_dilation, norm_layer))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes, groups=self.groups,
                                base_width=self.base_width, dilation=self.dilation,
                                norm_layer=norm_layer))

        return nn.Sequential(*layers)

    def _forward_impl(self, x: Tensor) -> Tensor:
        # See note [TorchScript super()]
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.fc(x)

        return x

    def forward(self, x: Tensor) -> Tensor:
        return self._forward_impl(x)


def _resnet(
    arch: str,
    block: Type[Union[BasicBlock, Bottleneck]],
    layers: List[int],
    pretrained: bool,
    progress: bool,
    **kwargs: Any
) -> ResNet:
    model = ResNet(block, layers, **kwargs)
    if pretrained:
        state_dict = load_state_dict_from_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model


def resnet18(pretrained: bool = True, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""ResNet-18 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
                   **kwargs)


# def resnet34(pretrained: bool = True, progress: bool = True, **kwargs: Any) -> ResNet:
#     r"""ResNet-34 model from
#     `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
#                    **kwargs)


# def resnet50(pretrained: bool = True, progress: bool = True, **kwargs: Any) -> ResNet:
#     r"""ResNet-50 model from
#     `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
#                    **kwargs)


# def resnet101(pretrained: bool = True, progress: bool = True, **kwargs: Any) -> ResNet:
#     r"""ResNet-101 model from
#     `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
#                    **kwargs)


# def resnet152(pretrained: bool = True, progress: bool = True, **kwargs: Any) -> ResNet:
#     r"""ResNet-152 model from
#     `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
#                    **kwargs)


# def resnext50_32x4d(pretrained: bool = True, progress: bool = True, **kwargs: Any) -> ResNet:
#     r"""ResNeXt-50 32x4d model from
#     `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.
#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     kwargs['groups'] = 32
#     kwargs['width_per_group'] = 4
#     return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
#                    pretrained, progress, **kwargs)


# def resnext101_32x8d(pretrained: bool = True, progress: bool = True, **kwargs: Any) -> ResNet:
#     r"""ResNeXt-101 32x8d model from
#     `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.
#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     kwargs['groups'] = 32
#     kwargs['width_per_group'] = 8
#     return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
#                    pretrained, progress, **kwargs)


# def wide_resnet50_2(pretrained: bool = True, progress: bool = True, **kwargs: Any) -> ResNet:
#     r"""Wide ResNet-50-2 model from
#     `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.
#     The model is the same as ResNet except for the bottleneck number of channels
#     which is twice larger in every block. The number of channels in outer 1x1
#     convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
#     channels, and in Wide ResNet-50-2 has 2048-1024-2048.
#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     kwargs['width_per_group'] = 64 * 2
#     return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
#                    pretrained, progress, **kwargs)


# def wide_resnet101_2(pretrained: bool = True, progress: bool = True, **kwargs: Any) -> ResNet:
#     r"""Wide ResNet-101-2 model from
#     `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.
#     The model is the same as ResNet except for the bottleneck number of channels
#     which is twice larger in every block. The number of channels in outer 1x1
#     convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
#     channels, and in Wide ResNet-50-2 has 2048-1024-2048.
#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     kwargs['width_per_group'] = 64 * 2
#     return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
#                    pretrained, progress, **kwargs)




#定义数据集类
class CifarDataset(Dataset):
    """User defined class to build a datset using Pytorch class Dataset."""

    # 构造函数,输入数据,转换方式
    def __init__(self, mode, transform=None):
        """Method to initilaize variables."""
        self.transform = transform
        if mode is 'train':
            self.batch_1 = np.load(root_path + 'image_reform1.npy')
            self.batch_2 = np.load(root_path + 'image_reform2.npy')
            self.batch_3 = np.load(root_path + 'image_reform3.npy')
            self.batch_4 = np.load(root_path + 'image_reform4.npy')
            self.batch_5 = np.load(root_path + 'image_reform5.npy')
            self.labels_1 = np.load(root_path + 'labels1.npy')
            self.labels_2 = np.load(root_path + 'labels2.npy')
            self.labels_3 = np.load(root_path + 'labels3.npy')
            self.labels_4 = np.load(root_path + 'labels4.npy')
            self.labels_5 = np.load(root_path + 'labels5.npy')
            self.images = np.concatenate([self.batch_1,self.batch_2,self.batch_3,self.batch_4,self.batch_5])
            self.labels = np.concatenate([self.labels_1,self.labels_2,self.labels_3,self.labels_4,self.labels_5])
            print(self.images.shape)

        if mode is 'test':
            self.images = np.load(root_path + 'image_reform_test.npy')
            self.labels = np.load(root_path + 'labels_test.npy')

    # 取出一次训练所需要的数据
    def __getitem__(self, index):
        label = self.labels[index]
        image = self.images[index]

        if self.transform is not None:
            image = self.transform(image)

        return image, label

    # 返回长度
    def __len__(self):
        return len(self.images)

#输出标签对应的类
def output_label(label):
    output_mapping = {
                 0: "airplane",
                 1: "automobile",
                 2: "bird",
                 3: "cat",
                 4: "deer",
                 5: "dog",
                 6: "frog",
                 7: "horse",
                 8: "ship",
                 9: "truck"
                 }
    input = (label.item() if type(label) == torch.Tensor else label)
    return output_mapping[input]


# #读入csv
# train_csv = pd.read_csv("data_batch_1.csv")
# train_csv2 = pd.read_csv("data_batch_2.csv")
# train_csv3 = pd.read_csv("data_batch_3.csv")
# train_csv4 = pd.read_csv("data_batch_4.csv")
# train_csv5 = pd.read_csv("data_batch_5.csv")
# test_csv = pd.read_csv("test_batch.csv")
# #定义数据集对象
# train_set = CifarDataset(train_csv, transform=transforms.Compose([transforms.ToTensor()]))
# train_set2 = CifarDataset(train_csv2, transform=transforms.Compose([transforms.ToTensor()]))
# train_set3 = CifarDataset(train_csv3, transform=transforms.Compose([transforms.ToTensor()]))
# train_set4 = CifarDataset(train_csv4, transform=transforms.Compose([transforms.ToTensor()]))
# train_set5 = CifarDataset(train_csv5, transform=transforms.Compose([transforms.ToTensor()]))
# test_set = CifarDataset(test_csv, transform=transforms.Compose([transforms.ToTensor()]))

# #定义迭代器
# train_loader = DataLoader(train_set, batch_size=100)
# train_loader2 = DataLoader(train_set2, batch_size=100)
# train_loader3 = DataLoader(train_set3, batch_size=100)
# train_loader4 = DataLoader(train_set4, batch_size=100)
# train_loader5 = DataLoader(train_set5, batch_size=100)
# test_loader = DataLoader(test_set, batch_size=100)

# 初始化网络
net = resnet18()
net.to(device)

#循环次数
count = 0
# Lists for visualization of loss and accuracy
#误差
loss_list = []
#迭代次数
iteration_list = []
#精度
accuracy_list = []
# Lists for knowing classwise accuracy
#predictions_list = []
labels_list = []
test_predictions_list=[]


# #定义训练函数,输入迭代器
# def train(train_loader):
#     global count
#     global test_loader
#     global iteration_list
#     global loss_list
#     global accuracy_list
#     #对每张图片进行处理
#     for images, labels in train_loader:
#         # Transfering images and labels to GPU if available
#         images, labels = images.to(device), labels.to(device)
#         #改变图像大小,注意写成-1,自动计算行数,避免出错
#         train = Variable(images.view(-1, 3, 32, 32))
#         labels = Variable(labels)

#         # Forward pass
#         outputs = net(train)
#         # print(type(outputs))
#         # print(type(labels[1]))
#         # print(labels)
#         #计算误差
#         loss = error(outputs, labels.long())

#         # Initializing a gradient as 0 so there is no mixing of gradient among the batches
#         optimizer.zero_grad()

#         # Propagating the error backward
#         loss.backward()

#         # Optimizing the parameters
#         optimizer.step()

#         count += 1

#         # Testing the model
#     if not (count % 50):  # It's same as "if count % 50 == 0"
#         total = 0
#         correct = 0

#         #利用测试集测试训练精度
#         for images, labels in test_loader:
#             images, labels = images.to(device), labels.to(device)
#             labels_list.append(labels)

#             test = Variable(images.view(-1, 3, 32, 32))

#             outputs = net(test)

#             predictions = torch.max(outputs, 1)[1].to(device)

#             predictions_list.append(predictions)
#             correct += (predictions == labels).sum()

#             total += len(labels)

#         # accuracy = correct * 100 / total
#         #torch新版本不能直接除
#         accuracy = torch.true_divide(correct * 100, total)
#         loss_list.append(loss.data)
#         iteration_list.append(count)
#         accuracy_list.append(accuracy)


#     if not (count % 500):
#         print("Iteration: {}, Loss: {}, Accuracy: {}%".format(count, loss.data, accuracy))


#损失函数
error = nn.CrossEntropyLoss()
#学习率
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)

train_set = CifarDataset('train', transform=transforms.Compose([transforms.ToTensor()]))
train_loader = DataLoader(train_set, batch_size)
test_set = CifarDataset('test', transform=transforms.Compose([transforms.ToTensor()]))
test_loader = DataLoader(test_set, batch_size)

#调整学习率
def exp_lr_scheduler(optimizer, epoch, init_lr=0.001, lr_decay=4):
    """Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
    lr = init_lr * (decay_rate**(epoch // lr_decay))

    if epoch % lr_decay == 0:
        print('LR is set to {}'.format(lr))

    for param_group in optimizer.param_groups:
        param_group['lr'] = lr
    #返回改变了学习率的optimizer
    return optimizer

#循环训练
for epoch in range(num_epochs):
    loss_list = []
    precision_list = []

    if use_lr_decay:
        optimizer = exp_lr_scheduler(optimizer, epoch, learning_rate, lr_decay)

    start_time = time.time()

    for batch_id, [images, labels] in enumerate(train_loader):
        batch_time = time.time()

        # Forward pass
        outputs = net(images)
        #计算误差
        loss = error(outputs, labels.long())
        loss_list.append(loss.item())


        # Initializing a gradient as 0 so there is no mixing of gradient among the batches
        optimizer.zero_grad()

        # Propagating the error backward
        loss.backward()

        # Optimizing the parameters
        optimizer.step()

        count += 1

        # Testing the model
        if not (count % 50):  # It's same as "if count % 50 == 0"
            total = 0
            correct = 0

            #利用测试集测试训练精度
            for images, labels in test_loader:
                images, labels = images.to(device), labels.to(device)
                labels_list.append(labels)

                test = Variable(images.view(-1, 3, 32, 32))

                outputs = net(test)

                # predictions = torch.max(outputs, 1)[1].to(device)

                # predictions_list.append(predictions)
                test_predictions = torch.max(outputs, 1)[1].to(device)

                test_predictions_list.append(test_predictions)
                
                correct += (predictions == labels).sum()

                total += len(labels)

            # accuracy = correct * 100 / total
            #torch新版本不能直接除
            accuracy = torch.true_divide(correct * 100, total)
            #loss_list.append(loss.data)
            iteration_list.append(count)
            accuracy_list.append(accuracy)


        if not (count % 500):
            with io.open(root_path + test_loss_file_name + '.txt', 'a', encoding='utf-8') as file:
                file.write(
                    "Iteration: {}, Loss: {}, Accuracy: {}%\n".format(count, loss.data, accuracy) )
        
        predictions = torch.max(outputs, 1)[1]
        hit = (predictions == labels).sum().item()
        precision = hit / len(labels)
        precision_list.append(precision)

        print('Train Epoch: {} [{}/{} ({:.0f}%)] | Loss: {:.4f} |  Precision: {:.4f} | Time:{} | Total_Time:{}'.format(
            epoch, (batch_id + 1), len(train_loader), 100. * (batch_id + 1) / len(train_loader),
            loss,
            precision,
            round((time.time() - batch_time), 4),
            round((time.time() - start_time), 4)))

    with io.open(root_path + 'ResNet18\\' + loss_file_name + '.txt', 'a', encoding='utf-8') as file:
        if epoch == 0:
            file.write('Epoch {}: start_loss: {:.4f}\n'.format(epoch, loss_list[0]))

        file.write('Epoch {}: Avg_loss: {:.4f} | Avg_precision: {:.4f}\n'.format(epoch, np.array(loss_list).mean(),
                                                                                 np.array(precision_list).mean()))

# #画出随迭代次数改变的损失
# plt.plot(iteration_list, loss_list)
# plt.xlabel("No. of Iteration")
# plt.ylabel("Loss")
# plt.title("Iterations vs Loss")
# plt.show()
# #画出随迭代次数改变的误差
# plt.plot(iteration_list, accuracy_list)
# plt.xlabel("No. of Iteration")
# plt.ylabel("Accuracy")
# plt.title("Iterations vs Accuracy")
# plt.show()


#计算每一类的精度
class_correct = [0. for _ in range(10)]
total_correct = [0. for _ in range(10)]

with torch.no_grad():
    for images, labels in test_loader:
        images, labels = images.to(device), labels.to(device)
        test = Variable(images)
        outputs = net(test)
        predicted = torch.max(outputs, 1)[1]
        c = (predicted == labels).squeeze()

        for i in range(98):
            label = labels[i]
            class_correct[int(label)] += c[i].item()
            total_correct[int(label)] += 1

with open(root_path + 'ResNet18\\' + 'epoch'+str(num_epochs)+'-lr'+str(learning_rate) + '-batch_size'+str(batch_size) + '_accuracy.txt',mode='w') as file0:
    for i in range(10):
        print("Accuracy of {}: {:.2f}%".format(output_label(i), class_correct[i] * 100 / total_correct[i]),file=file0)


# #输出混淆矩阵
# from itertools import chain

# predictions_l = [predictions_list[i].tolist() for i in range(len(predictions_list))]
# labels_l = [labels_list[i].tolist() for i in range(len(labels_list))]
# predictions_l = list(chain.from_iterable(predictions_l))
# labels_l = list(chain.from_iterable(labels_l))

# import sklearn.metrics as metrics

# confusion_matrix(labels_l, predictions_l)
# print("Classification report for CNN :\n%s\n"
#       % (metrics.classification_report(labels_l, predictions_l)))

训练函数

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import torch
import torch.nn as nn
from torch.autograd import Variable

import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from sklearn.metrics import confusion_matrix


batch_size = 128
learning_rate = 0.001
num_epochs = 5


class FashionDataset(Dataset):
    """User defined class to build a datset using Pytorch class Dataset."""
    
    def __init__(self, mode, transform = None):
        """Method to initilaize variables.""" 
	if mode is ‘train’:
        		self.batch_1 = np.load(path/image_reform.npy)
		….
		self.batch_5 = np.load(path/image_reform.npy)
		self.labels_1 = np.load(path/labels1.npy)

		self.images = np.concatenate([batch_1,…, batch_5])
		self.labels = np.concatenate([labels_1,…, labels_5])
	if mode is ‘test’:
		self.images = np.load(path/image_reform_test.npy)
		self.labels = np.load(path/labels_test.npy)

        self.transform = transform #torch.toTensor()
        
        

    def __getitem__(self, index):
        label = self.labels[index]
        image = self.images [index]
        
        if self.transform is not None:
            image = self.transform(image)

        return image, label

    def __len__(self):
        return len(self.images)

train_set = FashionDataset(‘train’, transform=transforms.Compose([transforms.ToTensor()]))

train_loader = DataLoader(train_set, batch_size)

test_set = FashionDataset(‘test’, transform=transforms.Compose([transforms.ToTensor()]))
test_loader = DataLoader(test_set, batch_size)


class FashionCNN(nn.Module):
    
    def __init__(self):
        super(FashionCNN, self).__init__()
        
        self.layer1 = nn.Sequential(
            nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        
        self.layer2 = nn.Sequential(
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        
        self.fc1 = nn.Linear(in_features=64*6*6, out_features=600)
        self.drop = nn.Dropout2d(0.25)
        self.fc2 = nn.Linear(in_features=600, out_features=120)
        self.fc3 = nn.Linear(in_features=120, out_features=10)
        
    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.view(out.size(0), -1)
        out = self.fc1(out)
        out = self.drop(out)
        out = self.fc2(out)
        out = self.fc3(out)
        
        return out

model = FashionCNN()

error = nn.CrossEntropyLoss()

optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

count = 0
# Lists for visualization of loss and accuracy 
loss_list = []
iteration_list = []
accuracy_list = []

# Lists for knowing classwise accuracy
predictions_list = []
labels_list = []


for epoch in range(num_epochs):
    for images, labels in enumerate(train_loader):
        
        # Forward pass 
        outputs = model(images)
        loss = error(outputs, labels)
        
        # Initializing a gradient as 0 so there is no mixing of gradient among the batches
        optimizer.zero_grad()
        
        #Propagating the error backward
        loss.backward()
        
        # Optimizing the parameters
        optimizer.step()
    
        count += 1

# Testing the model
    
        if not (count % 50):    # It's same as "if count % 50 == 0"
            total = 0
            correct = 0
        
            for images_test, labels_test in test_loader:
                outputs = model(images_test)            
            
                predictions = torch.max(outputs, 1)[1].to(device)
                predictions_list.append(predictions)
                correct += (predictions == labels).sum()
            
                total += len(labels)
            
            accuracy = correct * 100 / total
            loss_list.append(loss.data)
            iteration_list.append(count)
            accuracy_list.append(accuracy)
        
        if not (count % 500):
            print("Iteration: {}, Loss: {}, Accuracy: {}%".format(count, loss.data, accuracy))




#Visualizing the Loss and Accuracy with Iterations
plt.plot(iteration_list, loss_list)
plt.xlabel("No. of Iteration")
plt.ylabel("Loss")
plt.title("Iterations vs Loss")
plt.show()



Looking the Accuracy in each class of FashionMNIST dataset
class_correct = [0. for _ in range(10)]
total_correct = [0. for _ in range(10)]

with torch.no_grad():
    for images, labels in test_loader:
        images, labels = images.to(device), labels.to(device)
        test = Variable(images)
        outputs = model(test)
        predicted = torch.max(outputs, 1)[1]
        c = (predicted == labels).squeeze()
        
        for i in range(100):
            label = labels[i]
            class_correct[label] += c[i].item()
            total_correct[label] += 1
        
for i in range(10):
    print("Accuracy of {}: {:.2f}%".format(output_label(i), class_correct[i] * 100 / total_correct[i]))
















pix_path = os.getcwd()  #'/mnt/NeuralStyle/Laboratory_Use/pix2pix/pix2pix_Use/pix2pix-step1'

os.makedirs('images/%s' % opt.dataset_name, exist_ok=True)  #过程图片
os.makedirs('saved_models/%s/d' % opt.dataset_name, exist_ok=True)   #存放模型
os.makedirs('loss_message/%s' % opt.dataset_name, exist_ok=True)   #存放loss信息

# Loss weight of L1 pixel-wise loss between translated image and real image
lambda_pixel = 10

cuda = True if torch.cuda.is_available() else False


# Loss functions
criterion_GAN = torch.nn.MSELoss()  #均方损失函数
criterion_pixelwise = torch.nn.L1Loss() #创建一个衡量输入x(模型预测输出)和目标y之间差的绝对值的平均值的标准




# Calculate output of image discriminator (PatchGAN)
patch = (1, opt.img_height//2**4, opt.img_width//2**4)

# Initialize generator and discriminator
generator = GeneratorUNet()
discriminator = Discriminator()



if cuda:
    generator = generator.cuda()
    discriminator = discriminator.cuda()
    criterion_GAN.cuda()
    criterion_pixelwise.cuda()

generator.apply(weights_init_normal)
discriminator.apply(weights_init_normal)

# Optimizers
learning_rate_G = opt.learning_rate_G
learning_rate_D = opt.learning_rate_D

optimizer_G = torch.optim.Adam(generator.parameters(), lr=learning_rate_G, betas=(opt.b1, opt.b2))
optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=learning_rate_D, betas=(opt.b1, opt.b2))


# Configure dataloaders
transforms_ = [     transforms.ToTensor(),
               transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))]

#修改成本地存放数据集地址
dataloader = DataLoader(ImageDataset("F:\\fontdata" , transforms_=transforms_),
                        batch_size=opt.batch_size, shuffle=True, num_workers=0)

val_dataloader = DataLoader(ImageDataset("F:\\fontdata" , transforms_=transforms_, mode='val'),
                            batch_size=20, shuffle=False, num_workers=0)

# Tensor type
Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor

def sample_images(batches_done):
    """Saves a generated sample from the validation set"""
    imgs = next(iter(val_dataloader))
    real_A = imgs['B'].type(Tensor)
    real_B = imgs['A'].type(Tensor)
    fake_B = generator(real_A)
    img_sample = torch.cat((real_A.data, fake_B.data, real_B.data), -2)
   # ipdb.set_trace()
    save_image(img_sample, pix_path + '/images/%s/%s.png' % (opt.dataset_name, batches_done), nrow=5, normalize=True)

    
    
    
def loss_val():
    batch = next(iter(val_dataloader))
    real_A = batch['B'].type(Tensor)
    real_B = batch['A'].type(Tensor)
    valid = Variable(Tensor(np.ones((real_A.size(0), *patch))), requires_grad=False)
    fake = Variable(Tensor(np.zeros((real_A.size(0), *patch))), requires_grad=False)
    fake_B = generator(real_A)
    pred_fake = discriminator(fake_B, real_A)
    loss_GAN = criterion_GAN(pred_fake, valid)
    # Pixel-wise loss
    loss_pixel = criterion_pixelwise(fake_B, real_B)

    return loss_pixel.item()

# ----------
#  Training
# ----------
generator.train()
discriminator.train()
prev_time = time.time()


#lr shuai jian
def lr_scheduler(optimizer, init_lr, epoch, lr_decay_iter):
    if epoch % lr_decay_iter:
        return init_lr
    lr = init_lr * 0.5
    optimizer.param_groups[0]['lr'] = lr
    return lr

min_tloss = 500
tloss_res = {}

for epoch in range(opt.epoch, opt.n_epochs):
    
    
    ch_lr_avg_loss_depart = []
    ch_lr_avg_loss = 0
    
    if epoch > 0:
        learning_rate_G = lr_scheduler(optimizer_G, learning_rate_G,epoch+1, opt.lrgd)
        # learning_rate_D = lr_scheduler(optimizer_D, learning_rate_D,epoch+1, opt.lrdd)
    
   
    print(learning_rate_G)
    print(learning_rate_D)
    
    for i, batch in enumerate(dataloader):

        # Model inputs
        real_A = batch['B'].type(Tensor)
        real_B = batch['A'].type(Tensor)

        # Adversarial ground truths
        valid = Variable(Tensor(np.ones((//
            real_A.size(0), *patch))), requires_grad=False)
        fake = Variable(Tensor(np.zeros((//
            real_A.size(0), *patch))), requires_grad=False)

        # ------------------
        #  Train Generators
        # ------------------
        # GAN loss
        fake_B = generator(real_A)
        #ipdb.set_trace()
        pred_fake = discriminator(fake_B, real_A)
        # ipdb.set_trace()
        loss_GAN = criterion_GAN(pred_fake, valid)
        # Pixel-wise loss
        loss_pixel = criterion_pixelwise(fake_B, real_B)

        # Total loss
        loss_G = loss_GAN + lambda_pixel * loss_pixel

        ch_lr_avg_loss_depart.append(loss_G.data.item())

        optimizer_G.zero_grad()

        loss_G.backward()

        optimizer_G.step()

        # ---------------------
        #  Train Discriminator
        # ---------------------

        optimizer_D.zero_grad()

        # Real loss
        pred_real = discriminator(real_B, real_A)
        loss_real = criterion_GAN(pred_real, valid)

        # Fake loss
        pred_fake = discriminator(fake_B.detach(), real_A)
        loss_fake = criterion_GAN(pred_fake, fake)

        # Total loss
        loss_D = 0.5 * (loss_real + loss_fake)

        loss_D.backward()
        optimizer_D.step()

        # --------------
        #  Log Progress
        # --------------

        # Determine approximate time left
        batches_done = epoch * len(dataloader) + i
        batches_left = opt.n_epochs * len(dataloader) - batches_done
        time_left = datetime.timedelta(seconds=batches_left * (time.time() - prev_time))
        prev_time = time.time()

        # Print log
        sys.stdout.write("\r[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [ pixel: %f, loss_GAN: %f] ETA: %s" %
                                                        (epoch, opt.n_epochs,
                                                        i, len(dataloader),
                                                        loss_D.item(),
                                                        lambda_pixel*loss_pixel.item(), loss_GAN.item(),
                                                        time_left))
        
        with io.open( pix_path + '/loss_message/%s/train_loss.txt' % opt.dataset_name, 'a', encoding='utf-8') as file:
            file.write('[Epoch: {}] [Dloss: {:.4f}] [loss_pixel: {:.4f}] [loss_GAN: {:.4f}] [Batch: {}/{}] \n'
                       .format(epoch,loss_D.item(),lambda_pixel*loss_pixel.item(),loss_GAN.item(),i,len(dataloader) ))


        
        # If at sample interval save image
        if batches_done % opt.sample_interval == 0:
            sample_images(batches_done)
    
    #计算平均loss和时间
    ch_lr_avg_loss = sum(ch_lr_avg_loss_depart) / len(ch_lr_avg_loss_depart)
    
    print('----------------------------------------------------------- \n')
    print('avg_loss: {:.4f} \n'.format(ch_lr_avg_loss))

    with io.open( pix_path + '/loss_message/%s/loss_time.txt' % opt.dataset_name, 'a', encoding='utf-8') as file:
        file.write('[avg_loss: {:.4f}] \n'.format(ch_lr_avg_loss))
    
    
    
    avg_loss = 0
    avg_loss = loss_val()    
    tloss_res[epoch] = avg_loss
    
    #每50轮保存模型参数
    if epoch > 0 and (epoch + 1) % 50 == 0:
        torch.save(generator.state_dict(), pix_path + '/saved_models/%s/generator_%d.pth' % (opt.dataset_name, epoch))
        torch.save(discriminator.state_dict(), pix_path + '/saved_models/%s/d/discriminator_%d.pth' % (opt.dataset_name, epoch))
    #保存loss最小时的模型参数
    if tloss_res[epoch] < min_tloss:
        min_tloss = tloss_res[epoch]
        tloss_res['min'] = tloss_res[epoch]
        tloss_res['minepoch'] = epoch
        torch.save(generator.state_dict(), pix_path + '/saved_models/%s/generator_min.pth' % (opt.dataset_name))
        torch.save(discriminator.state_dict(), pix_path + '/saved_models/%s/d/discriminator_min.pth' % (opt.dataset_name))
       

    
with io.open( pix_path + '/loss_message/%s/list_loss.txt' % opt.dataset_name, 'a', encoding='utf-8') as file:
    file.write('tloss_res: {} \n'.format(tloss_res))
        




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值