From e0271f8227d150c9a7e6cb788cab049a6c60f2ec Mon Sep 17 00:00:00 2001 From: Matteo Fabbri Date: Tue, 20 Feb 2018 14:36:50 +0100 Subject: [PATCH] simplified some Count() calls --- Src/numl.Tests/CollectionTests/CollectionsTests.cs | 2 +- Src/numl.Tests/DataTests/GraphTests.cs | 6 +++--- Src/numl/AI/Search/AdversarialSearch.cs | 2 +- Src/numl/Learner.cs | 2 +- Src/numl/Math/LinearAlgebra/MatrixStatics.cs | 4 ++-- Src/numl/Math/LinearAlgebra/VectorExtensions.cs | 9 +++++---- Src/numl/Model/Descriptor.cs | 5 +---- Src/numl/Recommendation/CofiRecommenderGenerator.cs | 2 +- Src/numl/Reinforcement/ReinforcementGenerator.cs | 6 +++--- Src/numl/Supervised/Classification/MultiClassLearner.cs | 2 +- .../Supervised/DecisionTree/DecisionTreeGenerator.cs | 2 +- Src/numl/Supervised/Generator.cs | 4 ++-- Src/numl/Supervised/NeuralNetwork/NetworkOps.cs | 5 +++-- Src/numl/Supervised/Score.cs | 4 ++-- 14 files changed, 27 insertions(+), 28 deletions(-) diff --git a/Src/numl.Tests/CollectionTests/CollectionsTests.cs b/Src/numl.Tests/CollectionTests/CollectionsTests.cs index a11b561..3657413 100644 --- a/Src/numl.Tests/CollectionTests/CollectionsTests.cs +++ b/Src/numl.Tests/CollectionTests/CollectionsTests.cs @@ -137,7 +137,7 @@ public void NSortedList_Size_Test() var contains = (dict.Where(w => w.Value == 0 && sorted.Contains(w.Key))); - bool result = (contains.Count() == 0); + bool result = (!contains.Any()); Assert.True(result, "Length was not equal to the elements in the collection"); diff --git a/Src/numl.Tests/DataTests/GraphTests.cs b/Src/numl.Tests/DataTests/GraphTests.cs index 9eb6818..9ea43f0 100644 --- a/Src/numl.Tests/DataTests/GraphTests.cs +++ b/Src/numl.Tests/DataTests/GraphTests.cs @@ -167,8 +167,8 @@ public void RemoveVertexTest() g.RemoveVertex(vertex1); - Assert.Equal(0, g.GetVertices().Where(v => v.Id == 1).Count()); - Assert.Equal(0, g.GetEdges().Where(e => e.ParentId == 1 || e.ChildId == 1).Count()); + Assert.Equal(0, g.GetVertices().Count(v => v.Id == 1)); + Assert.Equal(0, g.GetEdges().Count(e => e.ParentId == 1 || e.ChildId == 1)); } [Fact] @@ -190,7 +190,7 @@ public void RemoveEdgeTest() g.RemoveEdge(edge); - Assert.Equal(0, g.GetEdges().Where(e => e.ParentId == 1 && e.ChildId == 5).Count()); + Assert.Equal(0, g.GetEdges().Count(e => e.ParentId == 1 && e.ChildId == 5)); } diff --git a/Src/numl/AI/Search/AdversarialSearch.cs b/Src/numl/AI/Search/AdversarialSearch.cs index 2e0bad8..30d1f5f 100644 --- a/Src/numl/AI/Search/AdversarialSearch.cs +++ b/Src/numl/AI/Search/AdversarialSearch.cs @@ -28,7 +28,7 @@ internal Node GetBestChildNode(Node node, double v) .Where(n => n.Cost == v && n.State.IsTerminal); Node r; - if (q.Count() > 0) // favor terminal nodes first + if (q.Any()) // favor terminal nodes first r = q.Random(); else r = node.Children diff --git a/Src/numl/Learner.cs b/Src/numl/Learner.cs index 84d4b3d..3650158 100644 --- a/Src/numl/Learner.cs +++ b/Src/numl/Learner.cs @@ -141,7 +141,7 @@ private static LearningModel GenerateModel(IGenerator generator, Matrix x, Vecto Score score = new Score(); - if (testingSlice.Count() > 0) + if (testingSlice.Any()) { // testing object[] test = GetTestExamples(testingSlice, examples); diff --git a/Src/numl/Math/LinearAlgebra/MatrixStatics.cs b/Src/numl/Math/LinearAlgebra/MatrixStatics.cs index 63c454a..4f7554f 100644 --- a/Src/numl/Math/LinearAlgebra/MatrixStatics.cs +++ b/Src/numl/Math/LinearAlgebra/MatrixStatics.cs @@ -700,8 +700,8 @@ public static Matrix Slice(Matrix m, IEnumerable indices, VectorType t) { var q = indices.Distinct(); - int rows = t == VectorType.Row ? q.Where(j => j < m.Rows).Count() : m.Rows; - int cols = t == VectorType.Col ? q.Where(j => j < m.Cols).Count() : m.Cols; + int rows = t == VectorType.Row ? q.Count(j => j < m.Rows) : m.Rows; + int cols = t == VectorType.Col ? q.Count(j => j < m.Cols) : m.Cols; Matrix n = new Matrix(rows, cols); diff --git a/Src/numl/Math/LinearAlgebra/VectorExtensions.cs b/Src/numl/Math/LinearAlgebra/VectorExtensions.cs index 7c966e0..e673ca6 100644 --- a/Src/numl/Math/LinearAlgebra/VectorExtensions.cs +++ b/Src/numl/Math/LinearAlgebra/VectorExtensions.cs @@ -160,8 +160,7 @@ public static Vector ToVector(this double[] array) /// e as a Matrix. public static Matrix ToMatrix(this IEnumerable source, VectorType vectorType = VectorType.Row) { - var c = source.Count(); - if (c == 0) + if (!source.Any()) throw new InvalidOperationException("Cannot create matrix from an empty set."); return Matrix.Stack(vectorType, source.ToArray()); @@ -333,7 +332,7 @@ group i by i into g select new { key = g.Key, - count = source.Where(d => d == g.Key).Count() + count = source.Count(d => d == g.Key) }; double mode = -1; @@ -801,7 +800,9 @@ public static bool IsNaN(this Vector vector) public static bool IsBinary(this Vector vector) { var v = vector.Distinct(); - return ((v.Count() == 2 && (v.Contains(1d) && (v.Contains(0d) || v.Contains(-1d)))) || (v.Count() == 1 && (v.Contains(1d) || v.Contains(0d) || v.Contains(-1d)))); + var count = v.Count(); + + return ((count == 2 && (v.Contains(1d) && (v.Contains(0d) || v.Contains(-1d)))) || (count == 1 && (v.Contains(1d) || v.Contains(0d) || v.Contains(-1d)))); } /// diff --git a/Src/numl/Model/Descriptor.cs b/Src/numl/Model/Descriptor.cs index 8645564..25347f7 100644 --- a/Src/numl/Model/Descriptor.cs +++ b/Src/numl/Model/Descriptor.cs @@ -59,10 +59,7 @@ public Property this[string name] { get { - if (Features.Where(p => p.Name == name).Count() == 1) - return Features.Where(p => p.Name == name).First(); - else - return null; + return Features.Count(p => p.Name == name) == 1 ? Features.First(p => p.Name == name) : null; } } /// diff --git a/Src/numl/Recommendation/CofiRecommenderGenerator.cs b/Src/numl/Recommendation/CofiRecommenderGenerator.cs index a8b17e7..0b6ed17 100644 --- a/Src/numl/Recommendation/CofiRecommenderGenerator.cs +++ b/Src/numl/Recommendation/CofiRecommenderGenerator.cs @@ -82,7 +82,7 @@ public override IModel Generate(Matrix X, Vector y) // The mean needs to be values within rating range only. Vector mean = X.GetRows().Select(s => s.Where(w => this.Ratings.Test(w)).Sum() / - s.Where(w => this.Ratings.Test(w)).Count() + s.Count(w => this.Ratings.Test(w)) ).ToVector(); // update feature averages before preprocessing features. diff --git a/Src/numl/Reinforcement/ReinforcementGenerator.cs b/Src/numl/Reinforcement/ReinforcementGenerator.cs index b835567..e9ddfd9 100644 --- a/Src/numl/Reinforcement/ReinforcementGenerator.cs +++ b/Src/numl/Reinforcement/ReinforcementGenerator.cs @@ -123,7 +123,7 @@ public virtual void Preprocess(Matrix X1, Vector y, Matrix X2, Vector r) /// IReinforcementModel. public IReinforcementModel Generate(Descriptor description, IEnumerable examples) { - if (examples.Count() == 0) throw new InvalidOperationException("Empty example set."); + if (!examples.Any()) throw new InvalidOperationException("Empty example set."); Descriptor = description; if (Descriptor.Features == null || Descriptor.Features.Length == 0) @@ -169,7 +169,7 @@ public IReinforcementModel Generate(Descriptor descriptor, IEnumerable exa /// IReinforcementModel. public IReinforcementModel Generate(IEnumerable examples1, IEnumerable examples2) { - if (examples1.Count() == 0) throw new InvalidOperationException("Empty example set."); + if (!examples1.Any()) throw new InvalidOperationException("Empty example set."); if (this.Descriptor == null) throw new InvalidOperationException("Descriptor is null"); @@ -188,7 +188,7 @@ public IReinforcementModel Generate(IEnumerable examples1, IEnumerableIReinforcementModel. public IReinforcementModel Generate(Descriptor descriptor, IEnumerable examples1, Descriptor transitionDescriptor, IEnumerable examples2) { - if (examples1.Count() == 0) throw new InvalidOperationException("Empty example set."); + if (!examples1.Any()) throw new InvalidOperationException("Empty example set."); bool hasTransitionStates = (examples2 != null && examples2.Any()); diff --git a/Src/numl/Supervised/Classification/MultiClassLearner.cs b/Src/numl/Supervised/Classification/MultiClassLearner.cs index a6ae1ab..7a583ee 100644 --- a/Src/numl/Supervised/Classification/MultiClassLearner.cs +++ b/Src/numl/Supervised/Classification/MultiClassLearner.cs @@ -79,7 +79,7 @@ private static Tuple GenerateModel(IGenerator genera Score score = new Score(); - if (testingSlice.Count() > 0) + if (testingSlice.Any()) { object[] testExamples = examples.Slice(testingSlice).ToArray(); var testing = generator.Descriptor.Convert(testExamples, true).ToExamples(); diff --git a/Src/numl/Supervised/DecisionTree/DecisionTreeGenerator.cs b/Src/numl/Supervised/DecisionTree/DecisionTreeGenerator.cs index 399fcc0..795b96b 100644 --- a/Src/numl/Supervised/DecisionTree/DecisionTreeGenerator.cs +++ b/Src/numl/Supervised/DecisionTree/DecisionTreeGenerator.cs @@ -184,7 +184,7 @@ private Node BuildTree(Matrix x, Vector y, int depth, List used, Tree tree) // if this number is 0 then this edge // leads to a dead end - the edge will // not be built - if (slice.Count() > 0) + if (slice.Any()) { Vector ySlice = y.Slice(slice); // only one answer, set leaf diff --git a/Src/numl/Supervised/Generator.cs b/Src/numl/Supervised/Generator.cs index 1bac53b..5afcb8b 100644 --- a/Src/numl/Supervised/Generator.cs +++ b/Src/numl/Supervised/Generator.cs @@ -131,7 +131,7 @@ public virtual Matrix ToEncoded(Vector y) /// Model. public IModel Generate(IEnumerable examples) { - if (examples.Count() == 0) throw new InvalidOperationException("Empty example set."); + if (!examples.Any()) throw new InvalidOperationException("Empty example set."); if (Descriptor == null) throw new InvalidOperationException("Descriptor is null"); @@ -146,7 +146,7 @@ public IModel Generate(IEnumerable examples) /// Model. public IModel Generate(Descriptor description, IEnumerable examples) { - if (examples.Count() == 0) throw new InvalidOperationException("Empty example set."); + if (!examples.Any()) throw new InvalidOperationException("Empty example set."); Descriptor = description; if (Descriptor.Features == null || Descriptor.Features.Length == 0) diff --git a/Src/numl/Supervised/NeuralNetwork/NetworkOps.cs b/Src/numl/Supervised/NeuralNetwork/NetworkOps.cs index 847b4ad..8a7723f 100644 --- a/Src/numl/Supervised/NeuralNetwork/NetworkOps.cs +++ b/Src/numl/Supervised/NeuralNetwork/NetworkOps.cs @@ -194,7 +194,8 @@ public static Network Create(this Network network, int inputLayer, int outputLay /// public static Network AddConnections(this Network network, Neuron node, IEnumerable parentNodes, IEnumerable childNodes, double epsilon = double.NaN) { - if (epsilon == double.NaN) + //episilon == double.Nan will be always false, even if epsilon is Nan + if (double.IsNaN(epsilon)) epsilon = Edge.GetEpsilon(node.ActivationFunction.Minimum, node.ActivationFunction.Maximum, parentNodes.Count(), childNodes.Count()); if (parentNodes != null) @@ -257,7 +258,7 @@ public static Vector GetBiases(this Network network, int layer = 0) var nodes = network.GetNodes(layer + 1).ToArray(); - Vector biases = Vector.Zeros(nodes.Where(w => !w.IsBias).Count()); + Vector biases = Vector.Zeros(nodes.Count(w => !w.IsBias)); for (int i = 0; i < nodes.Length; i++) { diff --git a/Src/numl/Supervised/Score.cs b/Src/numl/Supervised/Score.cs index 352041d..f87193c 100644 --- a/Src/numl/Supervised/Score.cs +++ b/Src/numl/Supervised/Score.cs @@ -318,8 +318,8 @@ public static Score ScorePredictions(Vector predictions, Vector actual, { var score = new numl.Supervised.Score() { - TotalPositives = actual.Where(w => w == truthLabel).Count(), - TotalNegatives = actual.Where(w => (w == falseLabel || w != truthLabel)).Count(), + TotalPositives = actual.Count(w => w == truthLabel), + TotalNegatives = actual.Count(w => (w == falseLabel || w != truthLabel)), TruePositives = actual.Where((i, idx) => i == truthLabel && i == predictions[idx]).Count(), FalsePositives = actual.Where((i, idx) => (i == falseLabel || i != truthLabel) && predictions[idx] == truthLabel).Count(),