scijs / ndarray

📈 Multidimensional arrays for JavaScript
MIT License
1.21k stars 61 forks source link

how to reshape a ndarray? #46

Open cxchhh opened 1 year ago

cxchhh commented 1 year ago

Does this module has methods similar to reshape(A, m, n) in matlab? If so, how can I use it?

rreusser commented 1 year ago

It doesn't have reshape() exactly, but you might be able to use the constructor ndarray(data[, shape, stride, offset]):

a = ndarray([1, 2, 3, 4], [2, 2])

b = ndarray(a.data, [4])

This will probably work perfectly well for simple cases where the array is not already a stepped or transposed view, but be advised that stride and offset are capable of representing memory layouts which may not be completely straightforward to reinterpret with a different shape. When I know what the input l looks like though, I've frequently used this approach.

TBH it does seem like a bit of missing functionality to do this with strict checking so that you know the result is valid.

cxchhh commented 1 year ago

That's what I need, thanks. However, after b = ndarray(a.data, [4]), it seems that b.data and a.data are bind together. When I change b.data, a.data changes as well. Try this:

var a=zeros([1],'float32');
var b=ndarray(a.data,a.shape);
b.set(0,1);
console.log(a);
console.log(b);

you'll see that both a.data and b.data = [1]. That's weird.

rreusser commented 1 year ago

Yes, you can always call .slice() on the data array if you want to decouple them. You'll find that, in general, copying memory is the exception rather than the norm when using scijs/ndarray. This differs from matlab or numpy which tend to copy the memory on every operation. Also, in case you haven't seen it, ndarray-ops may be a useful set of functions, and I wrote this many years ago as well: https://github.com/scijs/scijs-ndarray-for-matlab-users

cxchhh commented 1 year ago

Yes, .slice() works for me either. Thank you very much for all these information.

cxchhh commented 1 year ago

Btw, are there any better modules to let me perform these operations as smoothly as pytorch?

rreusser commented 1 year ago

The only other module I know of is stdlib/ndarray. The Stdlib project is aiming to be much closer to numpy ndarrays, both in terms of design and extensibility, but although it's a much more complete foundation, it doesn't yet have an ecosystem of tools around it. I'm not too familiar with tensorflow, but if your interest is in ML, those toolkits might have more to offer than scijs/ndarray.