我正在 TensorFlow 中进行基本的轨道力学模拟。当“行星”离“太阳”太近时(当 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
或无穷大,然后按照人们对数值积分的期望正常传播。