GithubHelp home page GithubHelp logo

scisharp / numpy.net Goto Github PK

View Code? Open in Web Editor NEW
657.0 27.0 94.0 56.06 MB

C#/F# bindings for NumPy - a fundamental library for scientific computing, machine learning and AI

License: Other

C# 99.96% Python 0.04%

numpy.net's Introduction

logo

Numpy.NET is the most complete .NET binding for NumPy, which is a fundamental library for scientific computing, machine learning and AI in Python. Numpy.NET empowers .NET developers with extensive functionality including multi-dimensional arrays and matrices, linear algebra, FFT and many more via a compatible strong typed API. Several other SciSharp projects like Keras.NET and Torch.NET depend on Numpy.NET.

Example

Check out this example which uses numpy operations to fit a two-layer neural network to random data by manually implementing the forward and backward passes through the network.

Numpy Neural Network in C# and in Python

Numpy and Intellisense: a developer-friendly combination:

Numpy Intellisense

Installation

If you want to use Numpy.NET you have two options:

Numpy.dll

Just reference Numpy.dll via Nuget, set your build configuration to x64 and you are good to go. Thanks to Python.Included it doesn't require a local Python installation or will not clash with existing installations.

Numpy.Bare.dll

In certain use cases you might not want the packaged Python and NumPy packages. In that case you reference Numpy.Bare.dll via Nuget. Depending on the Numpy.Bare nuget version will need Python 3.5, 3.6 or 3.7 and Numpy 1.16 installed for it to work. The first two digits of the Numpy.Bare version indicate which Python version is needed for it to run (i.e. Numpy.Bare v3.6.1.1 needs Python 3.6 installed). If you are getting BadImageFormatException switch between x86 and x64 build settings.

In other cases, you might want to control the install location of the Python installation or even set it up yourself instead of having the Numpy library do it. For those cases Numpy.Bare is also great. Check out the custom installation example if you want to know how.

How does it work?

Numpy.NET uses Python for .NET to call into the Python module numpy. However, this does not mean that it depends on a local Python installation! Numpy.NET.dll uses Python.Included which packages embedded Python 3.7 and automatically deploys it in the user's home directory upon first execution. On subsequent runs, it will find Python already deployed and therefore doesn't install it again. Numpy.NET also packages the NumPy wheel and installs it into the embedded Python installation when not yet installed.

Long story short: as a .NET Developer you don't need to worry about Python at all. You just reference Numpy.NET, use it and it will just work, no matter if you have local Python installations or not.

Multi-threading (Must read!)

Beware: Not following these steps can result in deadlocks or access violation exceptions!

Python/NumPy doesn't have real multi-threading support. There is no advantage in "simultaneously" executing numpy functions on multiple threads because pythonnet requires you to use the Global Interpreter Lock (GIL) to lock access to the Python engine exclusively for only one thread at a time. If you have to call Python from a thread other than the main thread you first must release the main thread's mutex by calling PythonEngine.BeginAllowThreads() or you'll have a deadlock:

var a = np.arange(1000);
var b = np.arange(1000);

// https://github.com/pythonnet/pythonnet/issues/109
PythonEngine.BeginAllowThreads();

Task.Run(()=> {
  // when running on different threads you must lock!
  using (Py.GIL())
  {
    np.matmul(a, b);
  }
}).Wait();

Above example only serves as a reference on how to call numpy from a different thread than the main thread. As said before, having multiple background threads that call into Python doesn't give you multi-core processing because of the requirement to lock the GIL. Not doing so will result in access violation exceptions and/or deadlocks.

Note that you must call a method of np before calling PythonEngine.BeginAllowThreads() in order for the PythonEngine to be initialized. So, for instance, if you want to initialize an inherently multi-threaded .Net Core Web API at startup, do something like this:

np.arange(1);
PythonEngine.BeginAllowThreads();

Also, if you do this, be sure to wrap any calls to Numpy in using (Py.GIL()) { ... } or else you'll get AccessViolationExceptions.

Performance considerations

You might ask how calling into Python affects performance. As always, it depends on your usage. Don't forget that numpy's number crunching algorithms are written in C so the thin pythonnet and Python layers on top won't have a significant impact if you are working with larger amounts of data.

In my experience, calling numpy from C# is about 4 times slower than calling it directly in Python while the execution time of the called operation is of course equal. So if you have an algorithm that needs to call into numpy in a nested loop, Numpy.NET may not be for you due to the call overhead.

All of numpy is centered around the ndarray class which allows you to pass a huge chunk of data into the C routines and let them execute all kinds of operations on the elements efficiently without the need for looping over the data. So if you are manipulating arrays or matrices with thousands or hundreds of thousands of elements, the call overhead will be negligible.

