public int[] Argmax(IWeightTensor w, int dim) { int[] idx = null; WeightTensor m = w as WeightTensor; using (Tensor argMaxT = Ops.Argmax(null, m.TWeight, dim)) { float[] res = new float[argMaxT.ElementCount()]; argMaxT.CopyToArray(res); idx = new int[res.Length]; for (int i = 0; i < res.Length; i++) { idx[i] = (int)res[i]; } } return(idx); }
static void PredictMnist(string modelPath, string xtestPath, string ytestPath = null) { var xtest = TensorUtils.Deserialize(File.OpenRead(xtestPath)); xtest = xtest.Cast(DType.Float32); xtest = Ops.Div(null, xtest, 255f); // xtest = xtest.Narrow(0, 0, 101); var model = Sequential.Load(modelPath); var result = model.Predict(xtest, batchSize: 32); if (ytestPath == null) { return; } var ytest = TensorUtils.Deserialize(File.OpenRead(ytestPath)); ytest = ytest.Cast(DType.Float32); // ytest = ytest.Narrow(0, 0, 101); ytest = Ops.Argmax(null, ytest, 1).Squeeze(); var t = result.Narrow(0, 0, 11); // Console.WriteLine(t.Format()); result = Ops.Argmax(null, result, 1).Squeeze(); t = result.Narrow(0, 0, 11); // Console.WriteLine(t.Format()); double sum = 0.0; for (var i = 0; i < ytest.Sizes[0]; ++i) { sum += (int)ytest.GetElementAsFloat(i) == (int)result.GetElementAsFloat(i) ? 1.0 : 0.0; } Console.WriteLine($"Accuracy: {sum / ytest.Sizes[0] * 100}%"); }
/// <summary> /// Argmaxes the specified dimension. /// </summary> /// <param name="dimension">The dimension.</param> /// <returns>TVar.</returns> public Variable Argmax(int dimension) { return(new Variable(new UnaryTensorExpression(this.Expression, (result, src) => Ops.Argmax(result, src, dimension)))); }