我在使用Keras和Python对3D CNN进行分类时遇到问题。我有一个包含JSON格式的模型的文件夹。我把这些模型读成Numpy数组。模型是25 * 25 * 25并且表示体素化模型的占用网格(每个位置表示位置(i,j,k)中的体素是否具有点或否),因此我只有1个输入通道,喜欢2D图像中的灰度图像。我的代码如下:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution3D, MaxPooling3D
from keras.optimizers import SGD
from keras.utils import np_utils
from keras import backend as K
# Number of Classes and Epochs of Training
nb_classes = 3 # cube, cone or sphere
nb_epoch = 100
batch_size = 2
# Input Image Dimensions
img_rows, img_cols, img_depth = 25, 25, 25
# Number of Convolutional Filters to use
nb_filters = 32
# Convolution Kernel Size
kernel_size = [5,5,5]
X_train, Y_train = [], []
# Read from File
import os
import json
i=0
for filename in os.listdir(os.path.join(os.getcwd(), 'models')):
with open(os.path.join(os.getcwd(), 'models', filename)) as f:
file = f.readlines()
json_file = '\n'.join(file)
content = json.loads(json_file)
occupancy = content['model']['occupancy']
form = []
for value in occupancy:
form.append(int(value))
final_model = [ [ [ 0 for i in range(img_rows) ]
for j in range(img_cols) ]
for k in range(img_depth) ]
a = 0
for i in range(img_rows):
for j in range(img_cols):
for k in range(img_depth):
final_model[i][j][k] = form[a]
a = a + 1
X_train.append(final_model)
Y_train.append(content['model']['label'])
X_train = np.array(X_train)
Y_train = np.array(Y_train)
# (1 channel, 25 rows, 25 cols, 25 of depth)
input_shape = (1, img_rows, img_cols, img_depth)
# Init
model = Sequential()
# 3D Convolution layer
model.add(Convolution3D(nb_filters, kernel_size[0], kernel_size[1], kernel_size[2],
input_shape=input_shape,
activation='relu'))
# Fully Connected layer
model.add(Flatten())
model.add(Dense(128,
init='normal',
activation='relu'))
model.add(Dropout(0.5))
# Softmax Layer
model.add(Dense(nb_classes,
init='normal'))
model.add(Activation('softmax'))
# Compile
model.compile(loss='categorical_crossentropy',
optimizer=SGD())
# Fit network
model.fit(X_train, Y_train, nb_epoch=nb_epoch,
verbose=1)
在此之后,我收到以下错误
使用TensorFlow后端。 Traceback(最近一次调用最后一次):文件 “/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py” 第670行,在_call_cpp_shape_fn_impl中 status)文件“/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py”, 第89行,在退出 next(self.gen)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py”, 第469行,在raise_exception_on_not_ok_status中 pywrap_tensorflow.TF_GetCode(status))tensorflow.python.framework.errors_impl.InvalidArgumentError:否定 通过从'Conv3D'中减去5而导致的尺寸大小(op: 'Conv3D')输入形状:[?,1,25,25,25],[5,5,5,25,32]。
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):文件“CNN_3D.py”,第76行,in activation ='relu'))文件“/usr/local/lib/python3.6/site-packages/keras/models.py”,第299行,in 加 layer.create_input_layer(batch_input_shape,input_dtype)文件“/usr/local/lib/python3.6/site-packages/keras/engine/topology.py”, 第401行,在create_input_layer中 self(x)文件“/usr/local/lib/python3.6/site-packages/keras/engine/topology.py”, 第572行,致电 self.add_inbound_node(inbound_layers,node_indices,tensor_indices)文件 “/usr/local/lib/python3.6/site-packages/keras/engine/topology.py” 第635行,在add_inbound_node中 Node.create_node(self,inbound_layers,node_indices,tensor_indices)文件 “/usr/local/lib/python3.6/site-packages/keras/engine/topology.py” 第166行,在create_node中 output_tensors = to_list(outbound_layer.call(input_tensors [0],mask = input_masks [0]))文件 “/usr/local/lib/python3.6/site-packages/keras/layers/convolutional.py” 第1234行,正在通话中 filter_shape = self.W_shape)文件“/usr/local/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py”, 第2831行,在conv3d x = tf.nn.conv3d(x,kernel,strides,padding)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/ops/gen_nn_ops.py”, 第522行,在conv3d中 strides = strides,padding = padding,name = name)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py”, 第763行,在apply_op中 op_def = op_def)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, 第2397行,在create_op中 set_shapes_for_outputs(ret)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, 第1757行,在set_shapes_for_outputs中 shapes = shape_func(op)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, 第1707行,在call_with_requiring中 return call_cpp_shape_fn(op,require_shape_fn = True)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py”, 第610行,在call_cpp_shape_fn中 debug_python_shape_fn,require_shape_fn)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py”, 第675行,在_call_cpp_shape_fn_impl中 提高ValueError(err.message)ValueError:通过输入从“Conv3D”(op:'Conv3D')中减去5的5引起的负维度大小 形状:[?,1,25,25,25],[5,5,5,25,32]。
我错误地得到了这个错误?
答案 0 :(得分:7)
我认为问题在于您在Theano排序中设置输入形状,但您使用的是带有Tensorflow后端的Keras和Tensorflow img排序。此外,必须将y_train数组转换为分类标签。
更新的代码:
from keras.utils import np_utils
from keras import backend as K
if K.image_dim_ordering() == 'th':
X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols, img_depth)
input_shape = (1, img_rows, img_cols, img_depth)
else:
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, img_depth, 1)
input_shape = (img_rows, img_cols, img_depth, 1)
Y_train = np_utils.to_categorical(Y_train, nb_classes)
添加这些行应该修复它。