SciSharp / NumSharp

High Performance Computation for N-D Tensors in .NET, similar API to NumPy.
https://github.com/SciSharp
Apache License 2.0
1.36k stars 189 forks source link

np.meshgrid() has a hidden error returning wrong results #408

Open LordTrololo opened 4 years ago

LordTrololo commented 4 years ago

There seems to be a bug in the np.meshgrid() function. It has something to do with the way the unmanaged memory is handeld but I havent tried to understand the details.

Why hidden ? Well, lets say we have the following code:

var meshAB = np.meshgrid(np.arange(3), np.arange(3));

meshAB.Item1 seems to be ok, but meshAB.Item2 hides a nasty problem. Strangely enough, when one makes a clone of Item2, the cloned values are OK! This is also my quick fix for now.

So to summary, the code below:

var meshAB = np.meshgrid(np.arange(3), np.arange(3));
Console.WriteLine("meshAB.Item1.flatten(): " + meshAB.Item1.flatten().ToString());
Console.WriteLine("meshAB.Item2.flatten(): " + meshAB.Item2.flatten().ToString());

NDArray a = meshAB.Item1.Clone();
NDArray b = meshAB.Item2.Clone();

Console.WriteLine("a.flatten(): " +a.flatten().ToString());
Console.WriteLine("b.flatten(): " +b.flatten().ToString());

Will output:

meshAB.Item1.flatten(): [0, 1, 2, 0, 1, 2, 0, 1, 2]    
meshAB.Item2.flatten(): [0, 1, 2, 0, 1, 2, 0, 1, 2]     <-------WRONG
a.flatten(): [0, 1, 2, 0, 1, 2, 0, 1, 2]
b.flatten(): [0, 0, 0, 1, 1, 1, 2, 2, 2]      <------ CORRECT

The bug is nasty because in inspector we also see ok values which is not true. Here is an image: image

ArthHil commented 3 years ago

Same problem, but clone didnt resolve the problem

Oceania2018 commented 3 years ago

I tested it in tf.net preview. It's working good. image New version implemented the NumPy API in TensorFlow NumPy