TensorFlow.NET 소개 및 사용법

logo

TensorFlow.NET (TF.NET) provides a .NET Standard binding for TensorFlow. It aims to implement the complete Tensorflow API in C# which allows .NET developers to develop, train and deploy Machine Learning models with the cross-platform .NET Standard framework.

Join the chat at https://gitter.im/publiclab/publiclab Tensorflow.NET codecov NuGet Documentation Status Badge

TF.NET is a member project of SciSharp STACK.

tensors_flowing

Why TensorFlow.NET ?

SciSharp STACK's mission is to bring popular data science technology into the .NET world and to provide .NET developers with a powerful Machine Learning tool set without reinventing the wheel. Since the APIs are kept as similar as possible you can immediately adapt any existing Tensorflow code in C# with a zero learning curve. Take a look at a comparison picture and see how comfortably a Tensorflow/Python script translates into a C# program with TensorFlow.NET.

pythn vs csharp

SciSharp's philosophy allows a large number of machine learning code written in Python to be quickly migrated to .NET, enabling .NET developers to use cutting edge machine learning models and access a vast number of Tensorflow resources which would not be possible without this project.

In comparison to other projects, like for instance TensorFlowSharp which only provide Tensorflow's low-level C++ API and can only run models that were built using Python, Tensorflow.NET also implements Tensorflow's high level API where all the magic happens. This computation graph building layer is still under active development. Once it is completely implemented you can build new Machine Learning models in C#.

How to use

Install TF.NET and TensorFlow binary through NuGet.

### install tensorflow C# binding
PM> Install-Package TensorFlow.NET

### Install tensorflow binary
### For CPU version
PM> Install-Package SciSharp.TensorFlow.Redist

### For GPU version (CUDA and cuDNN are required)
PM> Install-Package SciSharp.TensorFlow.Redist-Windows-GPU

Import TF.NET in your project.

using static Tensorflow.Binding;

Linear Regression:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

// We can set a fixed init value in order to debug
var W = tf.Variable(-0.06f, name: "weight");
var b = tf.Variable(-0.73f, name: "bias");

// Construct a linear model
var pred = tf.add(tf.multiply(X, W), b);

// Mean squared error
var cost = tf.reduce_sum(tf.pow(pred - Y, 2.0f)) / (2.0f * n_samples);

// Gradient descent
// Note, minimize() knows to modify W and b because Variable objects are trainable=True by default
var optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost);

// Initialize the variables (i.e. assign their default value)
var init = tf.global_variables_initializer();

// Start training
using(tf.Session()) 
{
    // Run the initializer
    sess.run(init);

    // Fit all training data
    for (int epoch = 0; epoch < training_epochs; epoch++)
    {
        foreach (var (x, y) in zip<float>(train_X, train_Y))
            sess.run(optimizer, (X, x), (Y, y));

        // Display logs per epoch step
        if ((epoch + 1) % display_step == 0)
        {
            var c = sess.run(cost, (X, train_X), (Y, train_Y));
            Console.WriteLine($"Epoch: {epoch + 1} cost={c} " + $"W={sess.run(W)} b={sess.run(b)}");
        }
    }

    Console.WriteLine("Optimization Finished!");
    var training_cost = sess.run(cost, (X, train_X), (Y, train_Y));
    Console.WriteLine($"Training cost={training_cost} W={sess.run(W)} b={sess.run(b)}");

    // Testing example
    var test_X = np.array(6.83f, 4.668f, 8.9f, 7.91f, 5.7f, 8.7f, 3.1f, 2.1f);
    var test_Y = np.array(1.84f, 2.273f, 3.2f, 2.831f, 2.92f, 3.24f, 1.35f, 1.03f);
    Console.WriteLine("Testing... (Mean square loss Comparison)");
    var testing_cost = sess.run(tf.reduce_sum(tf.pow(pred - Y, 2.0f)) / (2.0f * test_X.shape[0]),
                                (X, test_X), (Y, test_Y));
    Console.WriteLine($"Testing cost={testing_cost}");
    var diff = Math.Abs((float)training_cost - (float)testing_cost);
    Console.WriteLine($"Absolute mean square loss difference: {diff}");

    return diff < 0.01;
});

