1.12学习日记

javaWeb——日记本系统 日记本系统 写在前面 系统采用传统的Jsp+Servlet+Model的MVC开发模式,前端采用主流的BootStrap技术,数据库采用Mysql,实现了个人日记本系统,亮点是Bootstrap的综合运用,ckeditor的运用以及FileUpload组件上传图片,以及MD5加密的应用(该项目是非本人开发,只是学习其中的知识); 一、需求: 登陆注册 日记的增删该查 日记分类(增删改查) 个人中... 阅读详情

前两天学校有课加上要回家所以没学习,今天开始继续学习(●ˇ∀ˇ●)

今天学第五节下:图片分类半监督

一、机器学习

        监督学习(Supervised Learning)是机器学习的一种方法,在这种方法中,模型通过学习带有标签的训练数据来进行预测或分类。换句话说,监督学习的任务是根据一组已知输入和相应的输出(标签),学习一个函数或模型,以便在面对新的、未知的输入时能够预测出对应的输出。

        无监督学习(Unsupervised Learning)是机器学习的一种方法,与监督学习不同,无监督学习不依赖于标注的数据。它的目标是从未标注的输入数据中提取结构或模式,而不是预测具体的标签或输出。

        半监督学习(Semi-supervised Learning) 是介于监督学习和无监督学习之间的一种机器学习方法。它结合了少量标注数据和大量未标注数据,用于训练机器学习模型。这种方法主要用于当标注数据很昂贵、获取困难或耗时,而未标注数据较容易获得的情境。

        半监督学习之中,无标签数据通过模型以预测值作为真实值,当作有标签数据

二、项目思路

  1. 把无标签数据读作数据集
  2. 从无标签数据集中取一批数据,通过模型得到预测值,包括置信度(概率)和标签。如果置信度大于某一值,就把其标签和x加入新的数据集semi_dataset(用于储存无标签数据集中打上标签的数据)
  3. 把semi_dataset当作有标签数据集进行训练

import random
import torch
import torch.nn as nn
import numpy as np
import os
from PIL import Image #读取文件数据
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm  #查看读取进度
from torchvision import transforms
import time
import matplotlib.pyplot as plt
from model_utils.model import initialize_model

