C#文件操作

C#文件操作集合三(文件及目录的创建和删除) 文件操作是开发过程中经常遇到的,如何创建文件、处理文件、保存文件以及读取文件这些工作是每一位开发都必须经历的。本节整理了文件及目录的创建、获取和删除。主要使用了File类和Dictionary类。 阅读详情
AI摘要

本文详细介绍了C#中关于文件夹创建、Path路径配置、文件读写、磁盘操作和文档序列化的常用函数和示例代码,包括Directory和Path类的方法,如CreateDirectory、GetPathRoot、ReadAllLines等,以及二进制、XML和Json的序列化与反序列化操作。

目录

一、文件夹创建

二、Path 路径配置

三、文件读写

四、磁盘操作

五、文档序列化


一、文件夹创建

常用函数:

Directory.Exists(path)                       -- 此文件夹是否存在
Directory.CreateDirectory(path)     -- 创建文件夹
Directory.Move(path_a, path_b)     -- 文件夹剪切
Directory.Delete(path)                       -- 只可删除空文件夹,若删除非空文件夹,会报异常
Directory.Delete(path, true)              -- 删除文件夹,包括里面的文档 

例程: 

internal class Program
{
    static void Main(string[] args)
    {
        string path_A = @"C:\\Temp\\A";
        string path_B = @"C:\\Temp\\B";

        if (!Directory.Exists(path_A)) //若此文件夹不存在
        {
            Directory.CreateDirectory(path_A); //创建此文件夹
            Directory.Move(path_A, path_B); //A文件夹剪切成B
            Directory.Delete(path_B, true); //删除B文件夹 
        }
    }
}

二、Path 路径配置

 常用函数:

Path.GetPathRoot(path)               -- 获取根目录
Path.GetDirectoryName(path)     -- 获取文件路径名
Path.GetFileNameWithoutExtension(path) -- 获取文件名 不包含后缀
Path.GetExtension(path)               -- 获取文件后缀
Path.GetFileName(path)                 -- 获取文件名 包含后缀
Path.GetFullPath(path)                   -- 获取文件绝对路径
Path.ChangeExtension(path, "text") -- 修改文件后缀
Path.GetExtension(path)                -- 获取文件后缀
Path.Combine("C:\\搜狗浏览器\\", "aaaa.txt") -- 合并文件路径

Path.GetRandomFileName()           -- 获取随机文件名+后缀
Path.PathSeparator                           -- 分隔符
Path.VolumeSeparatorChar            -- 冒号
Path.AltDirectorySeparatorChar    -- 反斜杠

例程: 

internal class Program
{
    static void Main(string[] args)
    {
        string path = @"C:\搜狗浏览器\ldinst-41.exe.ttd";

        //获取根目录
        Console.WriteLine(Path.GetPathRoot(path)); //结果显示: C:\

        //获取文件路径名
        Console.WriteLine(Path.GetDirectoryName(path)); //结果显示: C:\搜狗浏览器

        //获取文件名 不包含后缀
        Console.WriteLine(Path.GetFileNameWithoutExtension(path));//结果显示: ldinst-41.exe

        //获取文件后缀
        Console.WriteLine(Path.GetExtension(path));//结果显示: .ttd

        //获取文件名 包含后缀
        Console.WriteLine( Path.GetFileName(path)); //结果显示: ldinst-41.exe.ttd

        //获取绝对路径
        Console.WriteLine(Path.GetFullPath(path));//结果显示: C:\搜狗浏览器\ldinst-41.exe.ttd

        //修改文件后缀
        Console.WriteLine(Path.ChangeExtension(path, "text"));//结果显示: C:\搜狗浏览器\ldinst-41.exe.text

        //合并路径
        Console.WriteLine(Path.Combine(Path.GetDirectoryName(path), "aaaa.txt"));//结果显示: C:\搜狗浏览器\aaaa.txt

        //获取随机文件名+后缀
        Console.WriteLine(Path.GetRandomFileName()); //结果显示: vjzle4pq.1v0

        Console.WriteLine(Path.PathSeparator); //分隔符
        Console.WriteLine(Path.VolumeSeparatorChar);//冒号
        Console.WriteLine(Path.AltDirectorySeparatorChar); //反斜杠

    }
}

三、文件读写

 常用函数:

File.Create(path)               -- 文档创建并清空
File.Copy(path_1,path_2) -- 文档复制
File.Delete(path_2)           -- 文档删除
File.Move(path_1,path_2) -- 文档剪切
File.AppendText(path)     -- 文档内容追加
File.ReadAllLine(path)     -- 文档读取所有行
File.ReadAllText(path)     -- 读取整个文档

FileStream.Write(bytes,0,bytes.Length) -- 一个个写
FileStream.Flush()   -- 刷新

