SG++-Doxygen-Documentation
learnerExample.py

This example can be found under datadriven/examples/learnerExample.py.

1 from pysgpp.extensions.datadriven.learner import LearnerBuilder
2 import numpy as np
3 import matplotlib.pyplot as plt
4 from pysgpp.extensions.datadriven.uq.plot.plot1d import plotSG1d
5 from pysgpp.extensions.datadriven.uq.plot.plot2d import plotSG2d
6 from pysgpp.extensions.datadriven.learner import Types
7 
8 numSamples = 20
9 numDims = 2
10 
11 def f(x):
12  """
13  normal parabola
14  """
15  return np.prod(4. * x * (1 - x), axis=1)
16 
17 def g(x):
18  """
19  normal line
20  """
21  return np.prod(0.0 * x + 5, axis=1)
22 
23 
24 print("generate uniformly distributed samples (%i, %i)" % (numSamples, numDims))
25 samples = np.random.rand(numSamples, numDims)
26 values = f(samples)
27 
28 builder = LearnerBuilder()
29 builder.buildRegressor()
30 builder.withTrainingDataFromNumPyArray(samples, values)
31 builder = builder.withGrid().withBorder(Types.BorderTypes.NONE) # Modified basis functions
32 builder.withLevel(2)
33 builder = builder.withSpecification().withAdaptThreshold(0.00003)
34 builder.withAdaptPoints(3)
35 builder.withLambda(1e-6)
36 
37 builder.withLaplaceOperator()
38 # Alternative:
39 #builder.withIdentityOperator()
40 
41 builder = builder.withStopPolicy().withAdaptiveIterationLimit(3)
42 builder = builder.withCGSolver()
43 builder.withAccuracy(1e-7)
44 builder.withImax(100)
45 
46 # Create the final learner object
47 learner = builder.andGetResult()
48 
49 gs = learner.grid.getStorage()
50 
51 print ("Dimensions: %i" % gs.getDimension())
52 print ("Grid points: %i" % gs.getSize())
53 
54 print("================== Starting learning ==================")
55 
56 learner.setVerbosity(False)
57 learner.learnData()
58 print(learner.alpha)
59 
60 print("=======================================================")
61 
62 if numDims == 1:
63  plt.scatter(samples[:, 0], values)
64  plotSG1d(learner.grid, learner.alpha, color="red")
65 else:
66  plotSG2d(learner.grid, learner.alpha)
67  plt.scatter(samples[:, 0], samples[:, 1])
68 plt.show()
69