Почему следующие два сценария всегда приводят к потере нуля при использовании tf-nightly 2.2.0.dev20200423
и tfp-nightly 0.11.0.dev20200423
?
import tensorflow as tf
import tensorflow_probability as tfp
tf.config.experimental_run_functions_eagerly(True)
def get_mnist_data(normalize=True, categorize=True):
img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
if tf.keras.backend.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
if normalize:
x_train /= 255
x_test /= 255
if categorize:
y_train = tf.keras.utils.to_categorical(y_train)
y_test = tf.keras.utils.to_categorical(y_test)
return x_train, y_train, x_test, y_test, input_shape
def get_model(input_shape, num_classes=10):
model = tf.keras.Sequential()
model.add(tfp.layers.Convolution2DFlipout(6, input_shape=input_shape,
kernel_size=3, padding="SAME",
activation=tf.nn.relu))
model.add(tf.keras.layers.Flatten())
model.add(tfp.layers.DenseFlipout(num_classes))
return model
def train():
x_train, y_train, x_test, y_test, input_shape = get_mnist_data()
batch_size = 64
model = get_model(input_shape)
model.summary()
model.compile(loss="categorical_crossentropy")
model.fit(x_train, y_train, batch_size=batch_size, epochs=1)
if __name__ == '__main__':
train()
и
import tensorflow as tf
import tensorflow_probability as tfp
tf.config.experimental_run_functions_eagerly(True)
def get_mnist_data(normalize=True, categorize=True):
img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
if tf.keras.backend.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
if normalize:
x_train /= 255
x_test /= 255
if categorize:
y_train = tf.keras.utils.to_categorical(y_train)
y_test = tf.keras.utils.to_categorical(y_test)
return x_train, y_train, x_test, y_test, input_shape
def get_model(input_shape, num_classes=10):
model_input = tf.keras.layers.Input(shape=input_shape)
x = tfp.layers.Convolution2DFlipout(6, kernel_size=3, padding="SAME", activation=tf.nn.relu)(model_input)
x = tf.keras.layers.Flatten()(x)
x = tfp.layers.DenseFlipout(num_classes)(x)
model_output = tfp.layers.DistributionLambda(lambda t:
tfp.distributions.Categorical(logits=t, validate_args=True))(x)
model = tf.keras.Model(model_input, model_output)
model.summary()
return model
def neg_log_likelihood(y_true, y_pred):
return -tf.reduce_mean(y_pred.log_prob(tf.cast(tf.argmax(y_true, axis=-1), tf.int32)))
def train():
x_train, y_train, x_test, y_test, input_shape = get_mnist_data()
batch_size = 64
model = get_model(input_shape)
model.summary()
model.compile(loss=neg_log_likelihood)
model.fit(x_train, y_train, batch_size=batch_size, epochs=1)
if __name__ == '__main__':
train()
Пожалуйста, не предлагайте мне использовать стабильные версии этих библиотек (т.е. в настоящее время TF 2.1 и TFP 0.9), потому что я уже пытаюсь используйте эту ночную версию, чтобы избежать других ошибок, которые я получаю с TF 2.1 и TFP 0.9, что мешало моей работе в течение нескольких месяцев!
Кроме того, не предлагайте мне удалить tf.config.experimental_run_functions_eagerly(True)
, потому что я пытаюсь используйте его, чтобы избежать другой ошибки, которая возникает как в текущих нестабильных версиях, так и в последних стабильных версиях TF 2.1 и TFP 0.9. Ошибка описана здесь TypeError: Оператору вне кода построения функции передается тензор графика , и это самая досадная ошибка за всю историю!
Если вы любите TensorFlow (в этом случае, Вы, вероятно, сошли с ума), посмотрите на NotImplementedError: Невозможно преобразовать символ c Тензор (truediv_2: 0) в numpy массив .