0

I am changing an c++ example in mxnet. I do not understand how to allocate an NDArray object. There is no even basic documentation around, which is pretty frustrating.

I try to allocate an NDArray, but by declaring an instance it does not seem to allocate the data, only when I fill an array with data. Is that correct?

// this code snippet does not work     
  NDArray a = NDArray(Shape(10, 20), Context::cpu());
  const float *dat = a.GetData();
  float result = *dat; // read memory violation
  result = *(dat + 10);

// this code snippet works
  NDArray b = NDArray(Shape(10, 20), Context::cpu());
  a.SampleUniform(1.0, 2.0, &b);
  const float *dat2 = b.GetData();
  float result2 = *dat2; // works!!
  result2 = *(dat2 + 10); 

Has someone experience with the c++ API and changing networks?

  • Have you seen the example code https://github.com/apache/incubator-mxnet/tree/master/example/image-classification/predict-cpp ? – leezu Aug 10 '17 at 07:45

2 Answers2

2

there is a third argument delay_alloc: https://github.com/apache/incubator-mxnet/blob/master/cpp-package/include/mxnet-cpp/ndarray.h#L144

Set it false, you code will work.

  • Thanks for your reply, it works!!! Strangely enough in the class docs http://mxnet.io/doxygen/classmxnet_1_1NDArray.html , the default argument in the constructor is 'False', while according to intellisense the default is 'True'. – user2980583 Aug 22 '17 at 08:07
1

It's been a while since the question was posted. Here's my answer if it helps anyone.

You define the data to be set by using a std::vector and the matrix Shape which is stores the data from the vector.

  std::vector<mx_float> v {1.23, 4.56, 7.89, 5.71};

  // populates v vector data in a matrix of 1 row and 4 columns
  // mxnet::cpp::NDArray nda_array {v, Shape{1,4}, m_ctx};

  // populates v vector data in a matrix of 2 rows and 2 columns
  // where v[3] and v[4] are populated in second row
  mxnet::cpp::NDArray nda_array {v, Shape{2,2}, m_ctx};

  assert(nda_array.Size() == 4);

  assert(nda_array.At(0, 0) == v[0]);
  assert(nda_array.At(0, 1) == v[1]);
  assert(nda_array.At(1, 0) == v[2]);
  assert(nda_array.At(1, 1) == v[3]);
AdvSphere
  • 986
  • 7
  • 15