StreamWriter.WriteLine(text) -- 写一行
StreamWrite.BaseStream.Write(bytes,0,bytes.Length) -- 一个个写
StreamWrite.Flush()  -- 刷新

例程: 

internal class Program
{
    static void Main(string[] args)
    {

        string path = "C:\\Temp\\A.txt";
        using (FileStream fs = File.Create(path))//创建并清空原有数据
        {
            byte[] bytes = Encoding.UTF8.GetBytes("我最最最爱你,你不知道吗\r\n");
            fs.Write(bytes, 0, bytes.Length); //一个个写
            fs.Flush();

        }
        using (StreamWriter sw = File.AppendText(path)) //流写入 -- 追加
        {
            string text = "我是你.......";
            sw.WriteLine(text);

            byte[] bytes = Encoding.UTF8.GetBytes("eeeeeeeee\r\n");
            sw.BaseStream.Write(bytes, 0, bytes.Length); //一个个写

            sw.Flush();
        }
        //File.OpenRead(path);等价
        using (FileStream fs = new FileStream(path, FileMode.Open)) //分批读取
        {
            byte[] bytes = new byte[1 * 1024];
            int count = fs.Read(bytes, 0, bytes.Length);
            string date = Encoding.UTF8.GetString(bytes, 0, count);
            Console.WriteLine(date);
        }

        foreach (string item in File.ReadAllLines(path)) //读取所有行,遍历
        {
            Console.WriteLine(item);
        }

        Console.WriteLine(File.ReadAllText(path)); //读取整个文本

        string path_1 = "C:\\Temp\\A.txt";
        string path_2 = "C:\\Temp\\B.txt";
        File.Copy(path_1, path_2); //文档复制
        File.Delete(path_2); //文档删除
        File.Move(path_1, path_2); //文档剪切

    }
}

四、磁盘操作

 常用函数:

DriveInfo.GetDrives() -- 获取当前所有磁盘
drive.IsReady              -- 磁盘是否可用
drive.DriveType          -- 获取磁盘类型
drive.Name                  -- 磁盘名称
drive.TotalSize            -- 磁盘总空间
drive.AvailableFreeSpace -- 磁盘剩余空间

例程: 

internal class Program
{
    static void Main(string[] args)
    {
        foreach (DriveInfo drive in DriveInfo.GetDrives())
        {
            if (drive.IsReady)
            {
                Console.WriteLine($"类型:{drive.DriveType}" +
                                  $"名称:{drive.Name}" +
                                  $"总空间:{drive.TotalSize / 1024 / 1024 / 1024}G " +
                                  $"剩余空间:{drive.AvailableFreeSpace / 1024 / 1024 / 1024} G");
            }
            else
            {
                Console.WriteLine($"类型:{drive.DriveType} is not ready");
            }
        }
    }
}

五、文档序列化

 常用函数:

二进制序列化
    BinaryFormatter.Serialize(stream, text)  -- 序列化成二进制,写入文档
    BinaryFormatter.Deserialize(stream)      --反序列化读出文档
    
XML序列化
    XmlSerializer.Serialize(stream, text)  -- 序列化成XML格式,写入文档
    XmlSerializer.Deserialize(stream)      --反序列化读取
    
Json序列化
    JsonConvert.SerializeObject(text)         -- 序列化
    JsonConvert.DeserializeObject(result) -- 反序列化

例程: 

internal class Program
{
    static void Main(string[] args)
    {
        string path = @"C:\Temp\C.txt";
        string text = "凄凄切切QQ群www";

        //---------------二进制序列化------------------------
        using (Stream stream = File.OpenWrite(path))
        {
            BinaryFormatter bf = new BinaryFormatter();
            //序列化文档
            bf.Serialize(stream, text);
        }
        using (Stream stream = File.OpenRead(path))
        {
            BinaryFormatter bf = new BinaryFormatter();
            //反序列化读取
            Console.WriteLine(bf.Deserialize(stream));
        }

        //---------------XML序列化------------------------
        using (Stream stream = File.OpenWrite(path))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(string));
            //序列化文档
            serializer.Serialize(stream, text); 
        }
        using (Stream stream = File.OpenRead(path))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(string));
            //反序列化读取
            Console.WriteLine(serializer.Deserialize(stream));
        }
        //---------------Json序列化------------------------
        string result = JsonConvert.SerializeObject(text); //序列化
        Console.WriteLine(result);

        Console.WriteLine(JsonConvert.DeserializeObject(result)); //反序列化
    }
}

如有错误,烦请批评指正

C#— —文件操作 本文主要介绍C#中的一些文件操作,并介绍如何进行文件读写。 文章目录1. 文件信息类1.1 File和FileInfo类1.2 Directory和DirectoryInfo类1.3 DriveInfo类2. 流3. 读写器参考资料 1. 文件信息类 1.1 File和FileInfo类 File:提供关于文件创建、复制、删除、移动以及打开操作的静态方法,并且帮助创建FileStream对象; FileInfo:提供文件属性,以及关于文件创建、复制、删除、移动以及打开操作的实例方法,并且帮助创建FileS 阅读详情

