python - ValueError : Cannot feed value of shape (165, ) 对于张量 'Placeholder_11:0' ,其形状为 '(?, 2)'

标签 python python-3.x machine-learning tensorflow scikit-learn

我刚刚学习 TensorFlow。该计划的目标是探测地雷和岩石。但是当我提供占位符时我遇到了问题。我在这个网站上读到了很多关于这个问题的问题,但找不到解决方案。

feed_dict 中,train_y 的形状为 (165,)y (占位符)为(?, 2)...这是我认为的问题。但我不知道如何解决。我尝试 reshape train_y 但它不起作用。

我有这个错误:

ValueError: Cannot feed value of shape (165,) for Tensor 'Placeholder_11:0', which has shape '(?, 2)'

这是data和我的程序:

import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split


#traitement des données
df = pd.read_csv('sonar.all-data.csv')
X = df[df.columns[:60]].values
y = df[df.columns[60]]
encoder = LabelEncoder()
encoder.fit(y)
y = encoder.transform(y)


#mix data
X,y = shuffle(X, y, random_state = 1)

#separate date for training
train_x, test_x, train_y, test_y = train_test_split(X, y, test_size = 0.2, random_state = 415)




# Parameters
learning_rate = 0.1
num_steps = 500
display_step = 100


# Network Parameters
n_hidden_1 = 60 # 1st layer number of neurons 60
n_hidden_2 = 60 # 2nd layer number of neurons 60
num_input = X.shape[1]
num_classes = 2



# tf Graph input
X = tf.placeholder("float", [None, num_input])
Y = tf.placeholder("float", [None, num_classes])



# Store layers weight & bias
weights = {
    'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes]))
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([num_classes]))
}



# Create model
def neural_net(x):
    # Hidden fully connected layer with 50 neurons
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Hidden fully connected layer with 50 neurons
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    # Output fully connected layer with a neuron for each class
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    out_layer = tf.nn.relu(out_layer)
    
    return out_layer


# Construct model
logits = neural_net(X)
prediction = tf.nn.softmax(logits)



# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)


# Evaluate model
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))


# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()




# Start training
with tf.Session() as sess:

    # Run the initializer
    sess.run(init)

    for step in range(1, num_steps+1):
        sess.run(train_op, feed_dict={X: train_x, Y: train_y})
        if step % display_step == 0 or step == 1:
            # Calculate loss and accuracy
            loss, acc = sess.run([loss_op, accuracy], feed_dict={X: train_x,
                                                                 Y: train_y})
            print("Step " + str(step) + ", Minibatch Loss= " + \
                  "{:.4f}".format(loss) + ", Training Accuracy= " + \
                  "{:.3f}".format(acc))

感谢您的帮助!

最佳答案

我认为你应该对标签应用one-hot编码y:将你的LabelEncoder替换为sklearn.preprocessing.OneHotEncoder .

此代码应该适用于您的数据:

y = df[df.columns[60]].apply(lambda x: 0 if x == 'R' else 1).values.reshape(-1, 1)
encoder = OneHotEncoder()
encoder.fit(y)
y = encoder.transform(y)

关于python - ValueError : Cannot feed value of shape (165, ) 对于张量 'Placeholder_11:0' ,其形状为 '(?, 2)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46911972/

相关文章:

python-3.x - Numpy 计算随机 2D 或 1D 数组中的 Min Max

machine-learning - 如何扩展训练数据集中的模型以覆盖训练数据的各个方面

machine-learning - 神经网络有哪些不同类型或其层次分类

python - 如何将函数应用于列表中的每个元素,然后列出输出?

python - 简单 Python 代码中的 Str 对象错误

python - 提取字符、字符串或括号之间的文本

machine-learning - 在 tensorflow 中实现 MLP

python - 如何定期执行 CherryPy 中的函数

python-3.x - 有人可以帮我吗。我在用Python编写此代码时遇到问题

python - Python 重复单词