我的目标是从Keras神经网络模型检索logit。我在这里阅读:Keras - how to get unnormalized logits instead of probabilities
我需要将最后一个激活层更改为“线性”。这是我的代码
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
#Preprocessing
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images = train_images / 255.0
test_images = test_images / 255.0
#Preprocessing
#Generate the Model
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.linear)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
此行发生问题。有没有更好的方法来获取日志?如果没有,如何使激活线性化?
keras.layers.Dense(10, activation=tf.nn.linear)
答案 0 :(得分:0)
您可以使用Activation
层
#Generate the Model
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=None),
keras.layers.Activation('relu')
])
答案 1 :(得分:0)
使用线性激活对获取logit是正确的。在开发keras模型时,请使用来自keras的激活。
替换
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.linear)
使用
keras.layers.Dense(128, activation=keras.activations.relu),
keras.layers.Dense(10, activation=keras.activations.linear)
或者,不指定激活也默认为线性。
keras.layers.Dense(10)