The most performance sensitive aspect is creating an NDarray from a C# array, since the data has to be moved from the CLR into the Python interpreter. pythonnet does not optimize for passing large arrays from C# to Python but we still found a way to do that very efficiently. When creating an array with np.array( ... ) we internally use Marshal.Copy to copy the entire C#-array's memory into the numpy-array's storage. And to efficiently retrieve computation results from numpy there is a method called GetData<T> which will copy the data back to C# in the same way:

// create a 2D-shaped NDarray<int> from an int[]
var m = np.array(new int[] {1, 2, 3, 4});
// calculate the cosine of each element
var result = np.cos(m);
// get the floating point data of the result NDarray back to C#
var data = result.GetData<double>(); // double[] { 0.54030231, -0.41614684, -0.9899925 , -0.65364362 }

Numpy.NET vs NumSharp

The SciSharp team is also developing a pure C# port of NumPy called NumSharp which is quite popular albeit being not quite complete.

There are a couple of other NumPy ports out there featuring subsets of the original library. The only one that matches Numpy.NET in terms of completeness is the IronPython package numpy which is out of date though. The SciSharp team is committed to keeping Numpy.NET up to date with the original library and to feature as much of the original functionality as possible.

Code generation

The vast majority of Numpy.NET's code is generated using CodeMinion by parsing the documentation at docs.scipy.org/doc/numpy/. This allowed us to wrap most of the numpy-API in just two weeks. The rest of the API can be completed in a few more weeks, especially if there is popular demand.

Completion status

The following API categories have been generated (if checked off)

  • Array creation routines
  • Array manipulation routines
  • Binary operations
  • String operations
  • Datetime Support Functions
  • Data type routines
  • Optionally Scipy-accelerated routines(numpy.dual)
  • Floating point error handling
  • Discrete Fourier Transform(numpy.fft)
  • Financial functions
  • Functional programming
  • Indexing routines
  • Input and output
  • Linear algebra(numpy.linalg)
  • Logic functions
  • Masked array operations
  • Mathematical functions
  • Matrix library(numpy.matlib)
  • Miscellaneous routines
  • Padding Arrays
  • Polynomials
  • Random sampling(numpy.random)
  • Set routines
  • Sorting, searching, and counting
  • Statistics
  • Window functions

Over 500 functions of all 1800 have been generated, most of the missing functions are duplicates on Matrix, Chararray, Record etc.

Auto-generated Unit-Tests

We even generated hundreds of unit tests from all the examples found on the NumPy documentation. Most of them don't compile without fixing them because we did not go so far as to employ a Python-To-C# converter. Instead, the tests are set up with a commented out Python-console log that shows what the expected results are and a commented out block of somewhat C#-ified Python code that doesn't compile without manual editing.

Another reason why this process can not be totally automated is the fact that NumPy obviously changed the way how arrays are printed out on the console after most of the examples where written (they removed extra spaces between the elements). This means that oftentimes the results needs to be reformatted manually for the test to pass.

Getting more unit tests to run is very easy though, and a good portion have already been processed to show that Numpy.NET really works. If you are interested in working on the test suite, please join in and help. You'll learn a lot about NumPy on the way.

Documentation

Since we have taken great care to make Numpy.NET as similar to NumPy itself, you can, for the most part, rely on the official NumPy manual.

Create a Numpy array from a C# array and vice versa

To work with data from C# in Numpy it has to be copied into the Python engine by using np.array(...). You get an NDarray that you can use for further processing of the data. Here we calculate the square root:

// create an NDarray from a C# array
var a = np.array(new[] { 2, 4, 9, 25 });
Console.WriteLine("a: "+ a.repr);
// a: array([ 2,  4,  9, 25])
// apply the square root to each element
var roots = np.sqrt(a);
Console.WriteLine(roots.repr);
// array([1.41421356, 2.        , 3.        , 5.        ])

After processing the data you can copy it back into a C# array use a.GetData<int>(), but be aware of the datatype of the NDarray in order to get correct values back:

// Copy the NDarray roots into a C# array from NDarray (incorrect datatype)
Console.WriteLine(string.Join(", ", roots.GetData<int>()));
// 1719614413, 1073127582, 0, 1073741824 
Console.WriteLine("roots.dtype: " + roots.dtype);
// roots.dtype: float64
Console.WriteLine(string.Join(", ", roots.GetData<double>()));
// 1.4142135623731, 2, 3, 5

Creating multi-dimensional NDarrays from C# arrays

Creating an NDarray from data is easy. Just pass the C# array into np.array(...). You can pass 1D, 2D and 3D C# arrays into it.

// create a 2D NDarray
var m = np.array(new int[,] {{1, 2}, {3, 4}}); // the NDarray represents a 2 by 2 matrix

Another even more efficient way (saves one array copy operation) is to pass the data as a one-dimensional array and just reshape the NDarray.

// create a 2D NDarray
var m = np.array(new int[] {1, 2, 3, 4}).reshape(2,2); // the reshaped NDarray represents a 2 by 2 matrix

