1import c3py # import the python interface to the c3 library 2import numpy as np 3import matplotlib.pyplot as plt 4 5def func(x): 6 return x[:, 0]**2 + x[:, 1]**2 + x[:, 0] * x[:, 1] + np.sin(np.sum(x, axis=1)) \ 7 + x[:,0] * x[:,-1] + x[:, -1]**2.0 * np.cos(x[:, 0]) 8 9 10LB = -1.0 # lower bounds of features 11UB = 1.0 # upper bounds of features 12DIM = 20 # number of features 13 14Ntrain = 100 15X = np.random.rand(Ntrain, 2) 16Y = func(X) 17 18Ntest = 1000 19Xtest = np.random.rand(Ntest, 2) 20Ytest = func(Xtest) 21 22 23def build_ft_regress(xdata, ydata, nparam=2, init_rank=5, adaptrank=1, verbose=0): 24 dim = xdata.shape[1] 25 ndata = xdata.shape[0] 26 27 ft = c3py.FunctionTrain(dim) 28 for ii in range(dim): 29 ft.set_dim_opts(ii, "legendre", LB, UB, nparam) 30 31 ranks = [init_rank]*(dim+1) 32 ranks[0] = 1 33 ranks[dim] = 1 34 ft.set_ranks(ranks) 35 ft.build_data_model(ndata, xdata, ydata, 36 alg="AIO", obj="LS", adaptrank=adaptrank, 37 kickrank=1, roundtol=1e-10, verbose=verbose) 38 return ft 39 40print("X shape ", X.shape) 41print("Y shape ", Y.shape) 42ft_regress = build_ft_regress(X, Y, nparam=5, init_rank=1, adaptrank=1, verbose=0) 43 44print("Xtest.shape ", Xtest.shape) 45print("Ytest.shape ", Ytest.shape) 46ft_evals = ft_regress.eval(Xtest) 47 48err = np.linalg.norm(ft_evals - Ytest) / np.linalg.norm(Ytest) 49 50print("Relmse = ", err) 51plt.figure() 52plt.plot(ft_evals, Ytest, 'o') 53plt.show() 54 55