Tensorflow错误''无法为Tensor输入提供形状值(4,1):0',其形状为'(?,2)'''

时间:2018-05-23 23:18:05

标签: python tensorflow deep-learning

我在使用此代码时遇到以下错误:

文件“C:/ Users / lourd / Desktop / Arquivos /PROGRAMAÇÂO/ treino / IA”,第56行,在模块中     错误,_ = sess.run([cost,optimizer],feed_dict = {inputs:inp,targets:out})

文件“C:\ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ client \ session.py”,第900行,在运行中     run_metadata_ptr)

文件“C:\ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ client \ session.py”,第1111行,在_run中     STR(subfeed_t.get_shape())))

ValueError:无法为Tensor'输入提供形状(4,1)的值:0',其形状为'(?,2)'

我的代码:

 import tensorflow as tf

# Espaços reservados

inputs = tf.placeholder('float', [None, 2], name='input')
targets = tf.placeholder('float', name='Target')

# Variaveis

weight1 = tf.Variable(tf.random_normal(shape= [2, 3], stddev=0.02, name='Weight1'))
biases1 = tf.Variable(tf.random_normal(shape= [3], stddev=0.02), name='Biases1')

# Multiplicador

hlayer = tf.matmul(inputs, weight1)
hlayer += biases1

# Função de ativação

hlayer = tf.sigmoid(hlayer, name='hAtivador')

# Camada oculta crie camadas de saida e conclua a rede

weight2 = tf.Variable(tf.random_normal(shape=[3, 1], stddev=0.02), name='Weight2')
biases2 = tf.Variable(tf.random_normal(shape=[1], stddev=0.02), name='Biases2')

# Camada de saida

output = tf.matmul(hlayer, weight2)
output += biases2
output = tf.sigmoid(output, name='outActivation')

# Optimização para treinar

cost = tf.squared_difference(targets, output)
cost = tf.reduce_mean(cost)
optimizer = tf.train.AdamOptimizer().minimize(cost)

# sessao TensotFlow

import numpy as np

inp = [[0.1], [0.2], [1.0],[1.1]]
out = [[0], [1], [1], [0]]

inp = np.array(inp)
out = np.array(out)

# Começar a sessão

epochs = 4000

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    for i in range(epochs):
        error, _ =sess.run([cost,optimizer],feed_dict={inputs: inp,targets:out})
        print(i,error)

# Teste

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    for i in range(epochs):
        error, _ = sess.run([cost, optimizer], feed_dict={inputs: inp, targets: out})
        print(i, error)
    while True:
        a = input('Primeira entrada: ')
        b = input('Segunda entrada: ')
        inp = [[a, b]]
        inp = np.array(inp)
        prediction = sess.run([output], feed_dict={inputs: inp})
        print(prediction)

1 个答案:

答案 0 :(得分:1)

您向占位符提供的数据形状与占位符的形状不一致。

inputs = tf.placeholder('float', [None, 2], name='input')

VS

inp = [[0.1], [0.2], [1.0],[1.1]]

inputs形状更改为[None, 1]或为inp的每个条目添加第二个值。