Differences between Numpy.NET and NumPy

As you have seen, apart from language syntax and idioms, usage of Numpy.NET is almost identical to Python. However, due to lack of language support in C#, there are some differences which you should be aware of.

Array slicing syntax

You can access parts of an NDarray using array slicing. C# doesn't support the colon syntax in indexers i.e. a[:, 1]. However, by allowing to pass a string we circumvented this limitation, i.e. a[":, 1"]. Only the ... operator is not yet implemented, as it is not very important.

Variable argument lists

Some NumPy functions like reshape allow variable argument lists at the beginning of the parameter list. This of course is not allowed in C#, which supports a variable argument list only as the last parameter. In case of reshape the solution was to replace the variable argument list that specifies the dimensions of the reshaped array by a Shape object which takes a variable list of dimensions in its constructor:

var a=np.arange(24);
var b=np.reshape(a, new Shape(2, 3, 4)); // or a.reshape(2, 3, 4)

In other cases the problem was solved by providing overloads without the optional named parameters after the variable argument list.

Parameter default values

C# is very strict about parameter default values which must be compile time constants. Also, parameters with default values must be at the end of the parameter list. The former problem is usually solved by having a default value of null instead of the non-compile-time constant and setting the correct default value inside the method body when called with a value of null.

Unrepresentable operators

Python operators that are not supported in C# are exposed as instance methods of NDarray:

Python C#
// floordiv()
** pow()

Inplace modification

In NumPy you can write a*=2 which doubles each element of array a. C# doesn't have a *= operator and consequently overloading it in a Python fashion is not possible. This limitation is overcome by exposing inplace operator functions which all start with an 'i'. So duplicating all elements of array a is written like this in C#: a.imul(2);. The following table lists all inplace operators and their pendant in C#

Python C#
+= iadd()
-= isub()
*= imul()
/= idiv() or itruediv()
//= ifloordiv()
%= imod()
**= ipow()
<<= ilshift()
>>= irshift()
&= iand()
|= ior()
^= ixor()

(Possible) scalar return types

In NumPy a function like np.sqrt(a) can either return a scalar or an array, depending on the value passed into it. In C# we are trying to solve this by creating overloads for every scalar type in addition to the original function that takes an array and returns an array. This bloats the API however and hasn't been done for most functions and for some it isn't possible at all due to language limitations. The alternative is to cast value types to an array (NDarray can represent scalars too):

So a simple root = np.sqrt(2) needs to be written somewhat clumsily like this in C#: var root = (double)np.sqrt((NDarray)2.0); until overloads for every value type are added in time for your convenience. In any case, the main use case for NumPy functions is to operate on the elements of arrays, which is convenient enough:

var a = np.arange(100); // => { 0, 1, 2, ... , 98, 99 }
var roots = np.sqrt(a); // => { 0.0, 1.0, 1.414, ..., 9.899, 9.950 }

Complex numbers

Numpy.NET supports complex numbers even though the notation in Python and C# is very different:

>>> a = np.array([1+2j, 3+4j, 5+6j])

looks like this in C#

var a = np.array(new Complex[] { new Complex(1, 2), new Complex(3,4), new Complex(5,6), });

Access the real and imaginary components of a complex array via a.real and a.imag or copy the complex values of an ndarray into C# with Complex[] c=a.GetData<Complex>();.

Functions clashing with their class name

The function fft(...) in numpy.fft and random(...) in numpy.random had to be renamed because C# doesn't allow a member to have the same name as its enclosing class. That's why in Numpy.NET these functions have been renamed with a trailing underscore like this: np.fft.fft_(...)

Versions and Compatibility

Currently, Numpy.dll is targeting .NET Standard (on Windows) and packages the following binaries:

  • Python 3.7: (python-3.7.3-embed-amd64.zip)
  • NumPy 1.16 (numpy-1.16.3-cp37-cp37m-win_amd64.whl)

Numpy.Bare.dll is available for the Python versions 2.7, 3.5, 3.6 and 3.7 on Windows, Linux and MacOS on Nuget.

To make Numpy.dll support Linux a separate version of Python.Included packaging linux binaries of Python needs to be made and a version of Numpy.dll that packages a linux-compatible NumPy wheel. If you are interested, you may work on this issue.

License

Numpy.NET packages and distributes Python, pythonnet as well as numpy. All these dependencies imprint their license conditions upon Numpy.NET. The C# wrapper itself is MIT License.

Common Mistakes

  • If you check Prefer 32-bit in your build config or build with x86 instead of Any CPU Numpy.NET will crash with BadFormatException
  • If you have insufficient folder permissions in AppData Numpy.NET might crash. You can specify a different installpath by setting Installer.INSTALL_PATH = "<install path>";
  • If you get deadlocks (program hangs indefinitely) you should read the secton about multi-threading above!
  • If you get AccessViolationExceptions you should read the secton about multi-threading above!

