Changeset 17502
- Timestamp:
- 04/09/20 14:01:09 (5 years ago)
- Location:
- branches/3040_VectorBasedGP
- Files:
-
- 4 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/3040_VectorBasedGP/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Views/3.4/InteractiveSymbolicRegressionSolutionSimplifierView.cs
r17489 r17502 64 64 int reps = 0; 65 65 66 do { 67 prevResult = result; 68 //tree = NonlinearLeastSquaresConstantOptimizationEvaluator.OptimizeTree(tree, regressionProblemData, regressionProblemData.TrainingIndices, 69 // applyLinearScaling: true, maxIterations: constOptIterations, updateVariableWeights: true, 70 // cancellationToken: cancellationToken, iterationCallback: (args, func, obj) => { 71 // double newProgressValue = progress.ProgressValue + (1.0 / (constOptIterations + 2) / maxRepetitions); // (constOptIterations + 2) iterations are reported 72 // progress.ProgressValue = Math.Min(newProgressValue, 1.0); 73 // }); 74 tree = TensorFlowConstantOptimizationEvaluator.OptimizeTree(tree, regressionProblemData, regressionProblemData.TrainingIndices, 75 applyLinearScaling: true, updateVariableWeights: true, maxIterations: 10, learningRate: 0.001); 76 result = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(model.Interpreter, tree, 77 model.LowerEstimationLimit, model.UpperEstimationLimit, regressionProblemData, regressionProblemData.TrainingIndices, applyLinearScaling: true); 78 reps++; 79 improvement = result - prevResult; 80 } while (improvement > minimumImprovement && reps < maxRepetitions && 81 progress.ProgressState != ProgressState.StopRequested && 82 progress.ProgressState != ProgressState.CancelRequested); 83 return tree; 66 //do { 67 // prevResult = result; 68 // tree = NonlinearLeastSquaresConstantOptimizationEvaluator.OptimizeTree(tree, regressionProblemData, regressionProblemData.TrainingIndices, 69 // applyLinearScaling: true, maxIterations: constOptIterations, updateVariableWeights: true, 70 // cancellationToken: cancellationToken, iterationCallback: (args, func, obj) => { 71 // double newProgressValue = progress.ProgressValue + (1.0 / (constOptIterations + 2) / maxRepetitions); // (constOptIterations + 2) iterations are reported 72 // progress.ProgressValue = Math.Min(newProgressValue, 1.0); 73 // }); 74 // result = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(model.Interpreter, tree, 75 // model.LowerEstimationLimit, model.UpperEstimationLimit, regressionProblemData, regressionProblemData.TrainingIndices, applyLinearScaling: true); 76 // reps++; 77 // improvement = result - prevResult; 78 //} while (improvement > minimumImprovement && reps < maxRepetitions && 79 // progress.ProgressState != ProgressState.StopRequested && 80 // progress.ProgressState != ProgressState.CancelRequested); 81 //return tree; 82 const int maxIterations = 1000; 83 return TensorFlowConstantOptimizationEvaluator.OptimizeTree(tree, regressionProblemData, 84 regressionProblemData.TrainingIndices, 85 applyLinearScaling: false, updateVariableWeights: true, maxIterations: maxIterations, learningRate: 0.0001, 86 cancellationToken: cancellationToken, 87 progress: new SynchronousProgress<double>(cost => { 88 var newProgress = progress.ProgressValue + (1.0 / (maxIterations + 1)); 89 progress.ProgressValue = Math.Min(newProgress, 1.0); 90 progress.Message = $"MSE: {cost}"; 91 }) 92 ); 93 } 94 95 internal class SynchronousProgress<T> : IProgress<T> { 96 private readonly Action<T> callback; 97 public SynchronousProgress(Action<T> callback) { 98 this.callback = callback; 99 } 100 public void Report(T value) { 101 callback(value); 102 } 84 103 } 85 104 } -
branches/3040_VectorBasedGP/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression-3.4.csproj
r17475 r17502 47 47 <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> 48 48 <Prefer32Bit>false</Prefer32Bit> 49 <LangVersion>7</LangVersion> 49 50 </PropertyGroup> 50 51 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> … … 57 58 <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> 58 59 <Prefer32Bit>false</Prefer32Bit> 60 <LangVersion>7</LangVersion> 59 61 </PropertyGroup> 60 62 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' "> … … 67 69 <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> 68 70 <Prefer32Bit>false</Prefer32Bit> 71 <LangVersion>7</LangVersion> 69 72 </PropertyGroup> 70 73 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' "> … … 77 80 <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> 78 81 <Prefer32Bit>false</Prefer32Bit> 82 <LangVersion>7</LangVersion> 79 83 </PropertyGroup> 80 84 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> … … 87 91 <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> 88 92 <Prefer32Bit>false</Prefer32Bit> 93 <LangVersion>7</LangVersion> 89 94 </PropertyGroup> 90 95 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' "> … … 97 102 <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> 98 103 <Prefer32Bit>false</Prefer32Bit> 104 <LangVersion>7</LangVersion> 99 105 </PropertyGroup> 100 106 <ItemGroup> … … 113 119 </Reference> 114 120 <Reference Include="System.Drawing" /> 121 <Reference Include="System.Numerics" /> 115 122 <Reference Include="System.Xml.Linq"> 116 123 <RequiredTargetFramework>3.5</RequiredTargetFramework> -
branches/3040_VectorBasedGP/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/TensorFlowConstantOptimizationEvaluator.cs
r17493 r17502 20 20 #endregion 21 21 22 #define EXPLICIT_SHAPE 22 //#define EXPORT_GRAPH 23 //#define LOG_CONSOLE 24 //#define LOG_FILE 23 25 24 26 using System; 25 27 using System.Collections; 26 28 using System.Collections.Generic; 29 #if LOG_CONSOLE 27 30 using System.Diagnostics; 31 #endif 32 #if LOG_FILE 33 using System.Globalization; 34 using System.IO; 35 #endif 28 36 using System.Linq; 29 37 using System.Threading; … … 46 54 private const string LearningRateName = "LearningRate"; 47 55 48 #region Parameter Properties 56 private static readonly TF_DataType DataType = tf.float32; 57 58 #region Parameter Properties 49 59 public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter { 50 60 get { return (IFixedValueParameter<IntValue>)Parameters[MaximumIterationsName]; } … … 53 63 get { return (IFixedValueParameter<DoubleValue>)Parameters[LearningRateName]; } 54 64 } 55 56 57 65 #endregion 66 67 #region Properties 58 68 public int ConstantOptimizationIterations { 59 69 get { return ConstantOptimizationIterationsParameter.Value.Value; } … … 62 72 get { return LearningRateParameter.Value.Value; } 63 73 } 64 74 #endregion 65 75 66 76 public TensorFlowConstantOptimizationEvaluator() 67 77 : base() { 68 78 Parameters.Add(new FixedValueParameter<IntValue>(MaximumIterationsName, "Determines how many iterations should be calculated while optimizing the constant of a symbolic expression tree(0 indicates other or default stopping criterion).", new IntValue(10))); 69 Parameters.Add(new FixedValueParameter<DoubleValue>(LearningRateName, "", new DoubleValue(0.0 1)));79 Parameters.Add(new FixedValueParameter<DoubleValue>(LearningRateName, "", new DoubleValue(0.001))); 70 80 } 71 81 … … 87 97 ApplyLinearScalingParameter.ActualValue.Value, UpdateVariableWeights, 88 98 ConstantOptimizationIterations, LearningRate, 89 cancellationToken, counter); 90 } 91 92 public static ISymbolicExpressionTree OptimizeTree( 93 ISymbolicExpressionTree tree, 99 cancellationToken); 100 } 101 102 public static ISymbolicExpressionTree OptimizeTree(ISymbolicExpressionTree tree, 94 103 IRegressionProblemData problemData, IEnumerable<int> rows, 95 104 bool applyLinearScaling, bool updateVariableWeights, int maxIterations, double learningRate, 96 CancellationToken cancellationToken = default(CancellationToken), EvaluationsCounter counter= null) {105 CancellationToken cancellationToken = default(CancellationToken), IProgress<double> progress = null) { 97 106 98 107 int numRows = rows.Count(); … … 114 123 return (ISymbolicExpressionTree)tree.Clone(); 115 124 116 #if EXPLICIT_SHAPE 117 var target = tf.placeholder(tf.float64, new TensorShape(numRows, 1), name: problemData.TargetVariable); 118 #endif 119 // mse 120 var costs = tf.reduce_sum(tf.square(target - prediction)) / (2.0 * numRows); 121 var optimizer = tf.train.GradientDescentOptimizer((float)learningRate).minimize(costs); 125 var target = tf.placeholder(DataType, new TensorShape(numRows), name: problemData.TargetVariable); 126 // MSE 127 var cost = tf.reduce_mean(tf.square(prediction - target)); 128 129 var optimizer = tf.train.AdamOptimizer((float)learningRate); 130 //var optimizer = tf.train.GradientDescentOptimizer((float)learningRate); 131 var optimizationOperation = optimizer.minimize(cost); 132 133 #if EXPORT_GRAPH 134 //https://github.com/SciSharp/TensorFlow.NET/wiki/Debugging 135 tf.train.export_meta_graph(@"C:\temp\TFboard\graph.meta", as_text: false, 136 clear_devices: true, clear_extraneous_savers: false, strip_default_attrs: true); 137 #endif 122 138 123 139 // features as feed items … … 127 143 var variableName = kvp.Value; 128 144 if (problemData.Dataset.VariableHasType<double>(variableName)) { 129 var data = problemData.Dataset.GetDoubleValues(variableName, rows).ToArray(); 130 //if (vectorLength.HasValue) { 131 // var vectorData = new double[numRows][]; 132 // for (int i = 0; i < numRows; i++) 133 // vectorData[i] = Enumerable.Repeat(data[i], vectorLength.Value).ToArray(); 134 // variablesFeed.Add(variable, np.array(vectorData)); 135 //} else 145 var data = problemData.Dataset.GetDoubleValues(variableName, rows).Select(x => (float)x).ToArray(); 136 146 variablesFeed.Add(variable, np.array(data, copy: false).reshape(numRows, 1)); 137 //} else if (problemData.Dataset.VariableHasType<string>(variableName)) {138 // variablesFeed.Add(variable, problemData.Dataset.GetStringValues(variableName, rows));139 147 } else if (problemData.Dataset.VariableHasType<DoubleVector>(variableName)) { 140 var data = problemData.Dataset.GetDoubleVectorValues(variableName, rows).Select(x => x. ToArray()).ToArray();148 var data = problemData.Dataset.GetDoubleVectorValues(variableName, rows).Select(x => x.Select(y => (float)y).ToArray()).ToArray(); 141 149 variablesFeed.Add(variable, np.array(data)); 142 150 } else 143 151 throw new NotSupportedException($"Type of the variable is not supported: {variableName}"); 144 152 } 145 var targetData = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows).ToArray(); 146 variablesFeed.Add(target, np.array(targetData, copy: false).reshape(numRows, 1)); 153 var targetData = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows).Select(x => (float)x).ToArray(); 154 variablesFeed.Add(target, np.array(targetData, copy: false)); 155 147 156 148 157 List<NDArray> constants; 149 158 using (var session = tf.Session()) { 159 160 #if LOG_FILE 161 var directoryName = $"C:\\temp\\TFboard\\logdir\\manual_{DateTime.Now.ToString("yyyyMMddHHmmss")}_{maxIterations}_{learningRate.ToString(CultureInfo.InvariantCulture)}"; 162 Directory.CreateDirectory(directoryName); 163 var costsWriter = new StreamWriter(File.Create(Path.Combine(directoryName, "Costs.csv"))); 164 var weightsWriter = new StreamWriter(File.Create(Path.Combine(directoryName, "Weights.csv"))); 165 var gradientsWriter = new StreamWriter(File.Create(Path.Combine(directoryName, "Gradients.csv"))); 166 #endif 167 168 #if LOG_CONSOLE || LOG_FILE 169 var gradients = optimizer.compute_gradients(cost); 170 #endif 171 150 172 session.run(tf.global_variables_initializer()); 151 173 152 // https://github.com/SciSharp/TensorFlow.NET/wiki/Debugging 153 tf.train.export_meta_graph(@"C:\temp\TFboard\graph.meta", as_text: false); 174 progress?.Report(session.run(cost, variablesFeed)[0].GetValue<float>(0)); 175 176 177 #if LOG_CONSOLE 178 Trace.WriteLine("Costs:"); 179 Trace.WriteLine($"MSE: {session.run(cost, variablesFeed)[0].ToString(true)}"); 154 180 155 181 Trace.WriteLine("Weights:"); 156 foreach (var v in variables) 182 foreach (var v in variables) { 157 183 Trace.WriteLine($"{v.name}: {session.run(v).ToString(true)}"); 184 } 185 186 Trace.WriteLine("Gradients:"); 187 foreach (var t in gradients) { 188 Trace.WriteLine($"{t.Item2.name}: {session.run(t.Item1, variablesFeed)[0].ToString(true)}"); 189 } 190 #endif 191 192 #if LOG_FILE 193 costsWriter.WriteLine("MSE"); 194 costsWriter.WriteLine(session.run(cost, variablesFeed)[0].GetValue<float>(0).ToString(CultureInfo.InvariantCulture)); 195 196 weightsWriter.WriteLine(string.Join(";", variables.Select(v => v.name))); 197 weightsWriter.WriteLine(string.Join(";", variables.Select(v => session.run(v).GetValue<float>(0, 0).ToString(CultureInfo.InvariantCulture)))); 198 199 gradientsWriter.WriteLine(string.Join(";", gradients.Select(t => t.Item2.name))); 200 gradientsWriter.WriteLine(string.Join(";", gradients.Select(t => session.run(t.Item1, variablesFeed)[0].GetValue<float>(0, 0).ToString(CultureInfo.InvariantCulture)))); 201 #endif 158 202 159 203 for (int i = 0; i < maxIterations; i++) { 160 161 //optimizer.minimize(costs); 162 session.run(optimizer, variablesFeed); 204 if (cancellationToken.IsCancellationRequested) 205 break; 206 207 session.run(optimizationOperation, variablesFeed); 208 209 progress?.Report(session.run(cost, variablesFeed)[0].GetValue<float>(0)); 210 211 #if LOG_CONSOLE 212 Trace.WriteLine("Costs:"); 213 Trace.WriteLine($"MSE: {session.run(cost, variablesFeed)[0].ToString(true)}"); 163 214 164 215 Trace.WriteLine("Weights:"); 165 foreach (var v in variables) 216 foreach (var v in variables) { 166 217 Trace.WriteLine($"{v.name}: {session.run(v).ToString(true)}"); 167 } 168 218 } 219 220 Trace.WriteLine("Gradients:"); 221 foreach (var t in gradients) { 222 Trace.WriteLine($"{t.Item2.name}: {session.run(t.Item1, variablesFeed)[0].ToString(true)}"); 223 } 224 #endif 225 226 #if LOG_FILE 227 costsWriter.WriteLine(session.run(cost, variablesFeed)[0].GetValue<float>(0).ToString(CultureInfo.InvariantCulture)); 228 weightsWriter.WriteLine(string.Join(";", variables.Select(v => session.run(v).GetValue<float>(0, 0).ToString(CultureInfo.InvariantCulture)))); 229 gradientsWriter.WriteLine(string.Join(";", gradients.Select(t => session.run(t.Item1, variablesFeed)[0].GetValue<float>(0, 0).ToString(CultureInfo.InvariantCulture)))); 230 #endif 231 } 232 233 #if LOG_FILE 234 costsWriter.Close(); 235 weightsWriter.Close(); 236 gradientsWriter.Close(); 237 #endif 169 238 constants = variables.Select(v => session.run(v)).ToList(); 170 239 } … … 182 251 foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) { 183 252 if (node is ConstantTreeNode constantTreeNode) 184 constantTreeNode.Value = constants[i++].Get Double(0, 0);253 constantTreeNode.Value = constants[i++].GetValue<float>(0, 0); 185 254 else if (node is VariableTreeNodeBase variableTreeNodeBase && updateVariableWeights) 186 variableTreeNodeBase.Weight = constants[i++].Get Double(0, 0);255 variableTreeNodeBase.Weight = constants[i++].GetValue<float>(0, 0); 187 256 else if (node is FactorVariableTreeNode factorVarTreeNode && updateVariableWeights) { 188 257 for (int j = 0; j < factorVarTreeNode.Weights.Length; j++) 189 factorVarTreeNode.Weights[j] = constants[i++].Get Double(0, 0);258 factorVarTreeNode.Weights[j] = constants[i++].GetValue<float>(0, 0); 190 259 } 191 260 } -
branches/3040_VectorBasedGP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Converters/TreeToTensorConverter.cs
r17493 r17502 29 29 using Tensorflow; 30 30 using static Tensorflow.Binding; 31 using DoubleVector = MathNet.Numerics.LinearAlgebra.Vector<double>;32 31 33 32 namespace HeuristicLab.Problems.DataAnalysis.Symbolic { 34 33 public class TreeToTensorConverter { 35 34 36 #region helper class 37 public class DataForVariable { 38 public readonly string variableName; 39 public readonly string variableValue; // for factor vars 40 41 public DataForVariable(string varName, string varValue) { 42 this.variableName = varName; 43 this.variableValue = varValue; 44 } 45 46 public override bool Equals(object obj) { 47 var other = obj as DataForVariable; 48 if (other == null) return false; 49 return other.variableName.Equals(this.variableName) && 50 other.variableValue.Equals(this.variableValue); 51 } 52 53 public override int GetHashCode() { 54 return variableName.GetHashCode() ^ variableValue.GetHashCode(); 55 } 56 } 57 #endregion 35 private static readonly TF_DataType DataType = tf.float32; 58 36 59 37 public static bool TryConvert(ISymbolicExpressionTree tree, int numRows, Dictionary<string, int> variableLengths, 60 38 bool makeVariableWeightsVariable, bool addLinearScalingTerms, 61 out Tensor graph, out Dictionary<Tensor, string> parameters, out List<Tensor> variables 62 /*, out double[] initialConstants*/) { 39 out Tensor graph, out Dictionary<Tensor, string> parameters, out List<Tensor> variables) { 63 40 64 41 try { … … 66 43 graph = converter.ConvertNode(tree.Root.GetSubtree(0)); 67 44 68 //var parametersEntries = converter.parameters.ToList(); // guarantee same order for keys and values 69 parameters = converter.parameters; // parametersEntries.Select(kvp => kvp.Value).ToList(); 45 parameters = converter.parameters; 70 46 variables = converter.variables; 71 //initialConstants = converter.initialConstants.ToArray();72 47 return true; 73 48 } catch (NotSupportedException) { … … 75 50 parameters = null; 76 51 variables = null; 77 //initialConstants = null;78 52 return false; 79 53 } … … 85 59 private readonly bool addLinearScalingTerms; 86 60 87 //private readonly List<double> initialConstants = new List<double>();88 61 private readonly Dictionary<Tensor, string> parameters = new Dictionary<Tensor, string>(); 89 62 private readonly List<Tensor> variables = new List<Tensor>(); … … 97 70 98 71 99 100 72 private Tensor ConvertNode(ISymbolicExpressionTreeNode node) { 101 73 if (node.Symbol is Constant) { 102 var value = ((ConstantTreeNode)node).Value; 103 //initialConstants.Add(value); 104 #if EXPLICIT_SHAPE 105 //var var = (RefVariable)tf.VariableV1(value, name: $"c_{variables.Count}", dtype: tf.float64, shape: new[] { 1, 1 }); 74 var value = (float)((ConstantTreeNode)node).Value; 106 75 var value_arr = np.array(value).reshape(1, 1); 107 var var = tf.Variable(value_arr, name: $"c_{variables.Count}", dtype: tf.float64); 108 #endif 109 //var var = tf.Variable(value, name: $"c_{variables.Count}", dtype: tf.float64/*, shape: new[] { 1, 1 }*/); 76 var var = tf.Variable(value_arr, name: $"c_{variables.Count}", dtype: DataType); 110 77 variables.Add(var); 111 78 return var; … … 118 85 //var varValue = factorVarNode != null ? factorVarNode.VariableValue : string.Empty; 119 86 //var par = FindOrCreateParameter(parameters, varNode.VariableName, varValue); 120 #if EXPLICIT_SHAPE 121 var par = tf.placeholder(tf.float64, new TensorShape(numRows, variableLengths[varNode.VariableName]), name: varNode.VariableName); 122 #endif 87 var par = tf.placeholder(DataType, new TensorShape(numRows, variableLengths[varNode.VariableName]), name: varNode.VariableName); 123 88 parameters.Add(par, varNode.VariableName); 124 89 125 90 if (makeVariableWeightsVariable) { 126 //initialConstants.Add(varNode.Weight); 127 #if EXPLICIT_SHAPE 128 //var w = (RefVariable)tf.VariableV1(varNode.Weight, name: $"w_{varNode.VariableName}_{variables.Count}", dtype: tf.float64, shape: new[] { 1, 1 }); 129 var w_arr = np.array(varNode.Weight).reshape(1, 1); 130 var w = tf.Variable(w_arr, name: $"w_{varNode.VariableName}", dtype: tf.float64); 131 #endif 132 //var w = tf.Variable(varNode.Weight, name: $"w_{varNode.VariableName}_{variables.Count}", dtype: tf.float64/*, shape: new[] { 1, 1 }*/); 91 var w_arr = np.array((float)varNode.Weight).reshape(1, 1); 92 var w = tf.Variable(w_arr, name: $"w_{varNode.VariableName}", dtype: DataType); 133 93 variables.Add(w); 134 94 return w * par; … … 143 103 // foreach (var variableValue in factorVarNode.Symbol.GetVariableValues(factorVarNode.VariableName)) { 144 104 // //var par = FindOrCreateParameter(parameters, factorVarNode.VariableName, variableValue); 145 // var par = tf.placeholder( tf.float64, new TensorShape(numRows, 1), name: factorVarNode.VariableName);105 // var par = tf.placeholder(DataType, new TensorShape(numRows, 1), name: factorVarNode.VariableName); 146 106 // parameters.Add(par, factorVarNode.VariableName); 147 107 148 108 // var value = factorVarNode.GetValue(variableValue); 149 109 // //initialConstants.Add(value); 150 // var wVar = (RefVariable)tf.VariableV1(value, name: $"f_{factorVarNode.VariableName}_{variables.Count}", dtype: tf.float64, shape: new[] { 1, 1 });110 // var wVar = (RefVariable)tf.VariableV1(value, name: $"f_{factorVarNode.VariableName}_{variables.Count}", dtype: DataType, shape: new[] { 1, 1 }); 151 111 // //var wVar = tf.Variable(value, name: $"f_{factorVarNode.VariableName}_{variables.Count}"/*, shape: new[] { 1, 1 }*/); 152 112 // variables.Add(wVar); … … 159 119 160 120 if (node.Symbol is Addition) { 161 var terms = new List<Tensor>(); 162 foreach (var subTree in node.Subtrees) { 163 terms.Add(ConvertNode(subTree)); 164 } 165 121 var terms = node.Subtrees.Select(ConvertNode).ToList(); 166 122 return terms.Aggregate((a, b) => a + b); 167 123 } 168 124 169 125 if (node.Symbol is Subtraction) { 170 var terms = new List<Tensor>(); 171 for (int i = 0; i < node.SubtreeCount; i++) { 172 var t = ConvertNode(node.GetSubtree(i)); 173 if (i > 0) t = -t; 174 terms.Add(t); 175 } 176 126 var terms = node.Subtrees.Select(ConvertNode).ToList(); 177 127 if (terms.Count == 1) return -terms[0]; 178 else return terms.Aggregate((a, b) => a +b);128 return terms.Aggregate((a, b) => a - b); 179 129 } 180 130 181 131 if (node.Symbol is Multiplication) { 182 var terms = new List<Tensor>(); 183 foreach (var subTree in node.Subtrees) { 184 terms.Add(ConvertNode(subTree)); 185 } 186 187 if (terms.Count == 1) return terms[0]; 188 else return terms.Aggregate((a, b) => a * b); 132 var terms = node.Subtrees.Select(ConvertNode).ToList(); 133 return terms.Aggregate((a, b) => a * b); 189 134 } 190 135 191 136 if (node.Symbol is Division) { 192 var terms = new List<Tensor>(); 193 foreach (var subTree in node.Subtrees) { 194 terms.Add(ConvertNode(subTree)); 195 } 196 197 if (terms.Count == 1) return 1.0 / terms[0]; 198 else return terms.Aggregate((a, b) => a * (1.0 / b)); 137 var terms = node.Subtrees.Select(ConvertNode).ToList(); 138 if (terms.Count == 1) return 1.0f / terms[0]; 139 return terms.Aggregate((a, b) => a / b); 199 140 } 200 141 … … 207 148 var x1 = ConvertNode(node.GetSubtree(0)); 208 149 var x2 = ConvertNode(node.GetSubtree(1)); 209 return x1 / tf.pow(1 + x2 * x2, 0.5);150 return x1 / tf.pow(1.0f + x2 * x2, 0.5f); 210 151 } 211 152 … … 233 174 if (node.Symbol is Cube) { 234 175 return math_ops.pow( 235 ConvertNode(node.GetSubtree(0)), 3.0 );176 ConvertNode(node.GetSubtree(0)), 3.0f); 236 177 } 237 178 238 179 if (node.Symbol is CubeRoot) { 239 180 return math_ops.pow( 240 ConvertNode(node.GetSubtree(0)), 1.0 / 3.0);181 ConvertNode(node.GetSubtree(0)), 1.0f / 3.0f); 241 182 // TODO 242 183 // f: x < 0 ? -Math.Pow(-x, 1.0 / 3) : Math.Pow(x, 1.0 / 3), … … 281 222 282 223 if (node.Symbol is StartSymbol) { 224 Tensor prediction; 283 225 if (addLinearScalingTerms) { 284 226 // scaling variables α, β are given at the beginning of the parameter vector 285 #if EXPLICIT_SHAPE 286 //var alpha = (RefVariable)tf.VariableV1(1.0, name: $"alpha_{1.0}", dtype: tf.float64, shape: new[] { 1, 1 }); 287 //var beta = (RefVariable)tf.VariableV1(0.0, name: $"beta_{0.0}", dtype: tf.float64, shape: new[] { 1, 1 }); 288 289 var alpha_arr = np.array(1.0).reshape(1, 1); 290 var alpha = tf.Variable(alpha_arr, name: "alpha", dtype: tf.float64); 291 var beta_arr = np.array(0.0).reshape(1, 1); 292 var beta = tf.Variable(beta_arr, name: "beta", dtype: tf.float64); 293 #endif 294 //var alpha = tf.Variable(1.0, name: $"alpha_{1.0}", dtype: tf.float64/*, shape: new[] { 1, 1 }*/); 295 //var beta = tf.Variable(0.0, name: $"beta_{0.0}", dtype: tf.float64/*, shape: new[] { 1, 1 }*/); 227 var alpha_arr = np.array(1.0f).reshape(1, 1); 228 var alpha = tf.Variable(alpha_arr, name: "alpha", dtype: DataType); 229 var beta_arr = np.array(0.0f).reshape(1, 1); 230 var beta = tf.Variable(beta_arr, name: "beta", dtype: DataType); 296 231 variables.Add(alpha); 297 232 variables.Add(beta); 298 233 var t = ConvertNode(node.GetSubtree(0)); 299 return t * alpha + beta; 300 } else return ConvertNode(node.GetSubtree(0)); 234 prediction = t * alpha + beta; 235 } else { 236 prediction = ConvertNode(node.GetSubtree(0)); 237 } 238 239 return tf.reduce_sum(prediction, axis: new[] { 1 }); 301 240 } 302 241
Note: See TracChangeset
for help on using the changeset viewer.