def seed_everything(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True
    random.seed(seed)
    np.random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
#################################################################
seed_everything(0)
###############################################


HW = 224 #深度学习领域一般让图片大小为224,而文件中的图片是512*512



#数据变换   训练集和验证集的数据变换不同,验证和测试的时候要用原图,训练的时候才需要不同的数据变换进行训练
train_transform = transforms.Compose(
    [
        transforms.ToPILImage(),    #图片为224*224*3,模型需要3*224*224
        transforms.RandomResizedCrop(224),  #对图片随机放大裁切
        transforms.RandomRotation(50),  #对图片50°以内随机旋转
        transforms.ToTensor()   #变为张量进行模型运行
    ]
)

val_transform = transforms.Compose(
    [
        transforms.ToPILImage(),    #图片为224*224*3,模型需要3*224*224
        transforms.ToTensor()   #变为张量进行模型运行
    ]
)



#定义数据集
class food_Dataset(Dataset):
    def __init__(self, path, mode="train"):    #初始化,传入地址,得到数据集x和标签y
        self.mode = mode
        if mode == "semi":
            self.X = self.read_file(path)
        else:
            self.X, self.Y = self.read_file(path)
            self.Y = torch.LongTensor(self.Y)  #标签转为长整型
        if mode == "train":
            self.transform = train_transform   #数据增广
        else:
            self.transform = val_transform

    # 读文件
    def read_file(self, path):
        if self.mode == "semi":
            for i in tqdm(range(11)):
                file_list = os.listdir(path)  # 列出文件夹下所有文件名字
                xi = np.zeros((len(file_list), HW, HW, 3), dtype=np.uint8)  # 读为整型
                for j, img_name in enumerate(file_list):  # enumerate()既可以读到下标,也可以读到内容
                    img_path = os.path.join(path, img_name)
                    img = Image.open(img_path)
                    img = img.resize((HW, HW))
                    xi[j, ...] = img  # ...表示后面的维度表示一致,把图片放到第j个
                    print("读到了%d个数据" % len(xi))
                    return xi
        else:
            for i in tqdm(range(11)):
                file_dir = path + "/%02d" % i
                file_list = os.listdir(file_dir)  # 列出文件夹下所有文件名字

                xi = np.zeros((len(file_list), HW, HW, 3), dtype=np.uint8)  # 读为整型
                yi = np.zeros(len(file_list), dtype=np.uint8)

                for j, img_name in enumerate(file_list):  # enumerate()既可以读到下标,也可以读到内容
                    img_path = os.path.join(file_dir, img_name)
                    img = Image.open(img_path)
                    img = img.resize((HW, HW))
                    xi[j, ...] = img  # ...表示后面的维度表示一致,把图片放到第j个
                    yi[j] = i  # 标签

                # 把所有的xi,yi在0维合并
                if i == 0:
                    X = xi
                    Y = yi
                else:
                    X = np.concatenate((X, xi), axis=0)
                    Y = np.concatenate((Y, yi), axis=0)

            print("读到了%d个数据" % len(Y))
            return X, Y

    def __getitem__(self, item):
        if self.mode == "semi":
            return self.transform(self.X[item]), self.X[item]
        else:
            return self.transform(self.X[item]), self.Y[item]

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

class semiDataset(Dataset):
    def __init__(self, no_label_loader, model, device, thres=0.99):
        x, y = self.get_label(no_label_loader, model, device, thres)
        if x == []:
            self.flag = False

        else:
            self.flag = True
            self.X = np.array(x)
            self.Y = torch.LongTensor(y)
            self.transform = train_transform

    def get_label(self,no_label_loader, model, device, thres):
        model = model.to(device)
        pred_prob = []
        labels = []
        x = []
        y = []
        soft = nn.Softmax()
        with torch.no_grad():
            for bat_x, _ in no_label_loader:
                bat_x = bat_x.to(device)
                pred = model(bat_x)
                pred_soft = soft(pred)
                pred_max, pred_value = pred_soft.max(1)
                pred_prob.extend(pred_max.cpu().numpy().tolist())
                labels.extend(pred_value.cpu().numpy().tolist())

        for index, prob in enumerate(pred_prob):
            if prob > thres:
                x.append(no_label_loader.dataset[index][1])    #调用到原始的getitem
                y.append(labels[index])
        return  x, y

    def __getitem__(self, item):
        return self.transform(self.X[item]), self.Y[item]
    def __len__(self):
        return len(self.X)

def get_semiloader(no_label_loader, model, device, thres):
    semiset = semiDataset(no_label_loader, model, device, thres)
    if semiset.flag == False:
        return None
    else:
        semi_loader = DataLoader(semiset, batch_size=16, shuffle=False)
        return semi_loader

#模型
class myModel(nn.Module):
    def __init__(self, num_class):  #搭建模型框架
        super(myModel, self).__init__()
        #图片输入为3*224*224,要变为512*7*7,然后拉直、全连接、分类
        self.conv1 = nn.Conv2d(3, 64, 3, 1, 1)   #64*224*224
        self.bn1 = nn.BatchNorm2d(64)   #归一化
        self.relu = nn.ReLU()
        self.pool1 = nn.MaxPool2d(2)    #64*112*112

        self.layer1 = nn.Sequential(    #这样合并更方便,且美观
            nn.Conv2d(64, 128, 3, 1, 1),   #128*112*112
            nn.BatchNorm2d(128),   #归一化
            nn.ReLU(),
            nn.MaxPool2d(2)    #127*56*56
        )

        self.layer2 = nn.Sequential(
            nn.Conv2d(128, 256, 3, 1, 1),
            nn.BatchNorm2d(256),
            nn.ReLU(),
            nn.MaxPool2d(2)    #256*28*28
        )

        self.layer3 = nn.Sequential(
            nn.Conv2d(256, 512, 3, 1, 1),
            nn.BatchNorm2d(512),
            nn.ReLU(),
            nn.MaxPool2d(2)  #512*14*14
        )

        self.pool2 = nn.MaxPool2d(2)    #512*7*7
        self.fc1 = nn.Linear(25088, 1000)   #卷积 25088->1000
        self.relu2 = nn.ReLU()
        self.fc2 = nn.Linear(1000, num_class)   #1000->num_class(11)


    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.pool1(x)
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.pool2(x)
        x = x.view(x.size()[0], -1)     #拉直
        x = self.fc1(x)
        x = self.relu2(x)
        x = self.fc2(x)
        return x


#训练函数
def train_val(model, train_loader, val_loader, no_label_loader, device, epochs, optimizer, loss, thres, save_path):
    model = model.to(device)
    semi_loader = None

    plt_train_loss = [] #记录所有轮次的loss
    plt_val_loss = []

    plt_train_acc = []  #记录准确率
    plt_val_acc = []

    max_acc = 0.0   #保存准确率最高的模型

    for epoch in range(epochs):   #冲锋的号角
        train_loss = 0.0
        val_loss = 0.0
        train_acc = 0.0
        val_acc = 0.0
        semi_loss = 0.0
        semi_acc = 0.0
        start_time = time.time()

        model.train()     #模型调为训练模式
        for batch_x, batch_y in train_loader:
            x, target = batch_x.to(device), batch_y.to(device)
            pred = model(x)
            train_bat_loss = loss(pred, target)
            train_bat_loss.backward()
            optimizer.step() #更新模型的作用
            optimizer.zero_grad()
            train_loss += train_bat_loss.cpu().item()
            train_acc += np.sum(np.argmax(pred.detach().cpu().numpy(), axis=1) == target.cpu().numpy())
        plt_train_loss.append(train_loss / train_loader.__len__())
        plt_train_acc.append(train_acc / train_loader.dataset.__len__())    #记录准确率

        if semi_loader != None:
            for batch_x, batch_y in semi_loader:
                x, target = batch_x.to(device), batch_y.to(device)
                pred = model(x)
                semi_bat_loss = loss(pred, target)
                semi_bat_loss.backward()
                optimizer.step() #更新模型的作用
                optimizer.zero_grad()
                semi_loss += train_bat_loss.cpu().item()
                semi_acc += np.sum(np.argmax(pred.detach().cpu().numpy(), axis=1) == target.cpu().numpy())
            print("半监督的数据集的训练准确率为",semi_acc/train_loader.dataset.__len__())


        model.eval()
        with torch.no_grad():
            for batch_x, batch_y in val_loader:
                x, target = batch_x.to(device), batch_y.to(device)
                pred = model(x)
                val_bat_loss = loss(pred, target)
                val_loss += val_bat_loss.cpu().item()
                val_acc += np.sum(np.argmax(pred.detach().cpu().numpy(), axis=1) == target.cpu().numpy())
        plt_val_loss.append(val_loss/ val_loader.__len__())
        plt_val_acc.append(val_acc / val_loader.dataset.__len__())

        if epoch % 3 == 0 and plt_val_acc[-1] > 0.6:
            semi_loader = get_semiloader(no_label_loader, model, device, thres)

        if val_acc > max_acc:
            torch.save(model, save_path)
            max_acc = val_loss

        print("[%03d/%03d] %2.2f sec(s) Trainloss: %.6f |Valloss: %.6f Trainacc: %.6f |Valacc: %.6f" % \
              (epoch, epochs, time.time()-start_time, plt_train_loss[-1], plt_val_loss[-1], plt_train_acc[-1], plt_val_acc[-1]))


    plt.plot(plt_train_loss)
    plt.plot(plt_val_loss)
    plt.title("loss")
    plt.legend(["train", "val"])
    plt.show()

    plt.plot(plt_train_acc)
    plt.plot(plt_val_acc)
    plt.title("acc")
    plt.legend(["train", "val"])
    plt.show()


# path = r"D:\大学\学习\深度学习\课程代码\第四五节_分类代码\food_classification\food-11\training\labeled"   #训练数据的路径,r能去除转义字符的作用
# train_path = r"D:\大学\学习\深度学习\课程代码\第四五节_分类代码\food_classification\food-11\training\labeled"
# val_path = r"D:\大学\学习\深度学习\课程代码\第四五节_分类代码\food_classification\food-11\validation"
train_path = r"D:\大学\学习\深度学习\课程代码\第四五节_分类代码\food_classification\food-11_sample\training\labeled"
val_path = r"D:\大学\学习\深度学习\课程代码\第四五节_分类代码\food_classification\food-11_sample\validation"
no_label_path = r"D:\大学\学习\深度学习\课程代码\第四五节_分类代码\food_classification\food-11_sample\training\unlabeled\00"
#读数据集
train_set = food_Dataset(train_path, "train")
val_set = food_Dataset(val_path, "val")
no_label_set = food_Dataset(no_label_path, "semi")
train_loader = DataLoader(train_set, batch_size=16, shuffle=True)    #train_loader把train_set变为一批数据
val_loader = DataLoader(val_set, batch_size=16, shuffle=True)
no_label_loader = DataLoader(no_label_set, batch_size=16, shuffle=False)    #shuffle一定要等于false,因为是对无标签数据进行预测



# model = myModel(11)

#用大佬们的模型
# from torchvision.models import resnet18
# model = resnet18(pretrained=True)   #pretrained=True用架构和参数,=False时则从0开始训练
# in_features = model.fc.in_features      #替换分类头
# model.fc = nn.Linear(in_features, 11)   #把模型的分类头改为自己的输入维度11

#引用模型
# model = initialize_model("resnet18", 11, use_pretrained=True)
model, _ = initialize_model("vgg", 11, use_pretrained=True)

lr = 0.001  #学习率
loss = nn.CrossEntropyLoss()   #损失用交叉熵损失
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4)  #优化器
device = "cuda" if torch.cuda.is_available() else "cpu" #设备
save_path = "model_save/best_model_zhou.pth"   #保存最好的模型
epochs = 15     #训练轮次
thres = 0.99

