Skip to content

Instantly share code, notes, and snippets.

@chewxy
Created December 30, 2017 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chewxy/a51a9dc2c6b76e39c51e670e20d09789 to your computer and use it in GitHub Desktop.
Save chewxy/a51a9dc2c6b76e39c51e670e20d09789 to your computer and use it in GitHub Desktop.
Sparse tensors in Gorgonia
package main
import (
"fmt"
. "gorgonia.org/tensor"
)
func main() {
xs := []int{1, 2, 6, 8}
ys := []int{1, 2, 1, 6}
vals := []float32{3, 1, 4, 1}
S := CSCFromCoord(Shape{9, 7}, xs, ys, vals)
T2 := New(WithShape(9, 7), Of(Float32)) // dense
Result, _ := Add(S, T2)
fmt.Printf("When adding a sparse tensor to a dense tensor, the result is of %T:\n=============================================================================\n%+#s\n", Result, Result)
Result, _ = Add(T2, S)
fmt.Printf("And vice versa - %T\n=========================\n%+#s\n", Result, Result)
// Output:
// When adding a sparse tensor to a dense tensor, the result is of *tensor.Dense:
// =============================================================================
// Matrix (9, 7) [7 1]
// ⎡0 0 0 0 0 0 0⎤
// ⎢0 3 0 0 0 0 0⎥
// ⎢0 0 1 0 0 0 0⎥
// ⎢0 0 0 0 0 0 0⎥
// ⎢0 0 0 0 0 0 0⎥
// ⎢0 0 0 0 0 0 0⎥
// ⎢0 4 0 0 0 0 0⎥
// ⎢0 0 0 0 0 0 0⎥
// ⎣0 0 0 0 0 0 1⎦
// And vice versa - *tensor.Dense
// =========================
// Matrix (9, 7) [7 1]
// ⎡0 0 0 0 0 0 0⎤
// ⎢0 3 0 0 0 0 0⎥
// ⎢0 0 1 0 0 0 0⎥
// ⎢0 0 0 0 0 0 0⎥
// ⎢0 0 0 0 0 0 0⎥
// ⎢0 0 0 0 0 0 0⎥
// ⎢0 4 0 0 0 0 0⎥
// ⎢0 0 0 0 0 0 0⎥
// ⎣0 0 0 0 0 0 1⎦
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment