我在TensorFlow中进行基本的轨道力学模拟。当'planet'太靠近'sun'时(当x,y接近(0,0)时),TensorFlow在分割期间会获得异常(这可能有意义)。不知何故,它在异常期间返回异常,导致它完全失败。
我已经尝试使用tf.where
有条件地用NaN
替换这些除以零,然而,它然后遇到有效的相同错误。我也尝试使用tf.div_no_nan来获得零而不是NaN
,但是得到完全相同的错误。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def gravity(state, t):
print(len(tf.unstack(state)))
x, y, vx, vy = tf.unstack(state)
# Error is related to next two lines
fx = -x/tf.pow(tf.reduce_sum(tf.square([x,y]),axis=0),3/2)
fy = -y/tf.pow(tf.reduce_sum(tf.square([x,y]),axis=0),3/2)
dvx = fx
dvy = fy
return tf.stack([vx, vy, dvx, dvy])
# Num simulations
size = 100
# Initialize at same position with varying y-velocity
init_state = tf.stack([tf.constant(-1.0,shape=(size,)),tf.zeros((size)),tf.zeros((size)),tf.range(0,10,.1)])
t = np.linspace(0, 10, num=5000)
tensor_state, tensor_info = tf.contrib.integrate.odeint(
gravity, init_state, t, full_output=True)
init = tf.global_variables_initializer()
with tf.Session() as sess:
state, info = sess.run([tensor_state, tensor_info])
state = tf.transpose(state, perm=[1,2,0]).eval()
x, y, vx, vy = state
for i in range(10):
plt.figure()
plt.plot(x[i], y[i])
plt.scatter([0],[0])
我真的得到了
...
InvalidArgumentError: assertion failed: [underflow in dt] [9.0294095248318226e-17]
...
During handling of the above exception, another exception occurred:
...
InvalidArgumentError: assertion failed: [underflow in dt] [9.0294095248318226e-17]
...
我希望这个鸿沟能够产生NaN
or Infinity,然后通常会像人们期望的那样传播数值积分。
你可以试试这个
with tf.Session() as sess:
sess.run(init)
try:
state, info = sess.run([tensor_state, tensor_info])
except tf.errors.InvalidArgumentError:
state = #Whatever values/shape you need
我不知道你的情况是否合适,但也许你可以添加一些小常数来避免除以零。