Run this example in Jupyter Notebook.

Read the docs & book The Definitive Guide to Tensorflow.NET.

There are many examples reside at TensorFlow.NET Examples.

Troubleshooting of running example or installation, please refer here.

Contribute:

Feel like contributing to one of the hottest projects in the Machine Learning field? Want to know how Tensorflow magically creates the computational graph? We appreciate every contribution however small. There are tasks for novices to experts alike, if everyone tackles only a small task the sum of contributions will be huge.

You can:

  • Let everyone know about this project
  • Port Tensorflow unit tests from Python to C#
  • Port missing Tensorflow code from Python to C#
  • Port Tensorflow examples to C# and raise issues if you come accross missing parts of the API
  • Debug one of the unit tests that is marked as Ignored to get it to work
  • Debug one of the not yet working examples and get it to work

How to debug unit tests:

The best way to find out why a unit test is failing is to single step it in C# and its pendant Python at the same time to see where the flow of execution digresses or where variables exhibit different values. Good Python IDEs like PyCharm let you single step into the tensorflow library code.

Git Knowhow for Contributors

Add SciSharp/TensorFlow.NET as upstream to your local repo ...

git remote add upstream git@github.com:SciSharp/TensorFlow.NET.git

Please make sure you keep your fork up to date by regularly pulling from upstream.

git pull upstream master

 

[출처] https://github.com/SciSharp/TensorFlow.NET

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86852
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79152
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95892
604 Deploying Keras models using TensorFlow Serving and Flask file 졸리운_곰 2019.12.07 1296
603 flask를 이용한 tensorflow 트레이닝 모델 api file 졸리운_곰 2019.12.07 1086
602 텐서플로우(TensorFlow)를 이용해서 글자 생성(Text Generation) 해보기 – Recurrent Neural Networks(RNNs) 예제 – Char-RNN file 졸리운_곰 2019.12.07 1246
601 LSTM RNN을 이용하여 아마존 주가 예측하기 file 졸리운_곰 2019.12.04 1235
600 RNN 과거 주가데이터 학습하여 다음날 종가 예측하기 file 졸리운_곰 2019.12.04 854
599 CNN으로 문장 분류하기 file 졸리운_곰 2019.12.03 1335
598 Get to know TensorFlow.js in 7 minutes file 졸리운_곰 2019.11.18 1227
597 TensorFlow.js: 웹 프론트엔드에서 머신러닝 활용하기 file 졸리운_곰 2019.11.18 1053
596 '애자일과 데이터 관리의 결합'··· '데이터옵스'의 정의와 주요 기술 file 졸리운_곰 2019.11.17 1684
595 데브옵스와 분석의 결합··· ‘데이터옵스’를 아시나요? file 졸리운_곰 2019.11.17 1242
594 데이터옵스(DATAOPS) 란 무엇일까? file 졸리운_곰 2019.11.17 1638
593 데이터옵스는 단순히 데이터에 대한 데브옵스가 아님니다. DataOps is NOT Just DevOps for Data file 졸리운_곰 2019.11.17 1639
592 머신러닝(기계학습)에서 머신리즈닝(기계추론)으로 From Machine Learning to Machine Reasoning file 졸리운_곰 2019.11.15 1362
591 TensorFlow 모델을 저장하고 불러오기 (save and restore) 졸리운_곰 2019.11.13 821
590 번역 - Generative Adversarial Network (GAN) 설명 file 졸리운_곰 2019.11.11 1389
» TensorFlow.NET 소개 및 사용법 file 졸리운_곰 2019.11.02 1659
588 그때그때 달라요··· 머신러닝 기법·기술 따라잡기 file 졸리운_곰 2019.10.25 1319
587 Is Deep Learning Too Superficial? 딥러닝은 너무 피상적인가? file 졸리운_곰 2019.10.25 1294
586 CH7_Machine Learning Algorithms in Prolog.pdf file 졸리운_곰 2019.10.25 1347
585 딥 러닝 용어 - batch, iteration, epoch 졸리운_곰 2019.10.23 1203
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED