Matrix indexing
- Dominant language
- C++
- Stars
- 3.4k
- Forks
- 701
- PR merge metrics
- No merged PRs in 30d
Description
Hi,
I'm trying to access a cell/row/column in a matrix expression the same way I do with numpy matrices, but I get unexpected output.
For example, I create a model and input a batch:
```python
In [1]: import numpy as np
In [2]: import dynet as dy
[dynet] random seed: 1976554331
[dynet] allocating memory: 512MB
[dynet] memory allocation done.
In [3]: model = dy.Model()
In [4]: W = model.add_parameters((2, 3))
In [5]: input = dy.inputMatrix(np.random.random((9, )), (3, 3))
In [6]: input = dy.reshape(input, (3, 1), 3)
In [7]: output = dy.softmax(dy.parameter(W) * input)
In [8]: output.value()
Out[8]:
array([[[ 0.29126599, 0.32145429, 0.19847248]],
[[ 0.70873398, 0.67854571, 0.8015275 ]]])
```
If I take, for example, the first row or the first cell ([0,0]) from the numpy matrix, this is the output:
```python
In [9]: output.value()[0,0]
Out[9]: array([ 0.29126599, 0.32145429, 0.19847248])
In [10]: output.value()[0,0,0]
Out[10]: 0.29126599431037903
```
If I try to access rows, columns or cells directly from the expression object, the results are unexpected:
```python
In [11]: output[0].value()
Out[11]: [0.29126599431037903, 0.0, 0.0]
In [12]: output[0][0].value()
Out[12]: [0.29126599431037903, 0.0, 0.0]
In [13]: output[0][0][0].value()
Out[13]: [0.29126599431037903, 0.0, 0.0]
In [14]: output[1][0][0].value()
Out[14]: [0.7087339758872986, 0.0, 0.0]
In [15]: output[2].value()
PickElement::forward_impl requested element 2 from a vector of length 2
Aborted (core dumped)
```
```output[1][1][0].value()1``` and ```output[1][0][1].value()``` result in the same exception.
The only workaround I've found is to reshape the matrix to a vector and access a matrix cell by computing its index in the vector using column-major order:
```
output = dy.reshape(output, (6, ))
row = 1
col = 1
num_of_rows = 2
output[col * num_of_rows + row].value()
0.67854571
```
Is there a more direct way for matrix indexing? Thanks!
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.