Project Sponsors

numpy.net's People

Contributors

0x6a62 avatar aleksvujic avatar benkalegin avatar casey-bateman avatar henon avatar rstarkov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

numpy.net's Issues

SciPy

Can I somehow also import SciPy (and not only NumPy) to my C#-Project?

About np.linspace

in Python, when I want to generate a list with fixed number,we can do it : x_data = np.linspace(0.0,10.0,100), 100 number
but when I execute this in Numpy.NET, warms appear. Why is it not available?

np.delete not implemented?

hi, i'm trying to convert this code

need_to_be_deleted_idx = np.concatenate(([last], np.where(overlap_ratio > iou_thresh)[0]))
idxs = np.delete(idxs, need_to_be_deleted_idx)

to

var need_to_be_deleted_idx = np.concatenate(((NDarray)last, overlap_ratio[overlap_ratio >  (NDarray)iou_thresh][0]));
idxs =  np.delete(idxs, need_to_be_deleted_idx["0:"]);

but i can't get a Slice object of the NDarray, any hint how to solve this?

Nightly builds?

Hello, I'm getting an an issue with the latest version of Numpy.NET we downloaded from NuGet and think that it might be solved in master.

Is there any way to get a debug build and verify if the issue is resolved?

Currently the latest release is 3.7.1.9 which is 3 months old.

How to

How can I convert the below python line into NumSharp:
np.column_stack(np.where(mat > 0))
Thanks in advance.

Suggestions regarding np.linalg.norm, np.random.normal and GetData

Hello,

First of all, congrats on the great job of binding numpy so well. This is by far the best c# version of numpy I have encountered, and it was relatively easy to get things going (in combination with the documentation). After using this for a project I am working on, I have a few minor comments that I thought would make sense to write here:

np.linalg.norm

Works as expected, but only has only constructor. if I want to do something like:
np.linalg.norm(c, axis=1) using Numpy.NET now I have to write np.linalg.norm(c, null, new int[]{1}) which is maybe not the most ideal. Multiple constructors would be nice so axis could either be an int[] or just an int.

np.random.normal

Input arguments are also not the most robust. If I want to do something like:

np.random.normal(3, 2.5, c.shape) using Numpy.NET now I have to write np.random.normal(new NDarray<float>(new[] { 3 }), new NDarray<float>(new[] { 2.5 }), new[]{cshape[0], c.shape[1]}); . Would be nice ideally if we could just pass floats and ideally also a shape objects. From my understanding the variety of constructors are also limited.

GetData

Regarding GetData, unfortunately if I have a numpy array with shape of NxM where M>1 then I always just get a one dim vector. Would be nice if we could return an array based on a given shape. So my current workaround is to get the .repr
of the element from the NDarray and then convert it to Single/Double/Int32.

Thanks again for this nice binding package!

Complex numbers

Hello,
I noticed there's no complex numbers support for this binding.
There's some standard for those in C# System.Numerics.
Has this been considered?

If yea, then sorry for this spam.

Failure out-of-the-box

I am running a very trivial .net core app with code as simple as that:

    static async Task Main(string[] args)
    {
        Console.WriteLine("Starting test application!");

        var m = np.array(new int[] { 1, 2, 3, 4 });

        Console.WriteLine("");
        Console.WriteLine("Press any key to exit..");
        Console.ReadKey();
    }

Exceptions is thrown at numpy line:

System.IO.FileNotFoundException: 'Could not load file or assembly 'pickle5, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'

if I click continue:

System.IO.FileNotFoundException: 'Could not load file or assembly 'org, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'

continue:

System.IO.FileNotFoundException: 'Could not load file or assembly 'org.python, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'

continue:

System.IO.FileNotFoundException: 'Could not load file or assembly 'org.python.core, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'

continue:

System.IO.FileNotFoundException: 'Could not load file or assembly 'pwd, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'

etc...

System.IO.FileNotFoundException: 'Could not load file or assembly 'grp, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'

after about 6-7 more exceptions code is finally executed and seems to be running fine.. but why are so many exceptions thrown?

numpy: 3.7.1.14
running in x64
.net core 3.1

Needless to say I don't have python installed

some problem in build random array

var a1 = np.random.rand(300, 200);
Python.Runtime.PythonException:“TypeError : rand() got an unexpected keyword argument 'd0'”

var a1 = np.random.randn(300, 200);
Python.Runtime.PythonException:“TypeError : randn() got an unexpected keyword argument 'd0'”

Create NDarray stuck in ASP.NET

Hi, I try to use Numpy in ASP.NET app, and it's stuck on second call.
It's stuck in post method, in get method sometimes ok.

I try simple code

NDarray array = np.array(new float[,] { { 0 }, { 1 } });

Test.zip

Numpy.NET multiple instances?

