检查失败:vec.size()== NDIMS(1 vs. 2)RaspberryPi卷积神经网络中的异常错误

时间:2018-08-27 01:59:35

标签: python tensorflow conv-neural-network raspberry-pi3

我正在尝试在RaspberryPi 3B上训练Tensorflow卷积神经网络。我收到以下错误:

2018-08-19 18:57:07.720022: F./tensorflow/core/util/bcast.h:111] Check failed:
vec.size() == NDIMS (1 vs. 2)
Aborted

不知道出了什么问题,但这是代码:

import tensorflow as tf
import numpy as np
import csv
import pandas as pd
import os

image_height = 60
image_width = 1

image1_height = 15
image2_height = 1

model_name = "TensorflowCNN"


#Training Data Configuration

train_data = np.asarray(pd.read_csv("/media/pi/DISK_IMG/TrainingInput.csv", usecols=[1]))
lis = train_data.tolist()
lis = lis[0:60]
lis = [x[0].strip('[]\n,') for x in lis]
nlis = []
for i in lis:
    nlis.append(i.split())
for i in range(len(nlis)):
    nlis[i] = [float(x) for x in nlis[i] if x != "...,"]
nlis = [np.mean(x) for x in nlis]
train_data = np.asarray(nlis)

#Training Labels Configuration

train_labels = np.asarray(pd.read_csv("/media/pi/DISK_IMG/TrainingInput.csv", usecols=[2]))
mylist = train_labels.tolist()
mylist = mylist[0:60]
mylist = [x[0] for x in mylist]
index = 0
while index < len(mylist):
    if mylist[index] == "GravelTraining":
        mylist[index] = 1
    elif mylist[index] == "WaterTraining":
        mylist[index] = 2
    else:
        mylist[index] = 3

    index=index+1

train_labels = np.asarray(mylist)

#Validation Data Configuration

eval_data = np.asarray(pd.read_csv("/media/pi/DISK_IMG/TestingInput.csv", usecols=[1]))
List = eval_data.tolist()
List = List[0:15]
eval_data = np.asarray(List)

#Validation Labels Configuration

eval_labels = np.asarray(pd.read_csv("/media/pi/DISK_IMG/TestingInput.csv", usecols=[2]))
myList = eval_labels.tolist()
myList = myList[0:15]
index = 0
while index < len(myList):
    if myList[index] == "GravelTesting":
        myList[index] = 1
    elif myList[index] == "WaterTesting":
        myList[index] = 2
    else:
        myList[index] = 3

    index=index+1
eval_labels = np.asarray(myList)

category_names = list(map(str, range(3)))

#Processing and reshaping data

train_data = np.reshape(train_data, (-1, image_height, image_width, 1))
train_labels = np.reshape(train_labels, (-1, image_height, image_width, 1))

eval_data = np.reshape(eval_data, (-1, image1_height, image2_height, 1))
eval_labels = np.reshape(eval_labels, (-1, image1_height, image2_height, 1))


#CLASS FOR THE CONVOLUTIONAL NEURAL NETWORK


class ConvNet:

    def __init__(self, image_height, Image_width, num_classes, chan):

        self.input_layer = tf.placeholder(dtype = tf.float32, shape = [1,image_height, Image_width, chan], name = "inputs")

        conv_layer_1 = tf.layers.conv2d(self.input_layer, filters = 32, kernel_size = [5,5], padding = "same", activation = tf.nn.relu)
        pooling_layer_1 = tf.layers.max_pooling2d(conv_layer_1, pool_size = [2,1], strides = 1)

        flattened_pooling = tf.layers.flatten(pooling_layer_1)
        dense_layer = tf.layers.dense(flattened_pooling, 60, activation = tf.nn.relu)

        dropout = tf.layers.dropout(dense_layer, rate = 0.4, training = True)

        output_dense_layer = tf.layers.dense(dropout, num_classes)

        self.choice = tf.argmax(output_dense_layer, axis=1)
        self.probabilities = tf.nn.softmax(output_dense_layer)

        self.labels = tf.placeholder(dtype=tf.float32, name="labels")
        self.accuracy, self.accuracy_op = tf.metrics.accuracy(self.labels, self.choice)

        one_hot_labels = tf.one_hot(indices=tf.cast(self.labels, dtype=tf.int32), depth=num_classes)
        self.loss = tf.losses.softmax_cross_entropy(onehot_labels = one_hot_labels, logits=output_dense_layer)

        optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-2)
        self.train_operation = optimizer.minimize(loss=self.loss, global_step=tf.train.get_global_step())

#Training process:variables

training_steps = 20000
batch_size = 60

path = "./" + model_name + "-cnn/"

load_checkpoint = False

tf.reset_default_graph()
dataset = tf.data.Dataset.from_tensor_slices((train_data, train_labels))
dataset = dataset.shuffle(buffer_size=train_labels.shape[0])
dataset = dataset.batch(batch_size)
dataset = dataset.repeat()

dataset_iterator = dataset.make_initializable_iterator()
next_element = dataset_iterator.get_next()

#Final initialization of Neural Network and Training Process

cnn = ConvNet(image_height, image_width, 1, 1)
print("milestone1")

saver = tf.train.Saver(max_to_keep=2)
print('milestone2')

if not os.path.exists(path):
    os.makedirs(path)
print('milestone3')

#Training Loop For neural network

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())
    print('milestone4')

    sess.run(tf.local_variables_initializer())
    sess.run(dataset_iterator.initializer)

    for step in range(training_steps):

        current_batch = sess.run(next_element)
        batch_inputs = current_batch[0]
        batch_labels = current_batch[1]
        print("milestone5")
        sess.run((cnn.train_operation, cnn.accuracy_op), feed_dict={cnn.input_layer:batch_inputs, cnn.labels:batch_labels})

        if step % 1 == 0 and step > 0:
            current_acc = sess.run(cnn.accuracy)
            print("Accuracy at step " + str(step) + ":" + str(current_acc))
            saver.save(sess, path + model_name, step)

    print("Saving final checkpoint for training session.")
    saver.save(sess, path + model_name, step)

我知道这很长,但是如果有人可以让我知道我的程序出了什么问题,我将不胜感激。没有回溯,我从Stack Overflow收到通知,说我的帖子主要是代码,但是关于这个问题的话实际上没有太多要说的了。此外,我查看了许多与此相关的问题,但没有找到我可以使用的答案。预先感谢!

0 个答案:

没有答案