【问题标题】:categorical_crossentropy loss , no attribute 'get_shape'分类交叉熵损失,没有属性“get_shape”
【发布时间】:2018-03-23 01:27:14
【问题描述】:

我想获得最后一层的模型(用于训练)的 categorical_crossentropy 损失:model.add(Dense(num_classes, activation='softmax'))。所以我获取该层的输出并使用以下代码使用以下代码获取损失输出:

from sklearn.metrics import confusion_matrix
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.callbacks import TensorBoard
import numpy as np
from sklearn.model_selection import train_test_split
import tensorflow as tf
batch_size = 128
num_classes = 3
epochs = 1

# input image dimensions
img_rows, img_cols = 28, 28


(x_train, y_train), (x_test, y_test) = mnist.load_data()
x1_train=x_train[y_train==0]; y1_train=y_train[y_train==0]
x1_test=x_test[y_test==0];y1_test=y_test[y_test==0]
x2_train=x_train[y_train==1];y2_train=y_train[y_train==1]
x2_test=x_test[y_test==1];y2_test=y_test[y_test==1]
x3_train=x_train[y_train==2];y3_train=y_train[y_train==2]
x3_test=x_test[y_test==2];y3_test=y_test[y_test==2]

X=np.concatenate((x1_train,x2_train,x3_train,x1_test,x2_test,x3_test),axis=0)
Y=np.concatenate((y1_train,y2_train,y3_train,y1_test,y2_test,y3_test),axis=0)

# the data, shuffled and split between train and test sets
x_train, x_test, y_train, y_test = train_test_split(X,Y)

if K.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')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(1, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())

model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
model.summary()
get_dense_layer_output = K.function([model.layers[0].input],
                                  [model.layers[3].output])
layer_output = get_dense_layer_output([x_train])[0]
g=K.categorical_crossentropy(layer_output, y_train)

并出现错误:AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'。如何解决。

【问题讨论】:

  • 错误发生在代码中的哪个位置?
  • g=K.categorical_crossentropy(layer_output, y_train) 在这一行
  • 以后,最好省略所有与问题无关的代码部分(这里是x1, x2, x3员工,Tensorboardconfusion_matrixX, Y等) - 它们只会使问题看起来不必要地冗长,并且可能会阻止潜在的受访者......
  • 当然。我会处理好这个

标签: numpy tensorflow keras neural-network conv-neural-network


【解决方案1】:

您的网络已经在使用 categorical_crossentropy 进行训练。要获取数据集的损失值,您可以使用 model.evaluate

values = model.evaluate(X_train, y_train)

那么values[0]是损失值,values[1]是准确度指标。

【讨论】:

  • 我重新构建了我的问题:在下面的代码中,我想要 c 的值,这里 a 是真实的 labes,b 是预测标签:from keras import backend as K import numpy as np a=np.array([1,2,3]) b=np.array([1,1,1]) c=K.categorical_crossentropy(a, b)。但是出现错误AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'
【解决方案2】:

出于所有实际目的,下面史努比博士的回答是正确的。

出于教育目的(或您可能有的任何其他目的),以下是您的脚本和错误发生的情况:

在所有 Keras 损失函数中,例如 K.categorical_crossentropy(),参数是张量(有 get_shape 参数),而不是 numpy 数组(没有) - 检查 docs。所以,你应该将你的 numpy 数组转换为张量,但在此之前,你必须将它们转换为相同的类型(它们不是),否则你会得到一个错误:

y_train.dtype
# dtype('float64')

layer_output.dtype
# dtype('float32')

y_train = y_train.astype('float32')
y_true = K.constant(y_train)
y_pred = K.constant(layer_output)
g = K.categorical_crossentropy(target=y_true, output=y_pred)
g
# <tf.Tensor 'Neg_1:0' shape=(16327,) dtype=float32>

如您所见,结果g是一个(Tensorflow)张量,需要对其进行评估:

ce = K.eval(g)  # 'ce' for cross-entropy
type(ce)
# numpy.ndarray
ce.shape
# (16327,)

结果是一个 numpy 数组,其中包含 16,327 个训练样本中的每一个的损失。

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2020-03-14
    • 2017-11-11
    • 2018-09-03
    • 2016-08-01
    • 2019-06-19
    • 2017-06-26
    • 2020-03-03
    • 2017-03-14
    相关资源
    最近更新 更多