gorgonia / tensor

package tensor provides efficient and generic n-dimensional arrays in Go that are useful for machine learning and deep learning purposes
Apache License 2.0
362 stars 49 forks source link

Tensor Product (Kronecker product) of complex matrix #46

Open sah4ez opened 5 years ago

sah4ez commented 5 years ago

Hi everyone! Thanks for great package for work with tensors! I tried use this package for work with complex matrix/vectors, but not found Tensor Product implementation. You'll plan add this functional?

sah4ez commented 5 years ago

I wrote this methods as experiment:

func ProductVector(a, b *tensor.Dense) *tensor.Dense {
    if !a.Shape().IsVector() || !b.Shape().IsVector() {
        panic("should be vectors")
    }
    ar := a.Shape()
    br := b.Shape()
    l := ar[0] * br[0]
    k := tensor.New(tensor.WithShape(l), tensor.WithBacking(make([]complex128, ar[0]*br[0])))

    p := 0
    for i := 0; i < ar[0]; i++ {
        for j := 0; j < br[0]; j++ {
            ci, _ := a.At(i)
            cj, _ := b.At(j)
            k.Set(p, ci.(complex128)*cj.(complex128))
            p = p + 1
        }
    }
    return k
}

func ProductMatrix(m1, m2 *tensor.Dense) *tensor.Dense {
    if !m1.Shape().IsMatrix() || !m2.Shape().IsMatrix() {
        panic("should be matrix")
    }
    m := m1.Shape()
    p := m2.Shape()

    tmp := []*tensor.Dense{}
    for i := 0; i < m[0]; i++ {
        for j := 0; j < m[1]; j++ {
            cij, _ := m1.At(i, j)
            n, _ := tensor.Mul(m2, tensor.New(tensor.WithShape(1), tensor.WithBacking([]complex128{cij.(complex128)})))
            tmp = append(tmp, n.(*tensor.Dense))
        }
    }

    mv3 := []complex128{}
    for l := 0; l < len(tmp); l = l + m[0] {
        for j := 0; j < p[0]; j++ {
            for i := l; i < l+m[0]; i++ {
                for k := 0; k < p[1]; k++ {
                    cjk, _ := tmp[i].At(j, k)
                    mv3 = append(mv3, cjk.(complex128))
                }
            }
        }
    }
    m3 := tensor.New(tensor.WithShape(m[0]*p[0], m[1]*p[1]), tensor.WithBacking(mv3))

    return m3
}

I think, this code can add to genlib2 for all types. But I don't know how implement universal function for n-dimensions tensor.Dense

chewxy commented 4 years ago

Hey @sah4ez did you add this, do you need help?

sah4ez commented 4 years ago

@chewxy As I understand, big part of code generated through genlib2. So, for all types, need implement this function. So I have questions:

  1. snippets with code is ok?
  2. if this will be only for 2-dementions matrix, ok?