train_val(model, train_loader, val_loader, no_label_loader, device, epochs, optimizer, loss, thres, save_path)

java编写日记本 System.out.println("指令4代表“保存”,如果是新建的日记本需要保存,则将日记本保存到您输入的路径;System.out.println(“指令3代表“修改日记本”,修改日记时,既可以修改新建日记本的内容,也可以修改已打开日记本的内容”);System.out.println(“指令2代表“打开日记本”,读取指定路径的txt文件的内容并输出到控制台”);(3) 指令3代表“修改日记本”,修改日记时,既可以修改新建日记本的内容,也可以修改已打开日记本的内容。 阅读详情

相关推荐

学习笔记——神经科学的数学基础

m%3D2X_%7Bi%7DiNy%3DAxW%3DABx_%7Bj%7Dy_%7Bi%7Dy%3DWxt=N7T8卷积神经网络(CNN)详细介绍及其原理详解_IronmanJay的博客-优快云博客https://blog.csdn.net/IronmanJay/article/details/128689946?

zxyopenstar的博客 1374

odoo12学习日记1——odoo12安装与入门学习网址推荐

我的系统是win7,装的postgresql10版本和odoo12 安装因为我安装东西非常容易出错所以是选择看视频安装。 http://url.cn/5SLZBDY 虽然还是遇到了问题。。。 入门学习推荐是 https://segmentfault.com/u/ruter 和 https://blog.csdn.net/sunansheng/category_9265343.html 前面那位大佬...

m0_46347995的博客 180

动态刷新曲线_【GhPython应用】利用反射刷新Image sampler组件

【版权声明】| 作者:月之眼|案例图片来源:Sergiu Radu Pop的facebook| 如有侵权,请联系大水牛平台|如果觉得文章不错,欢迎分享效果展示利用python刷新Image sampler组件,主要的思路就是X输入端:输入要切换的图片路径,我的案例中输入了9张图片。然后通过100毫秒切换一张图片显示,来达到动态显示效果。代码分析run输入端类型:bool (I...

weixin_42393829的博客 531

学习日记(1.12)

学习日记(关于对hash的粗略了解和kmp的继续深入)

qq_74455082的博客 111

HX720/HX711 数据采集实战:从硬件配置到姿态解析(附源码详解)

本文详细解析了HX720/HX711数据采集传感器的硬件配置与姿态解析实战技巧,包括选型指南、电路设计避坑、抗干扰方案及源码实现。通过优化驱动代码和数据处理算法,提升采样率与精度,适用于动态称重和工业检测等场景。附源码详解,助力开发者快速掌握高精度数据采集技术。

weixin_30752699的博客 655

NDIAurora 6D、5D传感器裸线焊接与烧录 6D传感器型号:10001742;5D传感器型号:610157

NDI Aurora 6D、5D传感器裸线焊接与烧录

yanghong2000719的博客 1201

2023-12-1学习日记

阿里云通义千问开源了一系列大模型,包括参数量为18亿、70亿、140亿和720亿的四款基础开源模型。这些模型在中文任务上表现出色,尤其在复杂语义理解和逻辑推理方面有很强的能力。开源模型的优势包括更强的中文能力、降低成本、可定制性和丰富的生态系统。

qq_19986067的博客 95

AT91SAM9260搭建LINUX操作系统

一、 编写目的 2 二、 系统搭建 2 1. 下载相关软件包 2 2. Bootstrap编译 3 3. U-BOOT编译 5 4. LINUX编译 7 5. 通过U-BOOT的TFTP命令从TFTP服务器下载系统镜像 9 6. 文件系统制作 10 7. 挂载NFS作为根文件系统 10 三、 总结 14 一、编写目的 本文档用于记录AT91SAM9260 LINUX学

lshiceman的专栏 7412

学习日记12--python练习1

9.30 开始学习python练习&是位运算符, and 才是逻辑运算符,表示“和”。注意区别取余 mod 的运算符是 //list.append[object] 返回的是none,原list末尾自动加一个元素取list长度用len(list)itertools 模块中的permutation函数和combination函数,前者是排列后者是组合。返回值是iterators(迭代器), 所...

dershine的博客 306

vivado下ECO操作-不重新综合实现修改属性并生成.bit

ECO即engineer change order,即工程变更指令,可以对设计做局部小改动并只对改动部分重新布局布线并生成.bit。在一个工程动辄编译几个小时情况下,可以在调试中节省大量时间。比如我们在调试中,需要改变时钟占空比或者相位,需要改变寄存器初值等等,此时用ECO暂时改动,待验证后在重新编译无疑是最有效率的方法。 实现ECO通常有两种方式,一是通过vivado界面完成,另一种方法就是tcl脚本。所有的ECO操作都可以通过tcl操作完成,有的操作用vivado界面无法完成,只能通过tcl。以下主要

4657

《UDS协议从入门到精通》系列——图解0x23:通过地址读取内存

如何读取ECU中指定内存地址的数据?图解UDS 0x23服务带你快速上手!!

车载系统攻城狮 2623

JAVA学习日记1——配置JDK12,连接Access数据库

配置JDK12 官网下载链接: https://www.oracle.com/technetwork/java/javase/downloads/index.html jdk12不会自动安装jre,在安装目录下打开cmd运行:bin\jlink.exe --module-path jmods --add-modules java.desktop --output jre 手动生成jre c...

junior_programmer的博客 750

【30天从零玩转AI应用开发】第16篇:智能体Agent入门——ReAct框架原理+首个会思考、会动手的AI实战

摘要: 本文介绍了AI智能体(Agent)的核心概念及其与普通大模型(LLM)的区别。通过ReAct(Reason+Act)框架,智能体实现了自主思考、调用工具和分步执行的能力。文章详细讲解了LangChain Agent的四大组件,并推荐新手使用ZERO_SHOT_REACT_DESCRIPTION类型。最后提供了一个完整的智能体实战代码示例,该智能体具备数学计算和天气查询功能,能够自主选择工具完成任务,展示了AI从”被动回答“到”主动行动“的关键进化。

在上海谋生的软件喵记录喵生 626

【java学习日记】【2025.12.1】[1/60]

这里的二分,判断能否正常canRun()函数的两个条件关键。

qq_64012735的博客 359

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Direct12的学习日记(1)基础知识

1. 何为D3DD3D英文全称Direct3D,是一个低层的图形API,其用于控制和编程GPU(图形处理单元),故我们可以渲染出一个人造的3D世界。举例,如果我们想要通过一个命令来清理渲染目标,比如显示屏上内容,可以调用D3D的方法:ID3D12CommandList::ClearRenderTargetView;D3D层和硬件驱动就会通过GPU将命令转换为机器指令。 2. COM(Compone...

qq_42040849的博客 490

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

java学习日记1-安装jdk12,配置环境变量

java学习日记1-安装jdk12,配置环境变量

qq_41949967的博客 275

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

菜鸡学习日记的大一年度项目——数据库操作学习日记-1.12又是咕的一天

1.12去市中心买一些带回家的东西,又玩了一下午。 晚上打算把之前写爆的走迷宫程序弄得正常运行 所以。。。。今天还是没有开始学数据库操作。。。。。。。...

qq_42954464的博客 139

学习日记12.1——Android kotlin 图形验证码的转换

三行代码实现二进制数据流转图形验证码

m0_68044873的博客 1084

黑马程序员_Java学习日记12_IO流1

----------------------android培训、java培训、期待与您交流! --------------------- 1.IO流概述(Input,Output) IO流用来处理设备之间的数据传输,Java对数据的操作是通过流的方式,Java用于操作流的对象都在IO包中 流按操作数据分为两种:字节流和字符流 流按流向分为:输入流,输出流 字符流的由来: a 9

cdestiny的专栏 470

学习日记1/12坏日子(气死我了)

没啥,kmp

jdjdhdha的博客 122

用计算机学数学日记,【精华】小学生数学日记十篇

【精华】小学生数学日记十篇小学生数学日记 篇1在生活中,我们大家会遇到很多难题,大家遇到难题时是退缩了还是把他解决了呢?今天,我被一道数学题给难住了,这道是将112这12个数填入右图的12个空格里,使横行、竖行上面每个正方形里的四个数和都等于26.夜幕降临,我坐在台灯下左思右想,把十二个数字搬来搬去,不是竖的不对,就是横的不对,怎么也不对,怎么办呢?十分钟,二十分钟…….半个小时过去了,我真想放弃...

weixin_40002238的博客 424

我的日记V1.0

我的日记V1.0 文件信息:大小: 3878400 字节 文件版本: 1.0.0.1修改时间: 2018年5月25日, 2:30:46 MD5: 969D1FF525B94D739D22DB2E32897BAF SHA1: DEECB05274749F30AEB7C1F0C7A1F34AC8C111FE CRC32: 382A9455说明:本软件没有技术含量,只做入门学习交流使用!我的日记...

蓝头网络 600

项目大作业之日记本系统1

题目:       日记本系统 1          1 功能需求及技术可行性分析 日记本是我们从小到大一直在我们身边的好朋友,它记载着你的每一天,包括你的衣食住行,包含着你的喜怒哀乐,承载着你成长的气息。可以说,日记本是最了解你的“人”,它一直在默默倾听着你的心声。但是随着时间的流逝和科技的进步,纸质版的日记本已经不能满足于人们的需求,携带不方便,保密性差等缺点一点点的暴露出来,而我的这

qq_35612861的博客 1338

BUUCTF_REVERSE_学习日记

拖入DIE中检测,64位,无壳在ida64中打开,< shift + F12 >定位到含有flag的字符串按< R >将关键数字转化为字符串后分析伪码我们可以看出伪码的关键部分是5种case,这里可以发现case2和case3啥也不是,case1是最后输出flag,case4是定义f2,case5是对f2进行处理,所以我们可以得出case的顺序:case4->case5->case1。

2401_87875879的博客 852

java日记系统

IDE相关视频讲解:C语言程序设计入门之环境安装Java日记系统科普 在当今社会,日记作为一种记录生活、表达情感的方式,被越来越多的人喜爱和使用。然而,传统的纸质日记本存在着易丢失、难保存、不易查找等问题。为了解决这些问题,我们可以利用现代科技,建立一个基于Java语言的日记系统,方便用户随时记录、查找和分享自己的日记内...

weixin_37072113的博客 251

oracle日记账导出,OracleEBSR12GL日记账业务操作01:日记账批录入

OraEBSR1201登录OraEBSR1202添加收藏夹OraEBSR1203快捷键查询和保存OraEBSR1204提交请求查看请求结果OraEBSR1205修改密码和个人ProfileOraEBSR1206个人文件夹OraEBSR12GL日记账业务操作01:日记账批录入OraEBSR12GL日记账业务操作02:日记账录入OraEBSR12GL日记账业务操作03:日记账编辑OraEBSR12GL...

weixin_42186728的博客 678
上一篇: 1.9学习日记
下一篇: 1.14学习日记
紫薯粥zzz
博客等级 码龄5年 32粉丝 12原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值