相关推荐

使用C#在指定目录下创建文件夹的全面指南

通过本文的介绍,您应该对如何使用C#在指定目录下创建文件夹有了更深入的了解。有时,您可能需要在一个不存在的路径上创建多个文件夹。在这种情况下,您可以使用方法的重载版本,它接受一个额外的参数。在C#中,我们可以使用命名空间中的类来创建文件夹。其中,方法允许我们在指定的路径上创建一个新的文件夹。文件夹通常有一个唯一的路径,用于标识其在文件系统中的位置。这段代码将在驱动器下的目录中创建一个新的文件夹。要创建一个文件夹,只需调用方法并传入您想要创建的文件夹的路径。这段代码将在驱动器下创建三个嵌套的文件夹:、和。

N201871643的博客 790

C# 文件操作之创建文件夹

本文章主要是讲述C#中文件操作的基础知识,如何创建文件夹、创建文件、介绍Directory类\DirectoryInfo类和使用FolderBrowserDialog组件(文件夹对话框)。文章属于基础知识,参考了书籍刘丽霞《C#范例开发大全》,希望对大家有用! 一.界面设计 创建的C# Windows窗体应用程序,界面设计如下添加Lable控件、TextBox控件(其中textBox1可设置属...

ithome 2643

C#实现创建多级目录(附完整源码)

C#实现创建多级目录(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 396

C#语言的文件操作

使用using语句:确保文件流在使用后被正确关闭,避免资源泄漏。异常处理:尽可能包裹文件操作代码,添加异常处理来捕获可能发生的错误。路径管理:使用方法构建文件路径,确保代码在不同环境下的兼容性。文件访问权限:确保程序在执行文件操作时有适当的权限。性能考虑:对于大文件的读取,考虑使用FileStream进行非阻塞操作。通过本文的介绍,希望能够帮助读者在C#中熟练掌握文件操作技巧,为开发实践打下坚实的基础。无论是简单的文件读写,还是复杂的文件管理,这些基本操作都是不可或缺的组成部分。

2501_90485558的博客 633

C#怎样创建、移动及遍历文件夹

GetFileSystemInfos()方法:返回某个目录中所有文件和子目录的FileSystemInfo类型数组。2、DirectoryInfo类没有静态方法,仅可以用于实例化的对象,4、 通过Exists()方法判断要创建的文件夹是否存在。3、判断输入的文件夹名称是否为空,弹出提示框。

2301_77877379的博客 3260

华为海思IC前端中后端(COT&XPU)岗位笔试机考题

华为海思COT和XPU部门IC前端,IC中端,IC后端岗位笔试真题分享

weixin_37584728的博客 3362

C#中的文件操作

FileStream类表示在磁盘或网络路径上指向文件的流,并提供了在文件中读写字节和字节数组的方法(FileStream类提供的方法操作的是字节数据),通过这些方法FileStream对象可以读取诸如图像、声音等文件,也就是说FileStream能够处理各种数据文件。FileStream类有很多重载的构造方法,其中最常用的是带有三个参数的构造方法path:文件路径名mode:表示如何打开或创建文件(有 FileMode.Append、FileMode.Create、FileMode.Open等)

ht_game的博客 1726

风控要略-互联网业务反欺诈之路(一)

当前中国互联网安全产业答题可以分为基础安全和业务安全两个领域。从互联网诞生至2014年,互联网安全行业关注的热点基本都聚焦在网络安全、系统安全和应用安全这个三大基础安全领域上,“DDOS“(分布式拒绝服务攻击)1、“漏洞“、“拖库“2和“挂马“3等大家耳熟能详的术语也是从这些领域中衍生出来的。2014年前后,随着互联网业务的爆炸式发展,黑产团伙开始从“攻击渗透系统“的传统套路进化到“利用业务风控确实进行大规模牟利“的模式,并且逐渐形成规模庞大、分工明确的黑色产业链。

Despacito1006的博客 1013

C#文件操作指南

本文全面总结了C#中的文件操作方法,主要分为三个层次:1) File类提供最简单的一行代码读写;2) FileStream类支持更灵活的流式操作;3) BinaryReader/Writer用于高性能二进制处理。详细介绍了文件创建、复制、读写等基础操作,重点讲解了FileMode模式选择、路径处理技巧和编码问题。同时给出了最佳实践建议,包括必须使用using自动关闭文件、异常处理和大文件处理的性能优化方案。最后根据不同场景提供了方法选择指南,强调读写方式必须匹配的基本原则。

2503_94494029的博客 854

【Cadence】Virtuoso@LayoutXL 差分电路版图镜像同步技巧详解