I'm having trouble after instantiating and computing all Numpy tasks (successfully) - to refresh or load program again within another software (c# based). If i make a change to a parameter the whole process should refresh with set new parameter - yet it crashes completely like I'm still locked in the previous process. Really difficult to have a coherent debug/output since projects are being run within another software.
Even if I remove the project (should be clear) and re-add it - it just doesn't render anything 2nd time and onward ... like somehow memory isn't cleared - still part of the same static. Tried a simple ndarray generate.

Am I missing something? Should I start handling the python runtime? with lock and releaselock?

Ubuntu env

Can't run in Ubuntu.

An unhandled exception of type 'System.DllNotFoundException' occurred in Python.Runtime.NETStandard.dll: 'Unable to load shared library 'python36' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libpython36: cannot open shared object file: No such file or directory'

Related issue #2.

Convert C# variables to np.NDarray and vice versa

Hi

I am new to keras.net. One question that is not clear for me. When I call such class I give it as inputa C# varaibles such as list <> or array. I can convert these variables to numpy (array and ndarray) using loops but what are the generic function to convert
List <> ->\np.array \np.NDarray
\np.array \np.NDarray ->List<> \C# array

Thanks
Natan

Performance issue while using indexing

@henon any quick pointers

for (int i = 0; i <= 2212389 ; i++)
            {
                y2[new Slice(start: 5* i, stop: 5* (i + 1))]
                   = np.dot(y1[new Slice(i, i + 2 * 4)], b);

            }

this takes around 1-2 mins in c# and few seconds in python ,

i removed new slice and made the array static location and it is quite reasonable in C#, any suggestion to slice the array without new slice keyword

