如何解决我可以在keras自定义损失函数中包含sdeint随机积分吗?
我正在尝试让神经网络拟合随机微分方程(SDE)的两个参数,该方程的终端分布具有已知矩(均值,标准差)。特别是,我希望神经网络预测SDE上的参数,然后让自定义损失函数将SDE(对于给定数量的路径)整合到预测参数下,并计算与已知力矩的偏差。> python sde集成库
sdeint
似乎使用了numpy,该函数在keras损失函数中不起作用。我收到错误:
AttributeError:用户代码中:
/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:806 train_function *
return step_function(self,iterator)
<ipython-input-1-2252ad1bedac>:35 loss_fn *
Y_T = [sd.itoint(f,g,Y0,tspan)[-1][0] for i in range(30)]
/usr/local/lib/python3.7/site-packages/sdeint/integrate.py:123 itoint *
(d,m,f,G,y0,tspan,__,__) = _check_args(f,None,None)
/usr/local/lib/python3.7/site-packages/sdeint/integrate.py:86 _check_args *
if Gtest.ndim != 2 or Gtest.shape[0] != d:
AttributeError: 'Tensor' object has no attribute 'ndim'
有没有办法在损失函数中包括随机积分?我在下面提供了一个可重现的最小示例,以说明该错误。
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
import sdeint as sd
# Create Random Sample Data
def create_data(n):
x1 = np.array([i/100+np.random.uniform(-1,3) for i in range(n)]).reshape(n,1)
x2 = np.array([i/100+np.random.uniform(-3,5)+2 for i in range(n)]).reshape(n,1)
x3 = np.array([i/100+np.random.uniform(-6,5)-3 for i in range(n)]).reshape(n,1)
y1= [x1[i]-x2[i]+x3[i]+np.random.uniform(-2,2) for i in range(n)]
y2= [x1[i]+x2[i]-x3[i]+5+np.random.uniform(-1,3) for i in range(n)]
X = np.hstack((x1,x2,x3))
Y = np.hstack((y1,y2))
return X,Y
X,Y = create_data(n=450)
in_dim = X.shape[1]
out_dim = Y.shape[1]
xtrain,xtest,ytrain,ytest=train_test_split(X,Y,test_size=0.15)
# Define Custom Loss Function
def loss_fn(y_pred,obj):
# Extract SDE Parameters
Z = y_pred[0]
Y0 = y_pred[1]
def f(y,t):
return -(y+Z+1)
def g(y,t):
return Z
# Integrate
tspan = np.linspace(0.0,0.2,201)
Y_T = [sd.itoint(f,tspan)[-1][0] for i in range(30)]
Loss = (tf.mean(Y_T)-obj[0])**2+(tf.std(Y_T)-obj[1])**2
return Loss
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(100,input_dim=in_dim,activation="relu"))
model.add(tf.keras.layers.Dense(32,activation="relu"))
model.add(tf.keras.layers.Dense(out_dim))
model.compile(loss=loss_fn,optimizer="adam")
model.fit(xtrain,epochs=100,batch_size=12,verbose=0)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。