本文详细介绍了在Cadence Virtuoso LayoutXL中实现差分电路版图镜像同步的技巧,包括核心需求、环境配置、分步操作指南及高级技巧。通过使用LayoutXL的Group功能,工程师可以高效保持差分电路的对称性,提升版图迭代效率,确保高速信号处理的稳定性。特别适用于深亚微米工艺下的差分放大器设计。

weixin_29215391的博客 323

5分钟快速搭建:使用ros1_bridge实现ROS2容器与ROS1主机的无缝通信

本文详细介绍了如何在5分钟内快速搭建基于ros1_bridge的通信方案,实现运行在Docker容器中的ROS2节点与宿主机ROS1系统的无缝数据交换。通过环境隔离、Docker容器化部署及选择性桥接配置,该方案能有效整合新旧系统,避免大规模代码重构,是机器人项目渐进式升级的实用策略。

weixin_29268637的博客 179

【C#】文件操作

操作变量和常量时,数据都是存储在内存中的,程序运行结束后会被全被删除。想要长久地保存数据,可以选用文件或数据库来存储。 C#提供了DriveInfo、Directory、DirectoryInfo、File、FileInfo、Path等文件操作类,来实现在程序运行时对文件进行创建、读写、移动等操作。 一、DriveInfo 密封类,用来查看计算机驱动器信息。主要包括查看磁盘的空间、磁盘的文件格式、磁盘的卷标等。 Driveinfo driveInfo=new Driveinfo("C"); .

weixin_56814032的博客 1615

【gridsample】地平线征程6芯片中gridsample算子的优化与部署实践

本文详细介绍了地平线征程6芯片中gridsample算子的优化与部署实践,重点探讨了PTQ和QAT量化方案在BEV感知任务中的应用。通过双线性插值优化、内存布局调整和混合精度配置等关键技术,显著提升了算子在自动驾驶场景下的性能和精度,为开发者提供了实用的部署指南和调优建议。

zero1的博客 1019

C# 文件操作

DriveInfo**枚举类型:**​DriveTypeDriveInfo​NTFSFAT32DriveTypeNameTotalSizeDriveType​FixedCDRomNetworkRemovableNTFS​driverNamedriver10241024。

qq_38358224的博客 1104

【误码率仿真】基于matlab 小波变换OFDM误码率仿真

其中,与传统的 OFDM 相比,小波变换 OFDM 在进行调制和解调时,使用的是小波变换函数。需要注意的是,由于小波变换函数将频域信号转换为时域信号,因此与传统 OFDM 不同,小波变换 OFDM 中的信号需要在时域上添加循环前缀。与传统的 OFDM 不同,小波变换 OFDM 使用小波函数作为基函数,而非正弦函数作为基函数,因此可以在保持子载波正交性的同时,让子载波之间的带宽变得更加均匀。在频域进行信号加权,然后进行小波逆变换,得到时域信号。在接收端进行信号接收,去掉循环前缀并进行小波变换得到频域信号。

Fanjufei的博客 662

【在 WSL2 GUI 中使用 pulseaudio 播放声音】

最近在搞一个Linux项目,由于WSL2中需要用到声音外放,无奈只能潜心研究。后来就使用了一种折中的方式替代,那就是pulseaudio。目前来讲WSL2对硬件外设的支持还是不太友好,关于USB的支持我之前在其他文章中已经论述过了,这里不讨论。1、Windows11别忘记打开声音2、可能有一定延迟,因为是通过网络传输的。3、效果的话只能见仁见智了,如果不能满足要求就安装一个实实在在的Ubuntu吧!

jiexijihe945的博客 4532

C# 文件操作实验

只是记录一下日常的实验作业而已,仅供参考仅供参考

yccck的博客 2621

paddle 43 用onnxruntime实现ppyoloe模型的部署(含python和c++版本)

PP-YOLOE+是PP-YOLOE模型的升级版,PP-YOLOE+_l在COCO test-dev2017达到了53.3的mAP, 同时其速度在Tesla V100上达到了78.1 FPS。PP-YOLOE+_s/m/x同样具有卓越的精度速度性价比。paddle官方只给出了基于paddle框架的部署案例,为了更好的部署,为此实现将paddle模型转换为onnx模型,然后在python下实现onnxruntime部署。后续会补充c++ onnxruntime部署

a486259的博客 1915

C#文件操作中文乱码问题

//C#写入/读出文本文件 string fileName =@"c:I.txt"; StreamReader sr = new StreamReader(fileName); string str=sr.ReadLine (); sr.close(); StreamWriterrw=File.CreateText(Server.MapPath(".")+"/myText.t

创业的程序员 2232

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

深度学习工具包 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# 加密解码各种方法
下一篇: C# Json 增删改查
**启程**
博客等级 码龄6年 49粉丝 52原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值