我只是在学习TensorFlow。该计划的目标是探测地雷和岩石。但是当我给占位符喂食时,我遇到了问题。我在这个网站上读到了很多关于这个问题的问题,但是找不到解决办法。
在feed_dict
中train_y
的形状为(165,)
,y
(占位符)为(?, 2)
......我认为这是问题所在。但我不知道如何解决它。我尝试重塑train_y
,但它不起作用。
我有这个错误:
ValueError:无法为Tensor提供形状值(165,) 'placeholder_11:0',其形状为'(?,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))
感谢您的帮助!
答案 0 :(得分:0)
我认为您应该对标签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)