示例#1
1
func TestUpdate(t *testing.T) {
	neuralNetwork := CreateSimpleNetwork(t)
	inputs := mat64.NewDense(1, 2, []float64{0.05, 0.10})
	neuralNetwork.Forward(inputs)
	values := mat64.NewDense(1, 2, []float64{0.01, 0.99})
	neuralNetwork.Backward(values)
	learningConfiguration := neural.LearningConfiguration{
		Epochs:    proto.Int32(1),
		Rate:      proto.Float64(0.5),
		Decay:     proto.Float64(0),
		BatchSize: proto.Int32(1),
	}
	neuralNetwork.Update(learningConfiguration)
	expected_weights_0 := mat64.NewDense(
		3, 2, []float64{0.149780716, 0.24975114, 0.19956143, 0.29950229, 0.35,
			0.35})
	if !mat64.EqualApprox(
		neuralNetwork.Layers[0].Weight, expected_weights_0, 0.0001) {
		t.Errorf("weights 0 unexpected:\n%v",
			mat64.Formatted(neuralNetwork.Layers[0].Weight))
	}
	expected_weights_1 := mat64.NewDense(
		3, 2, []float64{0.35891648, 0.51130127, 0.408666186, 0.561370121, 0.6,
			0.6})
	if !mat64.EqualApprox(
		neuralNetwork.Layers[1].Weight, expected_weights_1, 0.0001) {
		t.Errorf("weights 1 unexpected:\n%v",
			mat64.Formatted(neuralNetwork.Layers[1].Weight))
	}
}
func main() {
	// task 1: show qr decomp of wp example
	a := mat64.NewDense(3, 3, []float64{
		12, -51, 4,
		6, 167, -68,
		-4, 24, -41,
	})
	var qr mat64.QR
	qr.Factorize(a)
	var q, r mat64.Dense
	q.QFromQR(&qr)
	r.RFromQR(&qr)
	fmt.Printf("q: %.3f\n\n", mat64.Formatted(&q, mat64.Prefix("   ")))
	fmt.Printf("r: %.3f\n\n", mat64.Formatted(&r, mat64.Prefix("   ")))

	// task 2: use qr decomp for polynomial regression example
	x := []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	y := []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}
	a = Vandermonde(x, 2)
	b := mat64.NewDense(11, 1, y)
	qr.Factorize(a)
	var f mat64.Dense
	f.SolveQR(&qr, false, b)
	fmt.Printf("polyfit: %.3f\n",
		mat64.Formatted(&f, mat64.Prefix("         ")))
}
func ExampleCholesky() {
	// Construct a symmetric positive definite matrix.
	tmp := mat64.NewDense(4, 4, []float64{
		2, 6, 8, -4,
		1, 8, 7, -2,
		2, 2, 1, 7,
		8, -2, -2, 1,
	})
	var a mat64.SymDense
	a.SymOuterK(1, tmp)

	fmt.Printf("a = %0.4v\n", mat64.Formatted(&a, mat64.Prefix("    ")))

	// Compute the cholesky factorization.
	var chol mat64.Cholesky
	if ok := chol.Factorize(&a); !ok {
		fmt.Println("a matrix is not positive semi-definite.")
	}

	// Find the determinant.
	fmt.Printf("\nThe determinant of a is %0.4g\n\n", chol.Det())

	// Use the factorization to solve the system of equations a * x = b.
	b := mat64.NewVector(4, []float64{1, 2, 3, 4})
	var x mat64.Vector
	if err := x.SolveCholeskyVec(&chol, b); err != nil {
		fmt.Println("Matrix is near singular: ", err)
	}
	fmt.Println("Solve a * x = b")
	fmt.Printf("x = %0.4v\n", mat64.Formatted(&x, mat64.Prefix("    ")))

	// Extract the factorization and check that it equals the original matrix.
	var t mat64.TriDense
	t.LFromCholesky(&chol)
	var test mat64.Dense
	test.Mul(&t, t.T())
	fmt.Println()
	fmt.Printf("L * L^T = %0.4v\n", mat64.Formatted(&a, mat64.Prefix("          ")))

	// Output:
	// a = ⎡120  114   -4  -16⎤
	//     ⎢114  118   11  -24⎥
	//     ⎢ -4   11   58   17⎥
	//     ⎣-16  -24   17   73⎦
	//
	// The determinant of a is 1.543e+06
	//
	// Solve a * x = b
	// x = ⎡  -0.239⎤
	//     ⎢  0.2732⎥
	//     ⎢-0.04681⎥
	//     ⎣  0.1031⎦
	//
	// L * L^T = ⎡120  114   -4  -16⎤
	//           ⎢114  118   11  -24⎥
	//           ⎢ -4   11   58   17⎥
	//           ⎣-16  -24   17   73⎦
}
func main() {
	m := mat64.NewDense(2, 3, []float64{
		1, 2, 3,
		4, 5, 6,
	})
	fmt.Println(mat64.Formatted(m))
	fmt.Println()
	fmt.Println(mat64.Formatted(m.T()))
}
示例#5
0
func (self *Layer) DebugString() string {
	return fmt.Sprintf(
		"name: %v\nweight: %v\ninput: %v\noutput: %v\ndeltas: %v\nderivatives: "+
			"%v\n", self.Name,
		mat64.Formatted(self.Weight, mat64.Prefix("        ")),
		mat64.Formatted(self.Input, mat64.Prefix("        ")),
		mat64.Formatted(self.Output, mat64.Prefix("        ")),
		mat64.Formatted(self.Deltas, mat64.Prefix("        ")),
		mat64.Formatted(self.Derivatives, mat64.Prefix("             ")))
}
func showLU(a *mat64.Dense) {
	fmt.Printf("a: %v\n\n", mat64.Formatted(a, mat64.Prefix("   ")))
	var lu mat64.LU
	lu.Factorize(a)
	var l, u mat64.TriDense
	l.LFrom(&lu)
	u.UFrom(&lu)
	fmt.Printf("l: %.5f\n\n", mat64.Formatted(&l, mat64.Prefix("   ")))
	fmt.Printf("u: %.5f\n\n", mat64.Formatted(&u, mat64.Prefix("   ")))
	fmt.Println("p:", lu.Pivot(nil))
}
示例#7
0
func ExampleExcerpt() {
	// Excerpt allows diagnostic display of very large
	// matrices and vectors.

	// The big matrix is too large to properly print...
	big := mat64.NewDense(100, 100, nil)
	for i := 0; i < 100; i++ {
		big.Set(i, i, 1)
	}

	// so only print corner excerpts of the matrix.
	fmt.Printf("excerpt big identity matrix: %v\n\n",
		mat64.Formatted(big, mat64.Prefix(" "), mat64.Excerpt(3)))

	// The long vector is also too large, ...
	long := mat64.NewVector(100, nil)
	for i := 0; i < 100; i++ {
		long.SetVec(i, float64(i))
	}

	// ... so print end excerpts of the vector,
	fmt.Printf("excerpt long column vector: %v\n\n",
		mat64.Formatted(long, mat64.Prefix(" "), mat64.Excerpt(3)))
	// or its transpose.
	fmt.Printf("excerpt long row vector: %v\n",
		mat64.Formatted(long.T(), mat64.Prefix(" "), mat64.Excerpt(3)))

	// Output:
	// excerpt big identity matrix: Dims(100, 100)
	//  ⎡1  0  0  ...  ...  0  0  0⎤
	//  ⎢0  1  0            0  0  0⎥
	//  ⎢0  0  1            0  0  0⎥
	//  .
	//  .
	//  .
	//  ⎢0  0  0            1  0  0⎥
	//  ⎢0  0  0            0  1  0⎥
	//  ⎣0  0  0  ...  ...  0  0  1⎦
	//
	// excerpt long column vector: Dims(100, 1)
	//  ⎡ 0⎤
	//  ⎢ 1⎥
	//  ⎢ 2⎥
	//  .
	//  .
	//  .
	//  ⎢97⎥
	//  ⎢98⎥
	//  ⎣99⎦
	//
	// excerpt long row vector: Dims(1, 100)
	//  [ 0   1   2  ...  ...  97  98  99]

}
func ExampleCholeskySymRankOne() {
	a := mat64.NewSymDense(4, []float64{
		1, 1, 1, 1,
		0, 2, 3, 4,
		0, 0, 6, 10,
		0, 0, 0, 20,
	})
	fmt.Printf("A = %0.4v\n", mat64.Formatted(a, mat64.Prefix("    ")))

	// Compute the Cholesky factorization.
	var chol mat64.Cholesky
	if ok := chol.Factorize(a); !ok {
		fmt.Println("matrix a is not positive definite.")
	}

	x := mat64.NewVector(4, []float64{0, 0, 0, 1})
	fmt.Printf("\nx = %0.4v\n", mat64.Formatted(x, mat64.Prefix("    ")))

	// Rank-1 update the factorization.
	chol.SymRankOne(&chol, 1, x)
	// Rank-1 update the matrix a.
	a.SymRankOne(a, 1, x)

	var au mat64.SymDense
	au.FromCholesky(&chol)

	// Print the matrix that was updated directly.
	fmt.Printf("\nA' =        %0.4v\n", mat64.Formatted(a, mat64.Prefix("            ")))
	// Print the matrix recovered from the factorization.
	fmt.Printf("\nU'^T * U' = %0.4v\n", mat64.Formatted(&au, mat64.Prefix("            ")))

	// Output:
	// A = ⎡ 1   1   1   1⎤
	//     ⎢ 1   2   3   4⎥
	//     ⎢ 1   3   6  10⎥
	//     ⎣ 1   4  10  20⎦
	//
	// x = ⎡0⎤
	//     ⎢0⎥
	//     ⎢0⎥
	//     ⎣1⎦
	//
	// A' =        ⎡ 1   1   1   1⎤
	//             ⎢ 1   2   3   4⎥
	//             ⎢ 1   3   6  10⎥
	//             ⎣ 1   4  10  21⎦
	//
	// U'^T * U' = ⎡ 1   1   1   1⎤
	//             ⎢ 1   2   3   4⎥
	//             ⎢ 1   3   6  10⎥
	//             ⎣ 1   4  10  21⎦
}
示例#9
0
文件: data_test.go 项目: erubboli/mlt
func TestDataContainer(t *testing.T) {

	file, _ := os.Open("fixtures/2.csv")

	data := NewData(file, "target")
	if data.Cols != 4 {
		t.Error("Expected:", 4)
		t.Error("Actual:  ", data.Cols)
	}

	if data.Rows != 3 {
		t.Error("Expected:", 3)
		t.Error("Actual:  ", data.Rows)
	}

	if data.Labels[0] != "id" {
		t.Error("Expected:", "id")
		t.Error("Actual:  ", data.Labels[0])
	}

	if data.Data.At(2, 3) != 0.001 {
		t.Error("Expected:", "0.001")
		t.Error("Actual:  ", data.Data.At(2, 3))
	}

	fmt.Printf("data: %0.4v\n", mat64.Formatted(data.Data, mat64.Prefix("      ")))

}
示例#10
0
func ExampleFormatted() {
	a := mat64.NewDense(3, 3, []float64{1, 2, 3, 0, 4, 5, 0, 0, 6})

	// Create a matrix formatting value with a prefix ...
	fa := mat64.Formatted(a, mat64.Prefix("    "))

	// and then print with and without zero value elements.
	fmt.Printf("with all values:\na = %v\n\n", fa)
	fmt.Printf("with only non-zero values:\na = % v\n\n", fa)

	// Modify the matrix...
	a.Set(0, 2, 0)

	// and print it without zero value elements.
	fmt.Printf("after modification with only non-zero values:\na = % v\n\n", fa)

	// Output:
	// with all values:
	// a = ⎡1  2  3⎤
	//     ⎢0  4  5⎥
	//     ⎣0  0  6⎦
	//
	// with only non-zero values:
	// a = ⎡1  2  3⎤
	//     ⎢.  4  5⎥
	//     ⎣.  .  6⎦
	//
	// after modification with only non-zero values:
	// a = ⎡1  2  .⎤
	//     ⎢.  4  5⎥
	//     ⎣.  .  6⎦
}
示例#11
0
func TestBackward(t *testing.T) {
	neuralNetwork := CreateSimpleNetwork(t)
	inputs := mat64.NewDense(1, 2, []float64{0.05, 0.10})
	neuralNetwork.Forward(inputs)
	values := mat64.NewDense(1, 2, []float64{0.01, 0.99})
	neuralNetwork.Backward(values)
	expected_gradient_1 := mat64.NewDense(2, 1, []float64{0.13849856, -0.03809824})
	if !mat64.EqualApprox(
		neuralNetwork.Layers[1].Deltas, expected_gradient_1, 0.0001) {
		t.Errorf("gradient 1 unexpected:\n%v",
			mat64.Formatted(neuralNetwork.Layers[1].Deltas))
	}
	// TODO(ariw): Fill in the other value of layer 0's gradient when known.
	if !equalsApprox(0.00877136, neuralNetwork.Layers[0].Deltas.At(0, 0),
		0.0001) {
		t.Errorf("gradient 0 unexpected:\n%v",
			mat64.Formatted(neuralNetwork.Layers[0].Deltas))
	}
}
示例#12
0
func ExampleSymDense_SubsetSym() {
	n := 5
	s := mat64.NewSymDense(5, nil)
	count := 1.0
	for i := 0; i < n; i++ {
		for j := i; j < n; j++ {
			s.SetSym(i, j, count)
			count++
		}
	}
	fmt.Println("Original matrix:")
	fmt.Printf("%0.4v\n\n", mat64.Formatted(s))

	// Take the subset {0, 2, 4}
	var sub mat64.SymDense
	sub.SubsetSym(s, []int{0, 2, 4})
	fmt.Println("Subset {0, 2, 4}")
	fmt.Printf("%0.4v\n\n", mat64.Formatted(&sub))

	// Take the subset {0, 0, 4}
	sub.SubsetSym(s, []int{0, 0, 4})
	fmt.Println("Subset {0, 0, 4}")
	fmt.Printf("%0.4v\n\n", mat64.Formatted(&sub))

	// Output:
	// Original matrix:
	// ⎡ 1   2   3   4   5⎤
	// ⎢ 2   6   7   8   9⎥
	// ⎢ 3   7  10  11  12⎥
	// ⎢ 4   8  11  13  14⎥
	// ⎣ 5   9  12  14  15⎦
	//
	// Subset {0, 2, 4}
	// ⎡ 1   3   5⎤
	// ⎢ 3  10  12⎥
	// ⎣ 5  12  15⎦
	//
	// Subset {0, 0, 4}
	// ⎡ 1   1   5⎤
	// ⎢ 1   1   5⎥
	// ⎣ 5   5  15⎦
}
示例#13
0
func TestUndirect(t *testing.T) {
	for _, test := range directedGraphs {
		g := test.g()
		for _, e := range test.edges {
			g.SetEdge(e)
		}

		src := graph.Undirect{G: g, Absent: test.absent, Merge: test.merge}
		dst := simple.NewUndirectedMatrixFrom(src.Nodes(), 0, 0, 0)
		for _, u := range src.Nodes() {
			for _, v := range src.From(u) {
				dst.SetEdge(src.Edge(u, v))
			}
		}

		if !mat64.Equal(dst.Matrix(), test.want) {
			t.Errorf("unexpected result:\ngot:\n%.4v\nwant:\n%.4v",
				mat64.Formatted(dst.Matrix()),
				mat64.Formatted(test.want),
			)
		}
	}
}
func main() {
	a := Vandermonde(x, 2)
	b := mat64.NewDense(11, 1, y)
	c := mat64.NewDense(3, 1, nil)

	qr := new(mat64.QR)
	qr.Factorize(a)

	err := c.SolveQR(qr, false, b)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%.3f\n", mat64.Formatted(c))
	}
}
func main() {
	a := mat64.NewDense(2, 4, []float64{
		1, 2, 3, 4,
		5, 6, 7, 8,
	})
	b := mat64.NewDense(4, 3, []float64{
		1, 2, 3,
		4, 5, 6,
		7, 8, 9,
		10, 11, 12,
	})
	var m mat64.Dense
	m.Mul(a, b)
	fmt.Println(mat64.Formatted(&m))
}
示例#16
0
func ExamplePrincipalComponents() {
	// iris is a truncated sample of the Fisher's Iris dataset.
	n := 10
	d := 4
	iris := mat64.NewDense(n, d, []float64{
		5.1, 3.5, 1.4, 0.2,
		4.9, 3.0, 1.4, 0.2,
		4.7, 3.2, 1.3, 0.2,
		4.6, 3.1, 1.5, 0.2,
		5.0, 3.6, 1.4, 0.2,
		5.4, 3.9, 1.7, 0.4,
		4.6, 3.4, 1.4, 0.3,
		5.0, 3.4, 1.5, 0.2,
		4.4, 2.9, 1.4, 0.2,
		4.9, 3.1, 1.5, 0.1,
	})

	// Calculate the principal component direction vectors
	// and variances.
	vecs, vars, ok := stat.PrincipalComponents(iris, nil)
	if !ok {
		return
	}
	fmt.Printf("variances = %.4f\n\n", vars)

	// Project the data onto the first 2 principal components.
	k := 2
	var proj mat64.Dense
	proj.Mul(iris, vecs.View(0, 0, d, k))

	fmt.Printf("proj = %.4f", mat64.Formatted(&proj, mat64.Prefix("       ")))

	// Output:
	// variances = [0.1666 0.0207 0.0079 0.0019]
	//
	// proj = ⎡-6.1686   1.4659⎤
	//        ⎢-5.6767   1.6459⎥
	//        ⎢-5.6699   1.3642⎥
	//        ⎢-5.5643   1.3816⎥
	//        ⎢-6.1734   1.3309⎥
	//        ⎢-6.7278   1.4021⎥
	//        ⎢-5.7743   1.1498⎥
	//        ⎢-6.0466   1.4714⎥
	//        ⎢-5.2709   1.3570⎥
	//        ⎣-5.7533   1.6207⎦
}
func main() {
	fmt.Println(mat64.Formatted(eye(3)))
}
func cholesky(order int, elements []float64) fmt.Formatter {
	t := mat64.NewTriDense(order, false, nil)
	t.Cholesky(mat64.NewSymDense(order, elements), false)
	return mat64.Formatted(t)
}
示例#19
0
func TestMetropolisHastingser(t *testing.T) {
	for seed, test := range []struct {
		dim, burnin, rate, samples int
	}{
		{3, 10, 1, 1},
		{3, 10, 2, 1},
		{3, 10, 1, 2},
		{3, 10, 3, 2},
		{3, 10, 7, 4},
		{3, 10, 7, 4},

		{3, 11, 51, 103},
		{3, 11, 103, 51},
		{3, 51, 11, 103},
		{3, 51, 103, 11},
		{3, 103, 11, 51},
		{3, 103, 51, 11},
	} {
		dim := test.dim

		initial := make([]float64, dim)
		target, ok := randomNormal(dim)
		if !ok {
			t.Fatal("bad test, sigma not pos def")
		}

		sigmaImp := mat64.NewSymDense(dim, nil)
		for i := 0; i < dim; i++ {
			sigmaImp.SetSym(i, i, 0.25)
		}
		proposal, ok := NewProposalNormal(sigmaImp, nil)
		if !ok {
			t.Fatal("bad test, sigma not pos def")
		}

		// Test the Metropolis Hastingser by generating all the samples, then generating
		// the same samples with a burnin and rate.
		rand.Seed(int64(seed))
		mh := MetropolisHastingser{
			Initial:  initial,
			Target:   target,
			Proposal: proposal,
			Src:      nil,
			BurnIn:   0,
			Rate:     0,
		}
		samples := test.samples
		burnin := test.burnin
		rate := test.rate
		fullBatch := mat64.NewDense(1+burnin+rate*(samples-1), dim, nil)
		mh.Sample(fullBatch)
		mh = MetropolisHastingser{
			Initial:  initial,
			Target:   target,
			Proposal: proposal,
			Src:      nil,
			BurnIn:   burnin,
			Rate:     rate,
		}
		rand.Seed(int64(seed))
		batch := mat64.NewDense(samples, dim, nil)
		mh.Sample(batch)

		same := true
		count := burnin
		for i := 0; i < samples; i++ {
			if !floats.Equal(batch.RawRowView(i), fullBatch.RawRowView(count)) {
				fmt.Println("sample ", i, "is different")
				same = false
				break
			}
			count += rate
		}

		if !same {
			fmt.Printf("%v\n", mat64.Formatted(batch))
			fmt.Printf("%v\n", mat64.Formatted(fullBatch))

			t.Errorf("sampling mismatch: dim = %v, burnin = %v, rate = %v, samples = %v", dim, burnin, rate, samples)
		}
	}
}
示例#20
0
func printMatrix(M mat.Matrix) fmt.Formatter {
	return mat.Formatted(M, mat.Prefix(""))
}
示例#21
0
func TestPrincipalComponents(t *testing.T) {
	for i, test := range []struct {
		data     mat64.Matrix
		weights  []float64
		wantVecs *mat64.Dense
		wantVars []float64
		epsilon  float64
	}{
		// Test results verified using R.
		{
			data: mat64.NewDense(3, 3, []float64{
				1, 2, 3,
				4, 5, 6,
				7, 8, 9,
			}),
			wantVecs: mat64.NewDense(3, 3, []float64{
				0.5773502691896258, 0.8164965809277261, 0,
				0.577350269189626, -0.4082482904638632, -0.7071067811865476,
				0.5773502691896258, -0.4082482904638631, 0.7071067811865475,
			}),
			wantVars: []float64{27, 0, 0},
			epsilon:  1e-12,
		},
		{ // Truncated iris data.
			data: mat64.NewDense(10, 4, []float64{
				5.1, 3.5, 1.4, 0.2,
				4.9, 3.0, 1.4, 0.2,
				4.7, 3.2, 1.3, 0.2,
				4.6, 3.1, 1.5, 0.2,
				5.0, 3.6, 1.4, 0.2,
				5.4, 3.9, 1.7, 0.4,
				4.6, 3.4, 1.4, 0.3,
				5.0, 3.4, 1.5, 0.2,
				4.4, 2.9, 1.4, 0.2,
				4.9, 3.1, 1.5, 0.1,
			}),
			wantVecs: mat64.NewDense(4, 4, []float64{
				-0.6681110197952722, 0.7064764857539533, -0.14026590216895132, -0.18666578956412125,
				-0.7166344774801547, -0.6427036135482664, -0.135650285905254, 0.23444848208629923,
				-0.164411275166307, 0.11898477441068218, 0.9136367900709548, 0.35224901970831746,
				-0.11415613655453069, -0.2714141920887426, 0.35664028439226514, -0.8866286823515034,
			}),
			wantVars: []float64{0.1665786313282786, 0.02065509475412993, 0.007944620317765855, 0.0019327647109368329},
			epsilon:  1e-12,
		},
		{ // Truncated iris data transposed to check for operation on fat input.
			data: mat64.NewDense(10, 4, []float64{
				5.1, 3.5, 1.4, 0.2,
				4.9, 3.0, 1.4, 0.2,
				4.7, 3.2, 1.3, 0.2,
				4.6, 3.1, 1.5, 0.2,
				5.0, 3.6, 1.4, 0.2,
				5.4, 3.9, 1.7, 0.4,
				4.6, 3.4, 1.4, 0.3,
				5.0, 3.4, 1.5, 0.2,
				4.4, 2.9, 1.4, 0.2,
				4.9, 3.1, 1.5, 0.1,
			}).T(),
			wantVecs: mat64.NewDense(10, 4, []float64{
				-0.3366602459946619, -0.1373634006401213, 0.3465102523547623, -0.10290179303893479,
				-0.31381852053861975, 0.5197145790632827, 0.5567296129086686, -0.15923062170153618,
				-0.30857197637565165, -0.07670930360819002, 0.36159923003337235, 0.3342301027853355,
				-0.29527124351656137, 0.16885455995353074, -0.5056204762881208, 0.32580913261444344,
				-0.3327611073694004, -0.39365834489416474, 0.04900050959307464, 0.46812879383236555,
				-0.34445484362044815, -0.2985206914561878, -0.1009714701361799, -0.16803618186050803,
				-0.2986246350957691, -0.4222037823717799, -0.11838613462182519, -0.580283530375069,
				-0.325911246223126, 0.024366468758217238, -0.12082035131864265, 0.16756027181337868,
				-0.2814284432361538, 0.240812316260054, -0.24061437569068145, -0.365034616264623,
				-0.31906138507685167, 0.4423912824105986, -0.2906412122303604, 0.027551046870337714,
			}),
			wantVars: []float64{41.8851906634233, 0.07762619213464989, 0.010516477775373585, 0},
			epsilon:  1e-12,
		},
		{ // Truncated iris data unitary weights.
			data: mat64.NewDense(10, 4, []float64{
				5.1, 3.5, 1.4, 0.2,
				4.9, 3.0, 1.4, 0.2,
				4.7, 3.2, 1.3, 0.2,
				4.6, 3.1, 1.5, 0.2,
				5.0, 3.6, 1.4, 0.2,
				5.4, 3.9, 1.7, 0.4,
				4.6, 3.4, 1.4, 0.3,
				5.0, 3.4, 1.5, 0.2,
				4.4, 2.9, 1.4, 0.2,
				4.9, 3.1, 1.5, 0.1,
			}),
			weights: []float64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
			wantVecs: mat64.NewDense(4, 4, []float64{
				-0.6681110197952722, 0.7064764857539533, -0.14026590216895132, -0.18666578956412125,
				-0.7166344774801547, -0.6427036135482664, -0.135650285905254, 0.23444848208629923,
				-0.164411275166307, 0.11898477441068218, 0.9136367900709548, 0.35224901970831746,
				-0.11415613655453069, -0.2714141920887426, 0.35664028439226514, -0.8866286823515034,
			}),
			wantVars: []float64{0.1665786313282786, 0.02065509475412993, 0.007944620317765855, 0.0019327647109368329},
			epsilon:  1e-12,
		},
		{ // Truncated iris data non-unitary weights.
			data: mat64.NewDense(10, 4, []float64{
				5.1, 3.5, 1.4, 0.2,
				4.9, 3.0, 1.4, 0.2,
				4.7, 3.2, 1.3, 0.2,
				4.6, 3.1, 1.5, 0.2,
				5.0, 3.6, 1.4, 0.2,
				5.4, 3.9, 1.7, 0.4,
				4.6, 3.4, 1.4, 0.3,
				5.0, 3.4, 1.5, 0.2,
				4.4, 2.9, 1.4, 0.2,
				4.9, 3.1, 1.5, 0.1,
			}),
			weights: []float64{2, 3, 1, 1, 1, 1, 1, 1, 1, 2},
			wantVecs: mat64.NewDense(4, 4, []float64{
				-0.618936145422414, 0.763069301531647, 0.124857741232537, 0.138035623677211,
				-0.763958271606519, -0.603881770702898, 0.118267155321333, -0.194184052457746,
				-0.143552119754944, 0.090014599564871, -0.942209377020044, -0.289018426115945,
				-0.112599271966947, -0.212012782487076, -0.287515067921680, 0.927203898682805,
			}),
			wantVars: []float64{0.129621985550623, 0.022417487771598, 0.006454461065715, 0.002495076601075},
			epsilon:  1e-12,
		},
	} {
		vecs, vars, ok := PrincipalComponents(test.data, test.weights)
		if !ok {
			t.Errorf("unexpected SVD failure for test %d", i)
			continue
		}
		if !mat64.EqualApprox(vecs, test.wantVecs, test.epsilon) {
			t.Errorf("%d: unexpected PCA result got:\n%v\nwant:\n%v",
				i, mat64.Formatted(vecs), mat64.Formatted(test.wantVecs))
		}
		if !approxEqual(vars, test.wantVars, test.epsilon) {
			t.Errorf("%d: unexpected variance result got:%v, want:%v", i, vars, test.wantVars)
		}
	}
}
func main() {
	x, y := givens()
	fmt.Printf("%.4f\n", mat64.Formatted(mat64.QR(x).Solve(y)))
}
示例#23
0
func main() {
	flag.Parse()
	log.SetFlags(0)

	var tourn Tournament

	if *demo {
		tourn = Tournament{
			{"bob-r", "joe-c"},
			{"bob-r", "tim-c"},
			{"bob-r", "tim-c"},
			{"bob-r", "tim-c"},
			{"joe-r", "tim-c"},
			{"joe-r", "bob-c"},
			{"tim-r", "joe-c"},
			{"tim-r", "bob-c"},
			{"bob-c", "joe-r"},
			{"bob-c", "tim-r"},
			{"joe-c", "tim-r"},
			{"joe-c", "bob-r"},
			{"tim-c", "joe-r"},
			{"tim-c", "bob-r"},
		}
	} else {
		matches, err := ParseMatches(os.Stdin)
		if err != nil {
			log.Fatal(err)
		}
		tourn = Tournament(matches)
	}

	if *graph {
		tourn.Graph(os.Stdout)
		return
	} else if *matrix {
		prefix := "tournmat = "
		fmt.Printf("%v%v\n", prefix, mat64.Formatted(tourn.Matrix(), mat64.Prefix(strings.Repeat(" ", len(prefix)))))
		return
	} else if *eigvect {
		eig := mat64.Eigen(tourn.Matrix(), 1e-10)
		prefix := "eigvects = "
		fmt.Printf("%v%.4v\n", prefix, mat64.Formatted(eig.V, mat64.Prefix(strings.Repeat(" ", len(prefix)))))
		return
	} else if *eigval {
		eig := mat64.Eigen(tourn.Matrix(), 1e-10)
		prefix := "eigvals = "
		fmt.Printf("%v%.4v\n", prefix, mat64.Formatted(eig.D(), mat64.Prefix(strings.Repeat(" ", len(prefix)))))
		return
	}

	ranks := tourn.Ranks()
	if ranks == nil {
		log.Fatalf("no valid eigenvector ranking found")
	}

	players := tourn.Players()
	for i, rank := range ranks {
		fmt.Printf("%v\t%.2v\n", players[i], rank)
	}

}