我正在做基本的千层面示例: https ://github.com/Lasagne/Lasagne/blob/master/examples/mnist.py
我通过将它与另一个类似的例子结合起来稍微修改了它。
我正在尝试运行 CNN 模型,在其中我向 CNN def 添加了一些额外的输入,但应该没有什么不同。还将示例中输入层的默认值 28 更改为 60(高度和宽度),稍后在代码中使用类,但代码“挂起”在最后一个网络行,这意味着代码是仍在运行,但什么也没有发生。 运行代码时输出。input_var 在主循环中是这样定义的:
input_var = T.tensor4('input_var')
其余代码:
def build_cnn(classes, height, width, input_var=None):
print("Input layer, with height: {}, width: {} and input var: {}".format(height, width, input_var))
network = lasagne.layers.InputLayer(shape = (None, 1, height, width),
input_var=input_var)
print("Convolutional layer with 32 kernels of size 5x5")
network = lasagne.layers.Conv2DLayer(network,
num_filters = 32,
filter_size = (5, 5),
nonlinearity = lasagne.nonlinearities.rectify,
W = lasagne.init.HeNormal(gain = 'relu'))
编辑: 好的,根据我到目前为止的尝试,这似乎是我自己的数据集是问题所在。我已经重塑了我的数据集以匹配 MNIST 数据集。X_train 的形状为 [图像、通道、高度、宽度]。其中通道 = 1 和高度,宽度 = 60。检索这些的代码是:
def load_images():
dataset_path = os.path.abspath("C:/Users/laende/Dropbox/Skole UiS/4. semester/Master/Master/data/test_database")
[bilder, label, names] = read_images1(dataset_path, (28, 28))
label = np.array(label)
bilder = bilder / np.float32(256)
bilder = bilder[:, newaxis, :, :]
X_train1, X_test1, Y_train1, Y_test1 = train_test_split(bilder, label, test_size = 0.2)
list_of_labels = list(xrange(max(label) + 1))
classes = len(list_of_labels)
return X_train1, X_test1, Y_train1, Y_test1, classes
其中 read_images1 是:
def read_images1(path, sz = None, channel = None):
c = 0
X = []
y = []
folder_names = []
for dirname, dirnames, filenames, in os.walk(path):
for subdirname in dirnames:
subject_path = os.path.join(dirname, subdirname)
folder_names.append(subdirname)
for filename in os.listdir(subject_path):
try:
im = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE)
if (sz is not None):
im = cv2.resize(im, sz)
X.append(np.asarray(im, dtype = np.uint8))
y.append(c)
except IOError, (errno, strerror):
print "I/O error ({0]): {1}".format(errno, strerror)
except:
print "unexpected error:", sys.exc_info()[0]
raise
c = c + 1
return [X, y, folder_names]
运行的 main 中的代码:
def main(model='mlp', num_epochs=100):
# Load the dataset
print("Loading data...")
mnist = 1
if mnist == 1:
classes = 10
X_train, y_train, X_val, y_val, X_test, y_test = load_dataset()
dataset = {
'train': {'X': X_train, 'y': y_train},
'test': {'X': X_test, 'y': y_test}}
shape = dataset['train']['X'][0].shape
else:
X_train, X_test, y_train, y_test, classes = load_images()
dataset = {
'train': {'X': X_train, 'y': y_train},
'test': {'X': X_test, 'y': y_test}}
shape = dataset['train']['X'][0].shape
input_var = T.tensor4('inputs')
target_var = T.ivector('targets')
print("Building model and compiling functions...")
if model == 'mlp':
network = build_mlp(height=int(shape[1]),
width=int(shape[2]),
channel=int(shape[0]),
classes=int(classes),
input_var=input_var)
如果 mnist = 1 (主要)代码运行良好,如果我尝试使用我自己的数据集,它会卡在 build_mlp 中(类似于 cnn 的原始问题):
def build_mlp(classes, channel, height, width, input_var=None):
neurons = int(height * width)
network = lasagne.layers.InputLayer(shape = (None, channel, height, width),
input_var=input_var)
network = lasagne.layers.DropoutLayer(network, p = 0.2)
#Code gets stuck on this point, running forever, doing nothing.
#No error messages received either.
network = lasagne.layers.DenseLayer(
network,
num_units = neurons,
nonlinearity = lasagne.nonlinearities.rectify,
W = lasagne.init.GlorotUniform())
编辑 2: 在为此苦苦挣扎了一段时间后,我发现在 read_images1() 中调整图像大小导致了问题:
def read_images1(path, sz = None, channel = None):
c = 0
X = []
y = []
folder_names = []
for dirname, dirnames, filenames, in os.walk(path):
for subdirname in dirnames:
subject_path = os.path.join(dirname, subdirname)
folder_names.append(subdirname)
for filename in os.listdir(subject_path):
try:
im = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE)
#This part caused the problems.
if (sz is not None):
im = cv2.resize(im, sz)
X.append(np.asarray(im, dtype = np.uint8))
y.append(c)
except IOError, (errno, strerror):
print "I/O error ({0]): {1}".format(errno, strerror)
except:
print "unexpected error:", sys.exc_info()[0]
raise
c = c + 1
return [X, y, folder_names]
如果我没有通过任何调整大小并使用文件夹中的默认图像大小,则神经网络能够编译。有谁知道为什么?我将 read_images1() 更新为:
def read_images1(path, sz = None, na = False):
"""
:param path: sti til mappe med underliggende mapper tilhørende personer.
:param sz: Størrelse på bildefilene
:return: returnerer liste av bilder, labels og navn
"""
c = 0
X = []
y = []
folder_names = []
for dirname, dirnames, filenames, in os.walk(path):
for subdirname in dirnames:
subject_path = os.path.join(dirname, subdirname)
folder_names.append(subdirname)
for filename in os.listdir(subject_path):
try:
im = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE)
if (sz is not None):
im = cv2.resize(im, dsize=sz, interpolation = cv2.INTER_LANCZOS4)
if (na == True):
im = im[newaxis, :, :]
X.append(np.asarray(im, dtype = np.uint8))
y.append(c)
except IOError, (errno, strerror):
print "I/O error ({0]): {1}".format(errno, strerror)
except:
print "unexpected error:", sys.exc_info()[0]
raise
c = c + 1
return [X, y, folder_names]
如果我使用 sz = None 和 na = True 运行程序,那么它可以工作。如果为 sz 参数指定了任何大小,则代码会在尝试再次编译神经网络时卡住。