NDarray error initialization inside RestApi method (C#/WebApi project)

Hi!
If I work with NDarray in console app there is no problem. I can initialize array and use it for prediction. But inside REST API method it works only one time. After second invokation the app freezes at line:
var array = new float[1, 2];
var ndArray = new NDarray(array); //freezes at this line AFTER SECOND INVOCATION
result = ndArray.ToString();

In debug session in Visual Studio (2017/2019) it produces sometimes error: "AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt". Sometimes it just hangs on the line where array was created.

See my code:

  1. Back (C#): https://github.com/berlicon/MoscowTravelHackTestApp/tree/master/back/HackApi2
  2. Front (Angular.io): https://github.com/berlicon/MoscowTravelHackTestApp/tree/master/front/hack-app

Files with problems:

  1. WebApi controller: https://github.com/berlicon/MoscowTravelHackTestApp/blob/master/back/HackApi2/Controllers/MainController.cs
  2. Util class with model: https://github.com/berlicon/MoscowTravelHackTestApp/blob/master/back/HackApi2/Utils/ModelUtil.cs

Error in ModelUtil.TestNDarray() which invoked from WebApi method MainController.TestNDarray() with params [0, 0]

I have read the paragraph: https://github.com/SciSharp/Numpy.NET#multi-threading
And have already tried:

  1. PythonEngine.BeginAllowThreads(); //app crashed at this line and exit, so I commented this line
  2. Task.Run(()=> { //no effect
    using (Py.GIL()) //no effect with or without Task.Run around
    {
    var array = new float[1, 2];
    var ndArray = new NDarray(array); //freezes at this line AFTER SECOND INVOCATION
    result = ndArray.ToString();
    }
    }).Wait();
  3. ndArray.Dispose(); //Suprisingly it helps and I could invoke method without errors 5 times. But after some time it also has no effect
  4. GC.KeepAlive(ndArray); //no effect
  5. using (Py.GIL()) in web api method MainController.TestNDarray() //no effect

I tried this code at home (notebook Win10, Visual Studio 2019 community, python installed) and at work (desktop, Win10, Visual Studio 2017 Professional, Python installed) with equal results.

If I initialize NDarray from C# arrays incorrectly what is the correct way?

np.unique throwing null reference exception

Trying to run the following code:

var hstack = np.hstack(new NDarray[] { X });
var unique = hstack.unique();

image

I think the hstack returns a list which need to be converted. Not sure if there is any other scenario which will return PyTuple.

pls check this excption.

     var a = np.array(new float[110_000,1024]);
        var b = np.array(new float[1024]);
        int times = 10;

        var nums = System.Linq.Enumerable.Range(0, times).Select
          (
          i =>  np.matmul(a, b)
          ); // ok

        var tasks = System.Linq.Enumerable.Range(0, times).Select
            (
            i => Task.Run(() => np.matmul(a, b))
            );
        Task.WaitAll(tasks.ToArray()); //exction

System.NullReferenceException on calling np.linalg.eig

System.NullReferenceException is thrown when I try to calculate the eigenvalues and eigenvectors by using
(NDarray a,NDarray b) = np.linalg.eig(m);

The input NDArray m is:

array([[ 9.92148062e-01,  7.84595516e-04,  1.37193908e-02,
         1.51147931e-03, -1.32650354e-02, -1.12822401e-02,
        -3.61244437e-03, -2.88517326e-03, -1.74003759e-03,
         4.17302100e-03],
       [ 7.84595516e-04,  9.83456645e-01, -5.62064244e-04,
         2.23841492e-02, -2.23881784e-02, -9.68161260e-03,
         9.63603069e-03, -7.05316614e-03,  1.00093107e-02,
        -2.35091386e-02],
       [ 1.37193908e-02, -5.62064244e-04,  9.81816775e-01,
        -1.16108255e-03, -6.98776108e-03, -6.86699512e-03,
        -3.45562594e-03, -1.30434799e-03, -2.19424494e-03,
         5.21341224e-03],
       [ 1.51147931e-03,  2.23841492e-02, -1.16108255e-03,
         1.01695559e+00, -4.46816789e-02, -1.93067602e-02,
         1.92574020e-02, -1.40801263e-02,  1.99977619e-02,
        -4.69695248e-02],
       [-1.32650354e-02, -2.23881784e-02, -6.98776108e-03,
        -4.46816789e-02,  1.02386714e+00,  2.55910723e-02,
        -1.67217423e-02,  1.54990501e-02, -1.85557508e-02,
         4.35316107e-02],
       [-1.12822401e-02, -9.68161260e-03, -6.86699512e-03,
        -1.93067602e-02,  2.55910723e-02,  9.86279405e-01,
        -6.03309755e-03,  7.37078986e-03, -7.34218455e-03,
         1.71987508e-02],
       [-3.61244437e-03,  9.63603069e-03, -3.45562594e-03,
         1.92574020e-02, -1.67217423e-02, -6.03309755e-03,
         9.81460065e-01, -5.54752886e-03,  9.13307498e-03,
        -2.14697109e-02],
       [-2.88517326e-03, -7.05316614e-03, -1.30434799e-03,
        -1.40801263e-02,  1.54990501e-02,  7.37078986e-03,
        -5.54752886e-03,  9.76975963e-01, -6.00493669e-03,
         1.40935754e-02],
       [-1.74003759e-03,  1.00093107e-02, -2.19424494e-03,
         1.99977619e-02, -1.85557508e-02, -7.34218455e-03,
         9.13307498e-03, -6.00493669e-03,  9.81488428e-01,
        -2.17113314e-02],
       [ 4.17302100e-03, -2.35091386e-02,  5.21341224e-03,
        -4.69695248e-02,  4.35316107e-02,  1.71987508e-02,
        -2.14697109e-02,  1.40935754e-02, -2.17113314e-02,
         1.02326832e+00]])

My environment:

  1. Visual Studio 2017

  2. Numpy.NET 3.7.1.9

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Numpy.Bare Version=3.7.1.4, Culture=Neutral, PublicKeyToken=null'

I want to use c# to do machine learning. So I installed keras.NET and some other packages through NuGet in Visual Studio 2017. Here is what I have installed.
Google.Protobuf v3.12.3
Keras.NET v3.7.4.2
Microsoft.CSharp v4.6.0
Microsoft.NETCore.Targets v3.1.0
NumSharp v0.20.5
Python.Included v3.7.3.9
Pythonnet_netstandard_py37_win v2.5.1
Tensorflow.NET v0.11.8.1
System.Threading.Tasks v4.3.0
System.Text.Encoding v4.3.0
System.Runtime.CompilerServices.Unsafe v4.7.0
System.Runtime v4.3.0
System.Reflection.Primitives v4.3.0
System.Reflection.Emit.ILGeneration v4.7.0
System.Reflection v4.3.0
System.Numerics.Vectors v4.5.0
System.Memory v4.5.3
runtime.native.System v4.3.0
System.Buffers v4.5.0
System.Globalization v4.0.11
System.IO v4.3.0

Then I want to test whether it works. So I run the code from https://github.com/SciSharp/Keras.NET/blob/master/Examples/BasicSamples/XOR.cs

The code can be compiled but there is an error saying 'coule not oad file or assembly 'Numpy.bare.Version=3.7.1.4''.
Would someone please tell me what should I do to make it correct?

ModuleNotFoundError : No module named 'numpy'

Hi guys,

I am currently wrapping Numpy.NET around a visual programming interface.
You can take a look here: BHoM#2
The code is not ready to be tested yet, but it gives you an idea of what I am doing with it.

Everything goes fine until I run into the error below:
ModuleNotFoundError : No module named 'numpy'

I thought Python.Included was taking care of setting the right environment, but it seems that it can't find the numpy module.

Do you have any clue why?

np.array issue

H!

Maybe I'm missing something, but this works in python;
a=np.array([1,2,3])
np.array((a,a,a))
Out:
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])

np.array([a,a,a])
Out:
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])

In Numpy.net I tested;

np.array((a, a, a)); // fails (Can not convert type of given object to dtype)
np.array(new []{a, a, a}); // fails (Can not convert type of given object to dtype)

