I'm trying to learn to use DeepXDE by solving the heat equation. Luckily there is an example that I've been able to compare with but I get an error regarding shapes mismatching I haven't been able to resolve. I'm using Python 3.10.2.
I still struggle to understand the shape some commands are expecting. I've tried to guide myself with the example and having in mind the problem of solving the heat equation having a dataset of daily ground temperatures at certain depths. I use this data set to constraint as IC/BCs.
train_T initial's shape is (2557 time steps, 278 cell depths) before transformations.I added a random generated array that I normalize for the sake of the network training.
I'm also not sure about how I specify the training points inside the domain, boundaries, etc.
I'd like to know where the next shape mismatch error is coming from.
P.S. The last code lines will plot, save and generate some files you might not want.
This is my code:
import numpy as np
import matplotlib.pyplot as plt
import netCDF4 as nc
import deepxde as dde
import tensorflow as tf
train_T = np.random.rand(2557, 278)
train_mean=np.mean(train_T, axis=0, keepdims=True )
train_std =np.std(train_T, axis=0, keepdims=True)
train_T = (train_T-train_mean)/train_std
train_days, cells=np.shape(train_T)
time_steps=np.arange(train_days)
ic_T = train_T[0,:].reshape(-1,1) # First day profile as IC
ubc_T= train_T[:,0] # First/last cells as upper/lower BC
lbc_T=train_T[:,-1]
ub_depth,lb_depth = (depth[0],depth[-1]) # Depths of first and last cell
points=[]
values=[]
for day in range(train_days):
points.extend([[day, ub_depth], [day, lb_depth]])
values.extend([ubc_T[day], lbc_T[day]])
values = np.asarray(values).reshape(-1)
a=0.4
def pde(x,y):
dy_t=dde.grad.jacobian(y,x,i=0,j=0)
dy_zz = dde.grad.hessian(y, x, i=1, j=1)
return dy_t - a* dy_zz
# Computational geometry:
geom = dde.geometry.Interval(0, depth[-1])
timedomain = dde.geometry.TimeDomain(0, train_days)
geomtime = dde.geometry.GeometryXTime(geom, timedomain)
bc=dde.icbc.PointSetBC(points, values, shuffle=False)
ic = dde.icbc.IC(geomtime, lambda x: ic_T,lambda _ , on_initial: on_initial)
data = dde.data.TimePDE(
geomtime,
pde,
[bc, ic],
num_domain=cells,
num_boundary=2,
num_initial=cells,
num_test=cells,
)
net = dde.nn.FNN([cells] + [20] * 2 + [cells-2], "tanh", "Glorot normal")
model = dde.Model(data, net)
model.compile("adam", lr=1e-3)
model.train(iterations=20000)
model.compile("L-BFGS")
losshistory, train_state = model.train()
# Plot/print the results
dde.saveplot(losshistory, train_state, issave=True, isplot=True)
X, y_true = gen_testdata()
y_pred = model.predict(X)
f = model.predict(X, operator=pde)
print("Mean residual:", np.mean(np.absolute(f)))
print("L2 relative error:", dde.metrics.l2_relative_error(y_true, y_pred))
np.savetxt("test.dat", np.hstack((X, y_true, y_pred)))
This is the error I get:
Warning: 278 points required, but 286 points sampled.
Compiling model...
Building feed-forward neural network...
'build' took 0.034132 s
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_1789121/2863646270.py in <module>
61
62 model.compile("adam", lr=1e-3)
---> 63 model.train(iterations=20000)
64 model.compile("L-BFGS")
65 losshistory, train_state = model.train()
~/jupyter_py3.10.2/lib/python3.10/site-packages/deepxde/utils/internal.py in wrapper(*args, **kwargs)
20 def wrapper(*args, **kwargs):
21 ts = timeit.default_timer()
---> 22 result = f(*args, **kwargs)
23 te = timeit.default_timer()
24 if config.rank == 0:
~/jupyter_py3.10.2/lib/python3.10/site-packages/deepxde/model.py in train(self, iterations, batch_size, display_every, disregard_previous_best, callbacks, model_restore_path, model_save_path, epochs)
634 self.train_state.set_data_train(*self.data.train_next_batch(self.batch_size))
635 self.train_state.set_data_test(*self.data.test())
--> 636 self._test()
637 self.callbacks.on_train_begin()
638 if optimizers.is_external_optimizer(self.opt_name):
~/jupyter_py3.10.2/lib/python3.10/site-packages/deepxde/model.py in _test(self)
823 self.train_state.y_pred_train,
824 self.train_state.loss_train,
--> 825 ) = self._outputs_losses(
826 True,
827 self.train_state.X_train,
~/jupyter_py3.10.2/lib/python3.10/site-packages/deepxde/model.py in _outputs_losses(self, training, inputs, targets, auxiliary_vars)
539 if backend_name == "tensorflow.compat.v1":
540 feed_dict = self.net.feed_dict(training, inputs, targets, auxiliary_vars)
--> 541 return self.sess.run(outputs_losses, feed_dict=feed_dict)
542 if backend_name == "tensorflow":
543 outs = outputs_losses(inputs, targets, auxiliary_vars)
~/jupyter_py3.10.2/lib/python3.10/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
970
971 try:
--> 972 result = self._run(None, fetches, feed_dict, options_ptr,
973 run_metadata_ptr)
974 if run_metadata:
~/jupyter_py3.10.2/lib/python3.10/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1187 if (not is_tensor_handle_feed and
1188 not subfeed_t.get_shape().is_compatible_with(np_val.shape)):
-> 1189 raise ValueError(
1190 f'Cannot feed value of shape {str(np_val.shape)} for Tensor '
1191 f'{subfeed_t.name}, which has shape '
ValueError: Cannot feed value of shape (5950, 2) for Tensor Placeholder_86:0, which has shape (None, 278)
Please let me know if you needed more information.