goutham-fin / BCF-Workshop

Materials for the mini-course on deep learning and macro-finance.
19 stars 10 forks source link

Numerical issues in BCF_Model2 #1

Open BabaYara opened 1 year ago

BabaYara commented 1 year ago

I have been trying to run BCF_Model2..py on colab and I keep running into a matrix inversion problem. The error happens when the code tries to run this line:

EN = np.array([sig_qk_p,sig_qf_p,q_p]) - np.linalg.solve(QN,ER)

on the 11th Iteration.

This is the entire print out: Solving for value functions It: 0, Loss: 1.660e-03, Time: 4.60 It: 1000, Loss: 2.391e-07, Time: 24.31 WARNING:tensorflow:Compiled the loaded model, but the compiled metrics have yet to be built.model.compile_metricswill be empty until you train or evaluate the model. WARNING:tensorflow:Compiled the loaded model, but the compiled metrics have yet to be built.model.compile_metrics` will be empty until you train or evaluate the model. Iteration number and mean error: 11 , 0.024916804745222187 /n

LinAlgError Traceback (most recent call last) in <cell line: 1>() 13 ext = model_nnpde(params) 14 ext.maxIterations = args.maxIterations ---> 15 ext.solve(pde='True') 16 ext.clear_saved_models() 17

4 frames in solve(self, pde) 181 else: 182 self.psi[zi,fi]=1 --> 183 result = self.equations_region2(self.q[zi-1,fi],self.ssq[zi-1,fi],self.ssf[zi-1,fi],self.chi[zi-1,fi],zi,fi) 184 self.ssq[zi,fi], self.ssf[zi,fi], self.q[zi,fi],self.chi[zi,fi] = result[0], result[1], result[2],result[3] 185 del result

in equations_region2(self, q_p, sig_qk_p, sig_qf_p, Chi_p_old, zi, fi) 116 QN[2,:] = np.array([0,1-1/self.dz[zi-1](Chi_p_old-self.z_mat[zi,fi]) + self.q[zi-1,fi]/(q_pself.dz[zi-1])(1-self.z_mat[zi,fi]), -sig_qf_p/self.dz[zi-1]self.q[zi-1,fi]/(q_p*2)(Chi_p_old-self.z_mat[zi,fi]) - self.sig_f[0... 117 --> 118 EN = np.array([sig_qk_p,sig_qf_p,q_p]) - np.linalg.solve(QN,ER) 119 sig_qk_p,sig_qf_p,q_p = EN[0], EN[1], EN[2] 120 omega_1 = sig_qk_p2 + sig_qf_p2 + 2self.params['corr']sig_qk_p*sig_qf_p

/usr/local/lib/python3.10/dist-packages/numpy/core/overrides.py in solve(*args, **kwargs)

/usr/local/lib/python3.10/dist-packages/numpy/linalg/linalg.py in solve(a, b) 391 signature = 'DD->D' if isComplexType(t) else 'dd->d' 392 extobj = get_linalg_error_extobj(_raise_linalgerror_singular) --> 393 r = gufunc(a, b, signature=signature, extobj=extobj) 394 395 return wrap(r.astype(result_t, copy=False))

`

goutham-fin commented 1 year ago

Thanks for pointing it out.

I changed line 569 from self.Je=newJe to self.Je = np.maximum(0.001,newJe) and the issue disappears. Let me know if that works for you.

BabaYara commented 1 year ago

That fixes the problem but the then the model gets stuck in that iteration for some reason. But thanks for the attention!