目录

介绍

背景

使用代码

兴趣点


介绍

由于机器学习已变得非常流行,因此使用Keras和/或后端Tensorflow这样的开源SDK,Python语言也再次变得流行(与预测相反,Python将在未来五年内消失)。作为.NET环境的研究工程师,它给我带来了很多问题,我在那里使用Python,而我的主要重点是C#。当然,您可以以某种方式将Python代码嵌入到您的应用程序中(即,在.NET应用程序中运行Python脚本),但这并没有使它变得更好。

我认为,另一个解决方案是使用IronPython,这是一个可以直接运行Python代码的SDK,但是

  1. 它仍在使用Python 2.7(在2020年终止支持),并且对Python 3的支持发音类似于“请勿使用!”,好吧...
  2. 它不支持numpy之类的许多其他软件包,这对于进行机器学习是必不可少的
  3. 解决所有这些问题非常困难...只是不要将其用于此类目的。

因此,我开始研究新的解决方案,以及如何避免在.NET Core应用程序中使用其他Python环境(在应用程序启动时必须额外使用这些环境),并了解Keras.NET(https://github.com/SciSharp/Keras.NET)。明确地说,我不在乎SDK是否使用Python嵌入式,但是我不想用Python编写我的机器学习原型,所以这是改变游戏规则的地方。

背景

Keras.NET的文档非常简短,如果您需要进一步的知识,可以将它们链接到原始Keras文档。这对于理解此框架的工作方式非常有用。但是要弄清楚SDK如何在C#中工作是很痛苦的。

这里是文档链接:https : //scisharp.github.io/Keras.NET/
请查看先决条件(在此前提下,您还必须安装Python)。

在这里,您将找到API文档:https : //scisharp.github.io/Keras.NET/api/index.html

要了解此处发生的情况,您需要了解Keras的工作方式、密集层、时代等的用途。

使用代码

Arnaldo  P.Castaño的文章启发了我展示使用现有数据集的第二个示例以及如何使用Keras.NET进行训练。因此,这是有关使用Keras.NET与使用Keras(在Python中)看到一些区别的信息,也许有人会发现这非常有用。

首先,您将需要Nuget Keras.NET。在Visual Studio中使用程序包管理器,它类似于:

PM> Install-Package Keras.NET -Version 3.8.4.4

除此之外,您将需要使用Windows CLI或Powershell中的pip安装程序来安装Keras和Tensorflow for Python:

pip install keraspip install tensorflow

它必须在Windows-CLI中看起来像:

C:\Users\YOURNAME>pip install keras

如果您对pip安装程序有疑问,请检查是否已将Python设置为系统环境。安装屏幕底部有一个复选框,称为Python添加到PATH”,这非常重要。

如果这样做没有帮助,则您可能必须自行设置路径(互联网上有“操作方法”,如何修复pip的提示音,一旦解决了此问题,就可以确定Python设置正确) 。

最后,您将需要训练和测试集:https : //github.com/zalandoresearch/fashion-mnist#get-the-data。

首先,我将数据存储在本地并解压缩,因为我不想为解压缩而创建其他功能(这实际上并不难实现,但我想在此重点关注)。这只是一个数据。使用下面的代码(并调用该openDatas 函数,您将需要解压缩该文件,否则该函数将无法读取数据。请放置四个数据(2x图像,2x标签...训练并测试)。

其次,我在API-Doc中指出,已经实现了直接加载数据的函数,请参见:https : //scisharp.github.io/Keras.NET/api/Keras.Datasets.FashionMNIST.html

所以我们开始:为了进一步的目的,运行模型的第一次训练。

我的.NET-Core的入口点非常简单。我为训练做了一个类(KerasClass),只需从Main函数中调用它们即可:

using System;namespace Keras.net_and_fashion_mnist
{class Program{static void Main(string[] args){KerasClass keras = new KerasClass();keras.TrainModel();}        }
}

KerasClass是更加有趣的:

using Keras.Datasets;
using Keras.Layers;
using Keras.Models;
using Keras.Utils;
using Numpy;
using System;
using System.IO;
using System.Linq;namespace Keras.net_and_fashion_mnist
{class KerasClass{public void TrainModel(){int batch_size = 1000;   //Size of the batches per epochint num_classes = 10;    //We got 10 outputs since //we can predict 10 different labels seen on the //dataset: https://github.com/zalandoresearch/fashion-mnist#labelsint epochs = 30;         //Amount on trainingperiods, //I figure it out that the maximum is something about //700 epochs, after this it won't increase the //accuracy siginificantly// input image dimensionsint img_rows = 28, img_cols = 28;// the data, split between train and test setsvar ((x_train, y_train), (x_test, y_test)) = FashionMNIST.LoadData(); // Load the datasets from // fashion MNIST, Keras.Net implement this directlyx_train.reshape(-1, img_rows, img_cols).astype(np.float32); //ByteArray needs //to be reshaped to fit the dimmensions of the y arraysy_train = Util.ToCategorical(y_train, num_classes); //here, you modify the //forecast data to 10 outputs//as we have 10 different //labels to predict (see the //Labels on the Dataset)y_test = Util.ToCategorical(y_test, num_classes);   //same for the test data //[hint: you can change this //in example you want to //make just a binary //crossentropy as you just //want to figure, i.e., if //this is a angleboot or notvar model = new Sequential();model.Add(new Dense(100, 784, "sigmoid")); //hidden dense layer, with 100 neurons, //you have 28*28 pixel which make //784 'inputs', and sigmoid function //as activationfunctionmodel.Add(new Dense(10, null, "sigmoid")); //Ouputlayer with 10 outputs,...model.Compile(optimizer: "sgd", loss: "categorical_crossentropy", metrics: new string[] { "accuracy" }); //we have a crossentropy as prediction //and want to see as well the //accuracy metric.var X_train = x_train.reshape(60000, 784); //this is actually very important. //C# works with pointers, //so if you have to reshape (again) //the function for the correct //processing, you need to write this //to a different varvar X_test = x_test.reshape(10000, 784);model.Fit(X_train, y_train, batch_size, epochs, 1); //now, we set the data to //the model with all the //arguments (x and y data, //batch size...the '1' is //just verbose=1Console.WriteLine("---------------------");Console.WriteLine(X_train.shape);Console.WriteLine(X_test.shape);Console.WriteLine(y_train[0]);Console.WriteLine(y_train[1]);       //some outputs...you can play with themvar y_train_pred = model.Predict(X_train);       //prediction on the train dataConsole.WriteLine(y_train_pred);model.Evaluate(X_test.reshape(-1, 784), y_test); //-1 tells the code that //it can figure out the size of //the array by itself}private byte[] openDatas(string path, int skip)      //just the open Data function. //As I mentioned, I did not work //with unzip stuff, you have //to unzip the data before //by yourself{var file = File.ReadAllBytes(path).Skip(skip).ToArray();return file;}//Hint: First, I was working by opening the data locally and //I wanted to figure it out how to present data to the arrays. //So you can use something like this and call this within the TrainModel() function://x_train = openDatas(@"PATH\OF\YOUR\DATAS\train-images-idx3-ubyte", 16);//y_train = openDatas(@"PATH\OF\YOUR\DATAS\train-labels-idx1-ubyte", 8);//x_test = openDatas(@"PATH\OF\YOUR\DATAS\t10k-images-idx3-ubyte", 16);//y_test = openDatas(@"PATH\OF\YOUR\DATAS\t10k-labels-idx1-ubyte", 8);}
}

兴趣点

使用此代码将对您自己的模型进行首次培训。对我来说,这是我进入Keras.NET的第一步,我想分享这一点,因为Keras.NET的例子并不多。也许您可以将其用于您的目的。

https://www.codeproject.com/Articles/5286497/Starting-with-Keras-NET-in-Csharp-Train-Your-First

在C#中从Keras.NET开始——训练您的第一个模型相关推荐

  1. python训练好的图片验证_利用keras加载训练好的.H5文件,并实现预测图片

    我就废话不多说了,直接上代码吧! import matplotlib matplotlib.use('Agg') import os from keras.models import load_mod ...

  2. 在PyTorch上用Keras,分布式训练开箱即用,告别没完没了的Debug

    鱼羊 发自 凹非寺  量子位 报道 | 公众号 QbitAI 在开始一个新的机器学习项目时,难免要重新编写训练循环,加载模型,分布式训练--然后在Debug的深渊里看着时间哗哗流逝,而自己离项目核心还 ...

  3. Keras 的预训练权值模型用来进行预测、特征提取和微调(fine-tuning)

    转至:Keras中文文档 https://keras.io/zh/applications/ 应用 Applications Keras 的应用模块(keras.applications)提供了带有预 ...

  4. TensorFlow中的Keras用法和自定义模型和层

    Keras Keras 是一个用于构建和训练深度学习模型的高阶 API.它可用于快速设计原型.高级研究和生产,具有以下三个主要优势: 方便用户使用 Keras 具有针对常见用例做出优化的简单而一致的界 ...

  5. Keras自定义可训练参数

    Keras自定义可训练参数是在自定义层中实现的,因此需要我们自己编写一个层来实现我们需要的功能.话不多说,直接上实例. 假设我们需要自定义一个可学习的权重矩阵来对某一层的数据进行转换,则可以通过下面代 ...

  6. Keras少量样本训练强大图像分类模型

    原文:Building powerful image classification models using very little data 作者:Francois Chollet,2016.6.2 ...

  7. keras训练模型,训练集的准确率很高,但是测试集准确率很低的原因

    今天在测试模型时发现一个问题,keras训练模型,训练集准确率很高,测试集准确率很低,因此记录一下希望能帮助大家也避坑: 首先keras本身不同的版本都有些不同的或大或小的bug,包括之前也困扰过我的 ...

  8. TensorFlow2中使用Keras Tuner搜索网络的超参数

    1. 导入所需的库 import tensorflow as tf import kerastuner as kt import IPythonfor i in [tf, kt]:print(i.__ ...

  9. kera中使用keras.banked.ctc_decoder()导致内存不断增加的问题解决

    kera中使用keras.banked.ctc_decoder()导致内存不断增加的问题解决 遇到的问题 在使用keras训练了模型后,使用模型进行测试,测试过程中发现随着测试数据的增加,测试速度不断 ...

最新文章

  1. iOS开发多线程篇—线程安全
  2. 鸟哥的Linux私房菜(基础篇)-第三章、主机规划与磁盘分区(三.4. 重点回顾)
  3. 剑网三缘起的云端游戏,千呼万唤终于出来,有玩家不知道怎么玩?
  4. 从源码深处体验Spring核心技术--基于注解的IOC初始化
  5. 科创板开户手续费要2万元,大家怎么看?
  6. 【LeetCode笔记】11.盛最多水的容器(Java、双指针法)
  7. java中父类与子类, 不同的两个类中的因为构造函数由于递归调用导致栈溢出问题...
  8. Win10笔记本可以搜索到邻居WiFi却搜不到自家的??
  9. centos下查看最大Socket连接数
  10. NoSuchMethod: ByteBuffer.position(I)
  11. VS C#启用非托管代码调试 不运行修改
  12. 左耳朵耗子 | 技术人员的发展之路
  13. fpga板子怎么和电脑连_[笔记].怎样正确插拔FPGA开发板的JTAG仿真器,如USB-Blaster等?...
  14. 服务器CPU和普通CPU有什么区别?常用的服务器有六大区别
  15. [论文翻译]YOLOX: Exceeding YOLO Series in 2021
  16. 简述多媒体计算机的特点,多媒体课件的特点和作用
  17. 产品logo的设计:图标与几何构成
  18. 根据IMSI区别运营商
  19. #春Phone计划#51CTO沙龙广州站活动
  20. NI Linux实时设备上升级固件

热门文章

  1. docker 镜像修改的配置文件自动还原_所以到底该如何修改 docker 容器的端口映射!!!...
  2. 视觉控每天盯着桌面,少不了桌面手机壁纸图片,请收好
  3. 中国风吉祥纹样底纹背景,艾草绿和天青色趋势色彩
  4. 广东科技学院计算机原理组成,201120122操作系统原理期中试卷edited广东科技学院付博士(4页)-原创力文档...
  5. win7计算机文件夹打开慢,win7开机很慢怎么办 win7电脑开机慢的优化教程
  6. Qt实现桌面右下角放置窗体
  7. 图解Http学习第四章
  8. Kroneker Tensor:克罗内克张量
  9. Ubuntu16.04下禁用scp、sftp和winscp
  10. 虚拟主机网络设备iotlb