7月网络学习报告

2023-11-04

原始代码

import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
import os, PIL, pathlib,random


device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

data_dir = '/Users/montylee/NJUPT/Learn/Github/deeplearning/pytorch/P6/data/'
data_dir = pathlib.Path(data_dir)

data_paths = list(data_dir.glob('*'))
classNames = [str(path).split('/')[-1] for path in data_paths]

train_transforms = transforms.Compose([
    transforms.Resize([224,224]),
    transforms.RandomHorizontalFlip(), # 随机翻转和旋转
    transforms.ToTensor(),
    transforms.Normalize(mean = [0.485, 0.456, 0.406], # 均值
                         std = [0.229, 0.224, 0.225]) # 方差
])

total_dataset = datasets.ImageFolder(data_dir, transform=train_transforms)

total_dataset.class_to_idx

train_size = int(0.8 * len(total_dataset))
test_size = len(total_dataset) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(total_dataset, [train_size, test_size])
train_dataset, test_dataset

batch_size = 32
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=1)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True, num_workers=1)
[32]
# 构建 CNN 网络
import torch.nn.functional as F

num_classes = len(classNames)

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        # 特征提取网络
        self.conv1 = nn.Conv2d(3,16,kernel_size=3)
        self.bn1 = nn.BatchNorm2d(16)
        self.pool1 = nn.MaxPool2d(kernel_size=2)
        self.dropout = nn.Dropout(p=0.3)

        self.conv2 = nn.Conv2d(16,32,kernel_size=3)
        self.bn2 = nn.BatchNorm2d(32)
        self.pool2 = nn.MaxPool2d(kernel_size=2)
        self.dropout = nn.Dropout(p=0.3)

        self.conv3 = nn.Conv2d(32,64,kernel_size=3)
        self.bn3 = nn.BatchNorm2d(64)
        self.pool3 = nn.MaxPool2d(kernel_size=2)
        # self.dropout = nn.Dropout(p=0.3)

        # self.conv4 = nn.Conv2d(128,256,kernel_size=3)
        # self.pool4 = nn.MaxPool2d(kernel_size=2)


        # 分类网络
        self.fc1 = nn.Linear(64*26*26, 256)
        self.fc2 = nn.Linear(256, num_classes)


    def forward(self, x):
        x = self.pool1(F.relu(self.conv1(x)))
        x = self.dropout(x)
        x = self.pool2(F.relu(self.conv2(x)))
        x = self.dropout(x)
        x = self.pool3(F.relu(self.conv3(x)))
        # x = self.dropout(x)
        # x = self.pool4(F.relu(self.conv4(x)))

        # print(x.shape)

        x = torch.flatten(x, start_dim=1)

        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return x


loss_fn = nn.CrossEntropyLoss()
learn_rate = 1e-2
opt = torch.optim.SGD(model.parameters(), lr=learn_rate)

def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)

    train_loss, train_acc = 0 , 0

    for x , y in dataloader:
        x, y = x.to(device), y.to(device)

        pred = model(x)
        loss = loss_fn(pred, y)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    train_acc /= size
    train_loss /= num_batches

    return train_acc, train_loss


def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)

    test_loss, test_acc = 0 , 0

    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)

            target_pred = model(imgs)
            loss = loss_fn(target_pred, target)

            test_loss += loss.item()
            test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc /= size
    test_loss /= num_batches

    return test_acc, test_loss


epochs = 10
train_loss = []
train_acc = []
test_loss = []
test_acc = []

for epoch in range(epochs):
    model.train()
    epoch_train_acc, epoch_train_loss = train(train_loader, model, loss_fn, opt)

    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_loader, model, loss_fn)

    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

    template = ('Epoch:{:2d},Train_acc:{:.1f}%,Train_loss:{:.3f},Test_acc:{:.1f}%,Test_loss:{:.3f}')
    print(template.format(epoch+1,epoch_train_acc*100,epoch_train_loss,epoch_test_acc*100,epoch_test_loss))

print("Done")

import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['figure.dpi'] = 100

epochs_range = range(epochs)

