anshuman23 / tensorflex

Tensorflow bindings for the Elixir programming language :muscle:
https://hexdocs.pm/tensorflex/Tensorflex.html
Apache License 2.0
308 stars 14 forks source link

Added "append" function for matrices #22

Closed anshuman23 closed 6 years ago

anshuman23 commented 6 years ago

@josevalim, as per our discussion, added a function that can add a row to a matrix one at a time, similar to Python's list based append. Since this is a standalone functionality that can be used irrespective of the CSV loading function we are going to implement, I thought of pushing it separately. Also, this operation is fast, since old data is maintained and we just "push back" the new row at the end after reallocation of memory.

Some basic usage:

iex(1)> mat = Tensorflex.create_matrix(4,4,[[123,431,23,1],[1,2,3,4],[5,6,7,8],[768,564,44,5]])
%Tensorflex.Matrix{
  data: #Reference<0.3675359429.1377959937.238799>,
  ncols: 4,
  nrows: 4
}

iex(2)> mat = Tensorflex.append_to_matrix(mat, [[1,1,1,1]])
%Tensorflex.Matrix{
  data: #Reference<0.3675359429.1377959937.238799>,
  ncols: 4,
  nrows: 5
}

iex(3)> Tensorflex.matrix_to_lists mat
[
  [123.0, 431.0, 23.0, 1.0],
  [1.0, 2.0, 3.0, 4.0],
  [5.0, 6.0, 7.0, 8.0],
  [768.0, 564.0, 44.0, 5.0],
  [1.0, 1.0, 1.0, 1.0]
]

iex(4)> Tensorflex.matrix_pos(mat,5,3) 
1.0

Incorrect usage (having more than one row, or lower/higher number of columns than the original matrix) will raise:

iex(5)> mat = Tensorflex.append_to_matrix(mat, [[1,2]])
** (ArgumentError) data columns must be same as matrix and number of rows must be 1
    (tensorflex) lib/tensorflex.ex:46: Tensorflex.append_to_matrix/2

iex(5)> mat = Tensorflex.append_to_matrix(mat, [[1,1,1,1],[2,2,2,2]])
** (ArgumentError) data columns must be same as matrix and number of rows must be 1
    (tensorflex) lib/tensorflex.ex:46: Tensorflex.append_to_matrix/2