Stack works;
WriteLine(np.stack(new[] { a, a, a })); // works as expected
[[1. 2. 3.]
[1. 2. 3.]
[1. 2. 3.]]

np.stack((a, a, a)); // Does not compile

I solved my problem with stack, but I think np.array should work for this case?
/mattias

np.concatenate

Hi I have a data X with the shape 700x600.

I want to have X[: 0:30,55:79].
In python we do:
y=np.arange(30)
y1 = np.arange(55,79)
X1=X[:, np.concatenate((y,y1))]

How do I do it with numyp nuget?

Support of C# Range operator in indexes

when I convert python code

time_train = time[:split_time]
time_valid = time[split_time:]

to Numpy.Net, the only way I found was to use formatted strings:

var time_train = time[$":{split_time}"];
var time_valid = time[$"{split_time}:"];

C# language recently introduced Range, I think it would be nice to support it for readability (currently it raises exception):

var time_train = time[..split_time];
var time_valid = time[split_time..];

Numpy not responding and freezes the system while deploy on IIS

Hello! I want to use Numpy in my .NET (Framework) MVC project. In local IIS Express of VS, It completely works but the trouble appears when I deploy it on Win10 IIS. Numpy just freeze my system that I can't load any other page or reload the page used Numpy method.
I've tried:

  • "log" to get it error message, but It just freeze and I didn't get any message.
  • Use some simple method like np.array(myArr), It still just freeze! :(
  • Check if IIS run in 32bit mode but I found it's already ran in 64bit mode.

Would someone please tell me what should I do to make it work?

Getting an NDarray from a Bitmap

Hello,

I am trying to get an NDarray from a Bitmap object, so first I tried to save it as a jpg and using Keras.NET's ImageUtil.LoadImg() then ImageUtil.ImageToArray() to get a NDarray, it works, but sometimes, the first function seemed to crash and the error stays into the Python.Runtime, so I am trying to stay away from that.

I noticed I could maybe construct an NDarray through that constructor :
NDarray(IntPtr dataPtr, long dataLength, Dtype dtype)

Does it mean I would be able to transform the Bitmap object into a byte array and construct it with it?

Extra dimension added when using my_ndarray[other_ndarray_with_indexes]

hi,

i think i found an difference of how numpy and numpy.net handles this case:
bboxes has a shape of ( 999, 4) and keep_idx has a shape of e.g. ( 123 )
so in numpy bboxes = bboxes[keep_idx] results in a shape of (123,4) while in numpy.net i get a shape of (1,123,4)

is this my mistake or is this intentional?

np.loadtxt

For the method np.loadtxt there is no dtype: np.str, what are you supposed to use instead?

Python.Runtime.PythonException: Expected to see 2 array(s), for inputs ['image1', 'image1'] but instead got the following list of 1 arrays

how can I passe 2 arrays in the Predict method of BaseModel? (C#)

This is the error:

Python.Runtime.PythonException: ValueError : Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), for inputs ['image1', 'image2'] but instead got the following list of 1 arrays: [array([[[[0.85423136], [0.8542314 ], [0.8542314 ], ..., [0.8542314 ], [0.8542314 ], [0.85423136]], [[0.85423136], [0.8542314 ],...'

code:

image1 = image1.Resize(IMG_SIZE, IMG_SIZE, Inter.Linear); //Image<Gray, float>
image2 = image2.Resize(IMG_SIZE, IMG_SIZE, Inter.Linear); //Image<Gray, float>
NDarray reshapedImage1 = np.array(image1.Data).astype(np.float32);
NDarray reshapedImage2 = np.array(image2.Data).astype(np.float32);
reshapedImage1 /= 255;
reshapedImage2 /= 255;

NDarray imageConcat = np.concatenate((reshapedImage1, reshapedImage2));
imageConcat = imageConcat.reshape(2, IMG_SIZE, IMG_SIZE, 1);

var prediction = _baseModel.Predict(imageConcat); //error here

take_along_axis() doesn't return NDarray

The take_along_axis function doesn't have a return value.
public static void take_along_axis(NDarray arr, NDarray indices, int axis);

As the Numpy Documentation says it should return NDarray.

As my short look on the Numpy.NET code suggests the code is auto generated, I didn't want to open a PR. But the code is missing the return of the dynamic py after the invoke of the python functionality.

How can I translate it to C# ?

>>> import numpy as np
>>> a = [1,2,3,4,0,0,1,2]
>>> a = np.array(a)
>>> b = np.where(a == 0)
>>> b

b = np.where(a == 0)

I need the python equivalent code in c#

I'm having problem convert this py code

ex = (P2 - P1)/(numpy.linalg.norm(P2 - P1))

and
d = numpy.linalg.norm(P2 - P1)

and
ez = numpy.cross(ex,ey)

I'm using .net core 3.1 and I've installed this.

please I need the python equivalent of the above code in c#.

thanks in advance.

Nelly

Complex numbers implement

This is an awesome project!
I'm working on both Python and CSharp.
Recently,I'm trying to translate a python project to CSharp, however I need to implement complex numbers.
Hope Numpy.NET can handle Complex numbers.
Thanks.

Program stuck in np.arrange

When I try to build a NDarray using np.arrange like following:
var a1 = np.arange(25).reshape(5, 5);
No any exception found, but the program cannot step out from this line, it seems that it's stuck in it.
My environment:

  1. VS express 2017 C#
  2. .NET Framework 4.6.1
  3. My application is a WinForm project.

Thanks.

GetData does not match the values in the numpy array

Hi there, basically I have a 3x3 array of integers, which I then convert back to c# int[] array by using the instance method .GetData().

If I use it on an array after it was subject to some transformations, namely flipping axis and sometimes transpose (via the .T property), the data obtained makes no sense. Also, doing the same operation returns different int[] array every time. Here is an example of 10x the same operation.
The odd rows are the contents of the numpy array immediately before using GetData(), while the even rows are the output of GetData();

It seems to me that the GetData method could be getting its values from the wrong memory address.
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -447433968 -2147442432 7929956 6357102 6881389
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -469519893 -1946141184 -1 0 0
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -461065888 -1879043840 3 0 3
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -463497665 -2147463936 0 0 0
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -438135142 -1879020032 -1206988752 542 0
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -425946756 -1946109952 0 0 0
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -425619111 -1879003392 3 0 3
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -419589731 -2147433728 0 0 0
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -419720813 -1946107648 0 0 0
Numpy ndarray: [-1 0 0 0 0 0 0 0 0]
.GetData(): -1 0 0 0 -409563018 -1878980096 3 0 1

Cordially,

Martin

numpy deadlock

Hey guys, how to uses numpy.net in await/async function?

the example below will cause deadlock sometimes.

            foreach(var i in new int[] { 1, 2, 3, 4 })
            {
                await Task.Run(() =>
                {
                    var x_train = np.arange(0, 100, 1);
                });
            }

Error creating string ND array

Hi,

I'm trying to create an NDarray to store DateTime values from a normal C# array. When I try to create the NDarray I get the following error: Can not convert type of given object to dtype: System.String[].

            string[] times = new string[50];

            DateTime now = DateTime.Now;

            for (int i = 0; i < 50; i++)            
                times[i] = now.AddSeconds(i).ToString();            

            // Raises Exception
            NDarray<string> nTimes = np.array<string>(times);

When I try to make a NDarray<float> it works fine, but for NDarray<DateTime> and NDarray<string> this error occurs. Is there something I am doing wrong here or are these types not supported? Thanks for the help!

could np.meshgrid be implemented ?

hi,

after struggling with porting tensorflow code to tensorflow.net (easy) and porting related numpy code (hard) to SciSharp/NumSharp , Quansight-Labs/numpy.net and finally SciSharp/Numpy.NET i found that every numpy port is missing at least one function here and there or provides the function and throws a "oops not implemented" exception at runtime - it's a journey to say the least ...

i'm now converting the tensorflow NumSharp result via the ToNumpyNET()extension method to numpy.net and to cut a long story short - the one function missing is np.meshgrid - could this be implemented?

How to use NDArray shape?

In numpy, the shape of array can be computed like: np.shape
but in numsharp, how to test NDArray's shape?

macOS env

I try to use Numpy.NET in my macos

but it give me this error

Unable to load shared library 'python36' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(libpython36, 1): image not found at Python.Runtime.Runtime.Py_IsInitialized() at Python.Runtime.Runtime.Initialize(Boolean initSigs) at Python.Runtime.PythonEngine.Initialize(IEnumerable1 args, Boolean setSysArgv, Boolean initSigs) at Numpy.NumPy.InstallAndImport(Boolean force) at Numpy.NumPy.<>c.<.cctor>b__650_0() at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy1.CreateValue() at Numpy.np.array[T](T[,] object, Dtype dtype, Nullable1 copy, String order, Nullable1 subok, Nullable1 ndmin) at Submission#4.<>d__0.MoveNext() in :line 1 --- End of stack trace from previous location where exception was thrown --- at Microsoft.CodeAnalysis.Scripting.ScriptExecutionState.RunSubmissionsAsync[TResult](ImmutableArray1 precedingExecutors, Func2 currentExecutor, StrongBox1 exceptionHolderOpt, Func2 catchExceptionOpt, CancellationToken cancellationToken) at Microsoft.CodeAnalysis.Scripting.Script1.RunSubmissionsAsync(ScriptExecutionState executionState, ImmutableArray1 precedingExecutors, Func2 currentExecutor, Func`2 catchExceptionOpt, CancellationToken cancellationToken) at ICSharpCore.Script.InteractiveScriptEngine.ExecuteAsync(String statement)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.