plt.figure(figsize = (12,3))
plt.subplot(1,2,1)
plt.plot(epochs_range,train_acc,label='Training Accuracy')
plt.plot(epochs_range,test_acc,label='Test Accuracy')
plt.legend()
plt.title("Training and Validation Accuracy")

plt.subplot(1,2,2)
plt.plot(epochs_range,train_loss,label="Training Loss")
plt.plot(epochs_range,test_loss,label='Testing Loss')
plt.legend()
plt.title('Training and Validation Loss')
plt.show()

结果:

问题:

1.test_accuracy太低,小于30%,且没有收敛

2.只训练了10个epoch


解决方法

数据增强

数据集数量太少,而且将数据集分为训练集与测试集之后,数量更为稀少。

可以通过平移、旋转、缩放、裁剪、翻转、变形等,对图片进行处理,增加数据集数量

代码

(下面只对图像进行了翻转)

def data_aug(input_path, output_path,  new_data_path):
    imgaug(input_path, output_path)
    rename_img(output_path)
    merge_files(new_data_path, input_path, output_path)

def imgaug(input_path, output_path):
    input_dirs = [d for d in os.listdir(input_path) if os.path.isdir(os.path.join(input_path, d))]
    output_dirs = [d for d in os.listdir(output_path) if os.path.isdir(os.path.join(output_path, d))]

    for i in range(len(input_dirs)):
        input_dirs[i] = input_path + "\\" + input_dirs[i]

    for i in range(len(output_dirs)):
        output_dirs[i] = output_path + "\\" + output_dirs[i]

    seq = iaa.Sequential([iaa.Flipud(1.0)])

    len_class = len(input_dirs)

    for i in range(len_class):
        for file_name in os.listdir(input_dirs[i]):

            file_path = os.path.join(input_dirs[i], file_name)
            img = Image.open(file_path)


            img_arr = np.array(img)
            img_aug = seq(images=img_arr)
            img_aug = Image.fromarray(img_aug)

            if img_aug.mode == 'RGBA':
                    img_aug = img_aug.convert('RGB')

            output_file_path = os.path.join(output_dirs[i], file_name)
            img_aug.save(output_file_path)

def rename_img(folder_path):

    counters = {} 

    for folder_name in os.listdir(folder_path):
        folder = os.path.join(folder_path, folder_name)
        if os.path.isdir(folder):
            file_types = ['*.jpg', '*.jpeg', '*.png'] 
            total_files = 0
            for file_type in file_types:
                total_files += len(glob.glob(os.path.join(folder, file_type)))
            counters[folder_name] = total_files 
    counters = {key: value + 1 for key, value in counters.items()}

    for subfolder in os.listdir(folder_path):
        subfolder_path = os.path.join(folder_path, subfolder)
        if os.path.isdir(subfolder_path):
            counter = counters[subfolder]

            for name in os.listdir(subfolder_path):
                if name.endswith('.jpg') or name.endswith('.jpeg') or name.endswith('.png')
                    keyword = subfolder
                    number = counter
                    extension = os.path.splitext(name)[1][1:]
                    new_name = keyword + str(number) + '.' + extension
                    os.rename(os.path.join(subfolder_path, name), os.path.join(subfolder_path, new_name))
                    counter += 1


def merge_files(new_data_path, input_path, output_path):
    new_data_dirs = [d for d in os.listdir(new_data_path) if os.path.isdir(os.path.join(new_data_path, d))]

    for i in range(len(new_data_dirs)):
        new_data_dirs[i] = new_data_path + "\\" + new_data_dirs[i]

    len_class = len(new_data_dirs)
    input_dirs = [d for d in os.listdir(input_path) if os.path.isdir(os.path.join(input_path, d))]
    output_dirs = [d for d in os.listdir(output_path) if os.path.isdir(os.path.join(output_path, d))]

    for i in range(len(input_dirs)):
        input_dirs[i] = input_path + "\\" + input_dirs[i]

    for i in range(len(output_dirs)):
        output_dirs[i] = output_path + "\\" + output_dirs[i]
    for i in range(len_class):
       
        for filename in os.listdir(input_dirs[i]):
            if filename.endswith(".jpg"): 
                src_path = os.path.join(input_dirs[i], filename)
                dst_path = os.path.join(new_data_dirs[i], filename)
                shutil.copyfile(src_path, dst_path)

        for filename in os.listdir(output_dirs[i]):
            if filename.endswith(".jpg"):  
                src_path = os.path.join(output_dirs[i], filename)
                dst_path = os.path.join(new_data_dirs[i], filename)
                shutil.copyfile(src_path, dst_path)
