github.com/wzzhu/tensor@v0.9.24/example_sparse_test.go (about)

     1  package tensor
     2  
     3  import "fmt"
     4  
     5  func Example_sparse_basics() {
     6  	xs := []int{1, 2, 6, 8}
     7  	ys := []int{1, 2, 1, 6}
     8  	vals := []float32{3, 1, 4, 1}
     9  
    10  	S := CSCFromCoord(Shape{9, 7}, xs, ys, vals)
    11  	T := New(WithShape(9, 7), Of(Float32)) // dense
    12  
    13  	Result, _ := Add(S, T)
    14  	fmt.Printf("When adding a sparse tensor to a dense tensor, the result is of %T:\n=============================================================================\n%+#s\n", Result, Result)
    15  	Result, _ = Add(T, S)
    16  	fmt.Printf("And vice versa - %T\n=========================\n%+#s\n", Result, Result)
    17  
    18  	// Output:
    19  	// When adding a sparse tensor to a dense tensor, the result is of *tensor.Dense:
    20  	// =============================================================================
    21  	// Matrix (9, 7) [7 1]
    22  	// ⎡0  0  0  0  0  0  0⎤
    23  	// ⎢0  3  0  0  0  0  0⎥
    24  	// ⎢0  0  1  0  0  0  0⎥
    25  	// ⎢0  0  0  0  0  0  0⎥
    26  	// ⎢0  0  0  0  0  0  0⎥
    27  	// ⎢0  0  0  0  0  0  0⎥
    28  	// ⎢0  4  0  0  0  0  0⎥
    29  	// ⎢0  0  0  0  0  0  0⎥
    30  	// ⎣0  0  0  0  0  0  1⎦
    31  	//
    32  	// And vice versa - *tensor.Dense
    33  	// =========================
    34  	// Matrix (9, 7) [7 1]
    35  	// ⎡0  0  0  0  0  0  0⎤
    36  	// ⎢0  3  0  0  0  0  0⎥
    37  	// ⎢0  0  1  0  0  0  0⎥
    38  	// ⎢0  0  0  0  0  0  0⎥
    39  	// ⎢0  0  0  0  0  0  0⎥
    40  	// ⎢0  0  0  0  0  0  0⎥
    41  	// ⎢0  4  0  0  0  0  0⎥
    42  	// ⎢0  0  0  0  0  0  0⎥
    43  	// ⎣0  0  0  0  0  0  1⎦
    44  }
    45  
    46  func Example_sparse_advanced() {
    47  	xs := []int{1, 2, 6, 8}
    48  	ys := []int{1, 2, 1, 6}
    49  	vals := []int16{3, 1, 4, 1}
    50  
    51  	S := CSCFromCoord(Shape{9, 7}, xs, ys, vals)
    52  	T := New(WithShape(9, 7), Of(Int16))     // dense
    53  	Reuse := New(WithShape(9, 7), Of(Int16)) // reuse must be a *Dense because the result will always be a dense
    54  	Result, _ := Add(S, T, WithReuse(Reuse))
    55  	fmt.Printf("Operations involving sparse tensors also do take the usual function options like Reuse:\n%+#s\nResult == Reuse: %t", Result, Result == Reuse)
    56  
    57  	// Output:
    58  	// Operations involving sparse tensors also do take the usual function options like Reuse:
    59  	// Matrix (9, 7) [7 1]
    60  	// ⎡0  0  0  0  0  0  0⎤
    61  	// ⎢0  3  0  0  0  0  0⎥
    62  	// ⎢0  0  1  0  0  0  0⎥
    63  	// ⎢0  0  0  0  0  0  0⎥
    64  	// ⎢0  0  0  0  0  0  0⎥
    65  	// ⎢0  0  0  0  0  0  0⎥
    66  	// ⎢0  4  0  0  0  0  0⎥
    67  	// ⎢0  0  0  0  0  0  0⎥
    68  	// ⎣0  0  0  0  0  0  1⎦
    69  	//
    70  	// Result == Reuse: true
    71  }