Я получаю ошибку недопустимого аргумента при подаче тензоров на график в тензорном потоке?

Я использую tensorflow версии 1.5 в Windows 10. Я использую тонкую модель Tensorflow сети Inception V4, которая была взята с веб-сайта, используя их предварительно обученные веса и добавляя свои собственные слои в конце для классификации 120 различных объектов. Это полный код, за исключением строк, содержащих модули импорта и пути к наборам данных.

image_size = 299
tf.logging.set_verbosity(tf.logging.INFO)
with slim.arg_scope(inception_blocks_v4.inception_v4_arg_scope()):
    X_input = tf.placeholder(tf.float32, shape = (None, image_size, image_size, 3))
    Y_label = tf.placeholder(tf.float32, shape = (None, num_classes))        
    targets = convert_to_onehot(labels_dir, no_of_features = num_classes)
    targets = tf.constant(targets, dtype = tf.float32)

    Images = [] 
    images = glob.glob(images_file_path)
    i = 0
    for my_img in images:
        image = mpimg.imread(my_img)[:, :, :3]
        image = tf.constant(image, dtype = tf.float32)
        Images.append(image)

    logits, end_points = inception_blocks_v4.inception_v4(inputs = X_input, num_classes = pre_num_classes, is_training = True, create_aux_logits= False)
    pretrained_weights = slim.assign_from_checkpoint_fn(ckpt_dir, slim.get_model_variables('InceptionV4'))
    with tf.Session() as sess:
        pretrained_weights(sess)

    my_layer = slim.fully_connected(logits, 560, activation_fn=tf.nn.relu, scope='myLayer1', weights_initializer = tf.truncated_normal_initializer(stddev = 0.001), weights_regularizer=slim.l2_regularizer(0.00005),biases_initializer = tf.truncated_normal_initializer(stddev=0.001), biases_regularizer=slim.l2_regularizer(0.00005))
    my_layer = slim.dropout(my_layer, keep_prob = 0.6, scope = 'myLayer2')
    my_layer = slim.fully_connected(my_layer, num_classes,activation_fn = tf.nn.relu,scope= 'myLayer3', weights_initializer = tf.truncated_normal_initializer(stddev=0.001), weights_regularizer=slim.l2_regularizer(0.00005), biases_initializer = tf.truncated_normal_initializer(stddev=0.001), biases_regularizer=slim.l2_regularizer(0.00005))
    my_layer_logits = slim.fully_connected(my_layer, num_classes, activation_fn=None,scope='myLayer4')  
    loss = tf.losses.softmax_cross_entropy(onehot_labels = Y_label, logits = my_layer_logits)  
    optimizer = tf.train.AdamOptimizer(learning_rate=0.0001)
    train_op = slim.learning.create_train_op(loss, optimizer) 
    images, labels = tf.train.batch([Images, targets], batch_size = 8, num_threads = 1, capacity = batch_size, enqueue_many=True)
    tensor_images = tf.convert_to_tensor(images, dtype = tf.float32)
    tensor_labels = tf.convert_to_tensor(labels, dtype = tf.float32)
    with tf.Session() as sess:
        print (tensor_images)
        print (tensor_labels)
    final_loss = slim.learning.train(train_op,logdir = new_ckpt_dir, number_of_steps = 1000, save_summaries_secs=5,log_every_n_steps=50)(feed_dict = {X_input:tensor_images ,Y_label: tensor_labels})  #{X_input:images ,Y_label: labels}

Я попытался передать правильные тензоры данных в feed_dict графика на этапе обучения и распечатал их, что дало мне следующий результат.

Tensor("batch:0", shape=(8, 299, 299, 3), dtype=float32, device=/device:CPU:0)
Tensor("batch:1", shape=(8, 120), dtype=float32, device=/device:CPU:0)

Но также выдает следующую ошибку:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,120]
 [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[?,120], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

person Ashutosh Sancheti    schedule 14.03.2018    source источник


Ответы (1)


Правильный способ подачи данных, сгенерированных из tf.train.batch, выглядит следующим образом:

Постройте свою модель следующим образом:

logits, end_points = inception_blocks_v4.inception_v4(
    inputs = tensor_images, num_classes = pre_num_classes, 
    is_training = True, create_aux_logits= False)

И в вашем проигрыше вы должны использовать:

loss = tf.losses.softmax_cross_entropy(
    onehot_labels = tf.one_hot(tensor_labels), logits = my_layer_logits)  

Подача tensor в tf.placeholder в настоящее время не поддерживается.

Примечание. Я предполагаю, что ваш tensor_labels - это просто индекс меток.

person Fan Luo    schedule 14.03.2018