if name == "__main__":

    input_path = r"C:\Users\STARRY\PycharmProjects\pythonProject1\data"# 原数据集路径
    output_path = r"C:\Users\STARRY\PycharmProjects\pythonProject1\data2" # 反转后存放数据集的路径
    new_data_path = r"C:\Users\STARRY\PycharmProjects\pythonProject1\data3" # 最终两个数据集合并后的路径

    data_aug(input_path, output_path,  new_data_path)

 结果

epoch=10

epoch=20

 建立更好的神经网络

1.可以使用ResNet50或者VGG16网络模型来替代

2.这里我是直接在原有的网络结构基础上加了

self.dropout = nn.Dropout(p=0.3)
self.conv4 = nn.Conv2d(128,256,kernel_size=3)
self.pool4 = nn.MaxPool2d(kernel_size=2)

代码

(只有神经网络部分做了改动)

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3,16,kernel_size=3)
        self.bn1 = nn.BatchNorm2d(16)
        self.pool1 = nn.MaxPool2d(kernel_size=2)
        self.dropout = nn.Dropout(p=0.3)

        self.conv2 = nn.Conv2d(16,32,kernel_size=3)
        self.bn2 = nn.BatchNorm2d(32)
        self.pool2 = nn.MaxPool2d(kernel_size=2)
        self.dropout = nn.Dropout(p=0.3)

        self.conv3 = nn.Conv2d(32,128,kernel_size=3)
        self.bn3 = nn.BatchNorm2d(64)
        self.pool3 = nn.MaxPool2d(kernel_size=2)
        self.dropout = nn.Dropout(p=0.3)

        self.conv4 = nn.Conv2d(128,256,kernel_size=3)
        self.pool4 = nn.MaxPool2d(kernel_size=2)
        self.fc1 = nn.Linear(36864, 256)
        self.fc2 = nn.Linear(256, num_classes)


    def forward(self, x):
        x = self.pool1(F.relu(self.conv1(x)))
        x = self.dropout(x)
        x = self.pool2(F.relu(self.conv2(x)))
        x = self.dropout(x)
        x = self.pool3(F.relu(self.conv3(x)))
        x = self.dropout(x)
        x = self.pool4(F.relu(self.conv4(x))
        x = torch.flatten(x, start_dim=1)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return x

结果

epoch=20

这里最高是到了85.4%

调整一些参数

可以调节优化器的学习速率以及batc_size的大小去提高准确度

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

7月网络学习报告 的相关文章

  • Java中类数组,创建后使用set函数,报NullPointerException空指针异常

    最近从新学习数组发现了一些问题 先创建一个Person类 public class Person private String name private int age public Person String name int age t
  • 线程状态是五种对?还是六种对?

    五种 线程在一定条件下 状态会发生变化 线程一共有以下几种状态 1 新建状态 New 新创建了一个线程对象 2 就绪状态 Runnable 线程对象创建后 其他线程调用了该对象的start 方法 该状态的线程位于 可运行线程池 中 变得可运
  • 推荐系统系列——推荐系统简介

    目录 演化关系图 推荐系统简介 什么是推荐系统 为什么需要推荐系统 如何构建推荐系统 推荐系统的步骤 常用评测指标 召回与排序 召回层与排序层的特点 多路召回 使用Embedding做召回 A B测试 为什么需要A B测试 A B测试的流程
  • 基于神经回路的靶向治疗的未来

    以靶向大脑回路为原则的治疗方法 随着诸如经颅磁刺激 TMS 深部脑刺激 DBS 和聚焦超声 FUS 等脑刺激治疗的发展 逐渐引起了广泛关注 这些技术可以有效治疗不同的神经精神疾病 但治疗特定疾病取决于选择合适的治疗目标 在这里 我们提出了一
  • 删除type报ORA-02303错误

    drop type result type 时 报错ORA 02303 无法使用类型或表的相关性来删除或取代一个类型 drop type result type array 时报错 对象不存在 CREATE OR REPLACE TYPE
  • 练习敲代码速度

    2023年9月18日 周一晚上 今晚不想学习 但又不想玩游戏 于是找了一些练习敲代码的网站来玩玩 顺便练习一下敲代码的速度 目录 参考资料 个人推荐 第一个 第二个 第三个 参考资料 电脑打字慢 有哪些比较好的练打字软件 知乎 https
  • C#——Lambda 表达式

    C Lambda 表达式 Lambda 表达式 是采用以下任意一种形式的表达式 表达式 lambda 表达式为其主体 input parameters gt expression 语句 lambda 语句块作为其主体 input param
  • 分布式相关论文

    想从事分布式系统 计算 hadoop等方面 需要哪些基础 推荐哪些书籍 转自知乎 作者 廖君 链接 https www zhihu com question 19868791 answer 88873783 来源 知乎 分布式系统 Dist
  • 线性代数学习之正交性,标准正交矩阵和投影

    正交基和标准正交基 前言 经过上一次线性代数学习之向量空间 维度 和四大子空间的学习 对于空间的概念已经有了非常深刻的认识了 而描述空间很重要的方式除了维度以外 那就是空间的基了 而如小标题所示就是跟空间的基相关 所以先来回忆一下空间基的相
  • autojs获取最近创建的媒体文件,获取本机音频视频图片文件脚本源码,翻译自java

    说明 本文提供的代码仅供参考 不建议用于生产环境 可能有些地方在最新版本的Auto js上面需要做修改 才能运行 Auto js简介 Auto js是利用安卓系统的 辅助功能 实现类似于按键精灵一样 可以通过代码模拟一系列界面动作的辅助工作

随机推荐

  • 宋人千首绝句【全十卷】

    千首宋人绝句 是清代严长明编辑的书籍 全书共十卷 分七言 五言 六言三部分 其中七言七卷 五言两卷 六言一卷 且按帝王 后妃 宫掖 宗室 降王 宋臣 闺媛等分类 收录有王安石 苏轼 黄庭坚 秦观 陆游 杨万里 范成大等著名诗人的六言绝句 编
  • 看了一次strongswan ipsec的设置.

    看了一次strongswan ipsec的设置 这次的设置要求是 Linux 中 strongwans与hillstone防火墙 stoneOS 建立ipsec连接 network network进行通信 要求Linux可以同时与多台防火墙
  • 从2018年以太坊统计数据看区块链发展趋势

    今年6月 我们发布了 以太坊网络状态 重点介绍了整个网络的一些关键数据和统计数据 六个月后 即将在2018年结束时 我们处于长期 加密货币冬天 的尾声 2017年末至今的市场波动已经引起了区块链行业的普遍关注 然而 仔细研究这些数字可以发现
  • Python实现根据磁盘剩余空间对磁盘多次写入和擦除

    实现根据磁盘剩余容量 对剩余容量 预留了1GB 进行多次的写入和删除数据 次数为变量counts 每次写入1GB的数据 即变量data 多次操作 以实现上述功能 通过更改taskTimes变量可以多次写入和删除 from datetime
  • 基于STM32的智能电子秤设计

    硬件设计 本设计是一款基于STM32单片机的电子秤系统 随着科学技术的不断发展 传统的机械秤逐渐被电子秤所取代 相比于计量不精确 费时费力的机械秤 电子秤采用在方便快捷的同时 又保证了结果的准确性 本次设计采用STM32单片机作为处理器 控
  • 03智慧安防

    一张图读懂一个产业之智慧安防 自2015年起 安防行业逐渐引入人工智能技术 智慧安防 一词开始进入大众视野 伴随着政府 平安城市 天网工程 雪亮工程 等项目不断推出 智慧安防快速成为智慧城市应用中落地情况较好 技术与服务相对成熟的领域之一
  • java 实现部门树_Java实现部门模块开发

    一 新增部门接口开发 1 1 DeptParam java 1 2 LevelUtils java 1 4 1 导入 commons lang3 依赖包 1 2 2 实现LevelUtils开发 1 3 在 com yuluomoshang
  • 物联网设备获取北京时间、年月日、星期几,GMT格林威治标准时间转换为北京时间,授时api Fiddler抓包调试

    1 获取北京时间 年月日 授时api 苏宁获取北京时间的api不要太方便 http quan suning com getSysTime do 使用 Fiddler抓包调试 查看HTTP返回报文 双击左侧抓取到的HTTP返回报文 使用 Sy
  • 同步异步BUCK研究

    目录 一 同步时钟 二 异步BUCK电路 1 基本公式推导 2 电感选型计算 三 同步BUCK电路 四 同步异步BUCK电路对比 前言 在硬件设计中 电源模块基本都会接触到 DC DC拓扑电路又是最常见的 所以深入理解DC DC电路至关重要
  • 轻松成为设计高手

    目录 2 Verilog语言基础 2 1 三种描述方法 2 Verilog语言基础 2 1 三种描述方法 1 数据流描述 assign连续赋值语句 2 行为描述 过程赋值语句 always和initial过程块 3 结构化描述 实例化已有的
  • 微服务(SpringCloud)

    1 什么是微服务 将一个大项目中各个业务代码进行拆分 拆分成多个互不相干小项目 每个项目完成自己特有的功能 而且可以通过调用别的项目完成整体功能 2 SpringCloud 是由Spring提供的一套能够快速搭建微服务框架程序的框架集 也被
  • WEB漏洞测试(二)——HTML注入 & XSS攻击

    上一篇介绍了我们安装BWAPP来完成我们的漏洞测试 在BWAPP中 将HTML Injection和XSS做了非常详细的分类 那么为什么要将两个一起讲呢 归根结底 我觉得这两个分明是一个玩意 充其量是攻击的方式不一样 我们先来介绍一下这两种
  • Electron入门应用打包exe(windows)

    最近在学习nodejs 得知Electron是通过将Chromium和Node js合并到同一个运行时环境中 用HTML CSS和JavaScript来构建跨平台桌面应用程序的一门技术 对于之前一直从事flash AIR桌面应用开发的我迫不
  • 【网络】交换机 VLAN 网关 路由器

    网关 含义 网间连接器 协议转换器 在传输层上实现网络互连 PS 二层交换机在链路层 路由 三层交换机在网络层 集线器 中继器在物理层 是最复杂的网络互联设备 仅用于两个高层协议不同的网络互连 网关有很多种 最常用的是TCP IP协议里的网
  • DDoS攻击原理及防御

    转自 微点阅读 https www weidianyuedu com 随着网络时代的到来 网络安全变得越来越重要 在互联网的安全领域 DDoS Distributed DenialofService 攻击技术因为它的隐蔽性 高效性一直是网络
  • matlab自回归模型AIC,时间序列笔记-自回归模型(二)

    笔记说明 在datacamp网站上学习 Time Series with R track Introduction to Time Series Analysis 课程 做的对应笔记 学识有限 错误难免 还请不吝赐教 如无特殊说明 笔记中所
  • gcc常见编译参数介绍

    1 常见编译参数介绍 gcc可以说是个伟大的编译器集合 支持c c object c java fortran pascal ada等一大堆语言 同时支持几乎所有32位以上的cpu和部分16位 8位cpu 因此几乎所有开源操作系统 商业un
  • uniapp微信小程序 ios端部分机型屏幕可左右滑动原因即处理

    1 原因 因为部分元素超过了屏幕尺寸大小 2 处理 在超出屏幕尺寸的元素上一级使用 width 100 overflow x hidden 如果是图片导致的 则需要把多余的裁剪掉
  • ubuntu虚拟机搭建hadoop完全分布式集群

    一 需要的工具 需要的工具我已经完成分享 需要的可以直接在网盘中下载 VMware15 Workstation Pro 提取码 pp12 ubuntu16 18 19 镜像 提取码 yfj0 Xshell Xftp 提取码 6ao9 jdk
  • 7月网络学习报告

    原始代码 import torch import torch nn as nn import torch nn functional as F import torchvision from torchvision import datas