ValueError: Cannot feed value of shape (784,) for Tensor 'x:0', which has shape '(?, 784)' - python-3.x

This is my first experience with Tensorflow. There appears to be many queries to this ValueError, however I am not getting any relief. I am using the notMNIST dataset, which is split 70/30 train test.
The error message appears to suggest there is a problem with my mini-batch. I have printed the shape of the placeholders, reshaped the input and label data to no success.
import tensorflow as tf
tf.reset_default_graph()
num_inputs = 28*28 # Size of images in pixels
num_hidden1 = 500
num_hidden2 = 500
num_outputs = len(np.unique(y)) # Number of classes (labels)
learning_rate = 0.0011
inputs = tf.placeholder(tf.float32, shape=[None, num_inputs], name="x")
labels = tf.placeholder(tf.int32, shape=[None], name = "y")
print(np.expand_dims(inputs, axis=0))
print(np.expand_dims(labels, axis=0))
def neuron_layer(x, num_neurons, name, activation=None):
with tf.name_scope(name):
num_inputs = int(x.get_shape()[1])
stddev = 2 / np.sqrt(num_inputs)
init = tf.truncated_normal([num_inputs, num_neurons], stddev=stddev)
W = tf.Variable(init, name = "weights")
b = tf.Variable(tf.zeros([num_neurons]), name= "biases")
z = tf.matmul(x, W) + b
if activation == "sigmoid":
return tf.sigmoid(z)
elif activation == "relu":
return tf.nn.relu(z)
else:
return z
with tf.name_scope("dnn"):
hidden1 = neuron_layer(inputs, num_hidden1, "hidden1", activation="relu")
hidden2 = neuron_layer(hidden1, num_hidden2, "hidden2", activation="relu")
logits = neuron_layer(hidden2, num_outputs, "output")
with tf.name_scope("loss"):
xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits)
loss = tf.reduce_mean(xentropy, name="loss")
with tf.name_scope("evaluation"):
correct = tf.nn.in_top_k(logits, labels, 1)
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
with tf.name_scope("train"):
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
grads = optimizer.compute_gradients(loss)
training_op = optimizer.apply_gradients(grads)
for var in tf.trainable_variables():
tf.summary.histogram(var.op.name + "/values", var)
for grad, var in grads:
if grad is not None:
tf.summary.histogram(var.op.name + "/gradients", grad)
# summary
accuracy_summary = tf.summary.scalar('accuracy', accuracy)
# merge all summary
tf.summary.histogram('hidden1/activations', hidden1)
tf.summary.histogram('hidden2/activations', hidden2)
merged = tf.summary.merge_all()
init = tf.global_variables_initializer()
saver = tf.train.Saver()
from datetime import datetime
now = datetime.utcnow().strftime("%Y%m%d%H%M%S")
root_logdir = "tf_logs/example03/dnn_final"
logdir = "{}/run-{}/".format(root_logdir, now)
train_writer = tf.summary.FileWriter("models/dnn0/train",
tf.get_default_graph())
test_writer = tf.summary.FileWriter("models/dnn0/test", tf.get_default_graph())
num_epochs = 50
batch_size = 128
with tf.Session() as sess:
init.run()
print("Epoch\tTrain accuracy\tTest accuracy")
for epoch in range(num_epochs):
for idx_start in range(0, x_train.shape[0], batch_size):
idx_end = num_epochs
x_batch, y_batch = x_train[batch_size], y_train[batch_size]
sess.run(training_op, feed_dict={inputs: x_batch, labels: y_batch})
summary_train, acc_train = sess.run([merged, accuracy],
feed_dict={x: x_batch, y: y_batch})
summary_test, acc_test = sess.run([accuracy_summary, accuracy],
feed_dict={x: x_test, y: y_test})
train_writer.add_summary(summary_train, epoch)
test_writer.add_summary(summary_test, epoch)
print("{}\t{}\t{}".format(epoch, acc_train, acc_test))
save_path = saver.save(sess, "models/dnn0.ckpt")
The following error
ValueError: Cannot feed value of shape (784,) for Tensor 'x:0', which has shape '(?, 784)'
occurs in line 96
sess.run(training_op, feed_dict={inputs: x_batch, labels: y_batch})

Your tensors do have mixed up shapes. You feed a tensor where the batch index is at the end into a tensor where the batch index is at the front.
Do x_batch = numpy.swapaxes(x_batch, 1, 0) before feeding the tensor.

On this line, you're referring to inputs and labels
sess.run(training_op, feed_dict={inputs: x_batch, labels: y_batch})
Where as on the lines below,
summary_train, acc_train = sess.run([merged, accuracy],
feed_dict={x: x_batch, y: y_batch})
summary_test, acc_test = sess.run([accuracy_summary, accuracy],
feed_dict={x: x_test, y: y_test})
you're referring to x and y. Change these to be the same. I.e. it should be the same value as your placeholder variables. (inputs and labels)

Related

Reshape data to be usable for training GCN in PyTorch

I am trying to build Graph Convolutional Network. I converted my dataframe to PyTorch
required format using below code.
class S_Dataset(Dataset):
def __init__(self, df, transform=None):
self.df = df
self.transform = transform
def __len__(self):
return len(self.df)
def __getitem__(self, idx):
row = self.df.iloc[idx]
x = torch.tensor([row.date.to_pydatetime().timestamp(), row.s1, row.s2, row.s3, row.s4, row.temp ,row.rh, row.Location, row.Node ], dtype=torch.float)
y = torch.tensor([row.Location], dtype=torch.long)
weight1 = torch.tensor([row.neighbor1_distance], dtype=torch.float)
weight2 = torch.tensor([row.neighbor2_distance], dtype=torch.float)
weight3 = torch.tensor([row.neighbor3_distance], dtype=torch.float)
edge_index1 = torch.tensor([[row.Location, row.neighbor1_name]], dtype=torch.long).t()
edge_index2 = torch.tensor([[row.Location, row.neighbor2_name]], dtype=torch.long).t()
edge_index3 = torch.tensor([[row.Location, row.neighbor3_name]], dtype=torch.long).t()
edge_index = torch.cat([edge_index1, edge_index2, edge_index3 ], dim=1)
weight = torch.cat([weight1, weight2, weight3], dim=0)
if self.transform:
x, y, edge_index, weight = self.transform(x, y, edge_index, weight)
return x, y, edge_index, weight
Process_Data = S_Dataset(df)
Next I divided data into train and test set:
train_size = int(len(Process_Data) * 0.8)
test_size = len(Process_Data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(Process_Data, [train_size, test_size])
# Create dataloaders
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True )
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=True )
I designed a simple model:
import torch
import torch.nn as nn
import torch.optim as optim
from torch_geometric.nn import GCNConv
# Create the model
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = GCNConv(9, 128)
self.conv2 = GCNConv(128, 64)
self.fc1 = nn.Linear(64, 32)
self.fc2 = nn.Linear(32, len(location_to_id))
def forward(self, x, edge_index, weight):
x = self.conv1(x, edge_index, weight)
x = torch.relu(x)
x = self.conv2(x, edge_index, weight)
x = torch.relu(x)
x = x.view(-1, 64)
x = self.fc1(x)
x = torch.relu(x)
x = self.fc2(x)
return x
Finally to train the model:
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()
for epoch in range(100):
total_loss = 0
for batch in train_loader:
optimizer.zero_grad()
x, y, edge_index, weight = batch
y_pred = model(x, edge_index, weight)
loss = criterion(y_pred, y)
loss.backward()
optimizer.step()
total_loss += loss.item()
print('Epoch: {} Loss: {:.4f}'.format(epoch, total_loss / len(train_loader)))
I am facing following error:
IndexError: The shape of the mask [2, 3] at index 0 does not match the shape of the indexed tensor [32, 3] at index 0
x, y, edge_index, weight = batch
This line is causing error.
How can I resphae my data so I can train my model?
The batch size is set at 32, but there might not be enough samples to fit in the batch size of 32.
I am assuming, this error occurs after the code runs for some time, I would appreciate more context on the problem
A general solution could be decreasing the size of batch to something smaller and trying the code again. Making sure all samples are covered in the epoch.

ValueError: Cannot feed value of shape (4,) for Tensor 'Placeholder_36:0', which has shape '(?, 4)'

I am trying to implement tensorflow regression model ,my data shape is train_X=(200,4) and train_Y=(200,). i am getting shape error ,here is my piece of code please can anyone mention where i am doing mistake.
df=pd.read_csv('all.csv')
df=df.drop('Time',axis=1)
print(df.describe()) #to understand the dataset
train_Y=df["power"]
train_X=df.drop('power',axis=1)
train_X=numpy.asarray(train_X)
train_Y=numpy.asarray(train_Y)
n_samples = train_X.shape[0]
tf Graph Input
X = tf.placeholder('float',[None,len(train_X[0])])
Y = tf.placeholder("float")
Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")
Construct a linear model
pred = tf.add(tf.multiply(X, W), b)
Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
Gradient descent
Note, minimize() knows to modify W and b because Variable objects are
trainable=True by default
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
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)
# Fit all training data
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X: x, Y: y})
# Display logs per epoch step
if (epoch+1) % display_step == 0:
c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
"W=", sess.run(W), "b=", sess.run(b))
print("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')
# Graphic display
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
plt.legend()
plt.show()enter code here
i changed shape and problem solved
train_y = np.reshape(train_y, (-1, 1))

Deep Neural Network using TensorFlow: TypeError: 'VarianceScaling' object is not subscriptable

I'm trying to build a deep neural network model with 3 hidden layers using TensorFlow. But I've encountered an error VarianceScaling' object is not subscriptable on this line:
W_hidden_1 = tf.Variable(weight_initializer[n_input, n_hl1])
Below is my code:
n_input = 18
n_target = 1
n_hl1 = 10
n_hl2 = 10
n_hl3 = 10
learning_rate = 0.1
batch_size = 100
X = tf.placeholder('float')
Y = tf.placeholder('float')
# Initializers
sigma = 1
weight_initializer = tf.variance_scaling_initializer(mode="fan_avg", distribution="uniform", scale=sigma)
bias_initializer = tf.zeros_initializer()
# Layer 1: Variables for hidden weights and biases
W_hidden_1 = tf.Variable(weight_initializer[n_input, n_hl1])
bias_hidden_1 = tf.Variable(bias_initializer([n_hl1]))
# Layer 2: Variables for hidden weights and biases
W_hidden_2 = tf.Variable(weight_initializer([n_hl1, n_hl2]))
bias_hidden_2 = tf.Variable(bias_initializer([n_hl2]))
# Layer 3: Variables for hidden weights and biases
W_hidden_3 = tf.Variable(weight_initializer([n_hl2, n_hl3]))
bias_hidden_3 = tf.Variable(bias_initializer([n_hl3]))
# Output layer: Variables for output weights and biases
W_out = tf.Variable(weight_initializer([n_hl3, n_target]))
bias_out = tf.Variable(bias_initializer([n_target]))
# Hidden layer
hidden_1 = tf.nn.relu(tf.add(tf.matmul(X, W_hidden_1), bias_hidden_1))
hidden_2 = tf.nn.relu(tf.add(tf.matmul(hidden_1, W_hidden_2), bias_hidden_2))
hidden_3 = tf.nn.relu(tf.add(tf.matmul(hidden_2, W_hidden_3), bias_hidden_3))
# Output layer (must be transposed)
out = tf.transpose(tf.add(tf.matmul(hidden_3, W_out), bias_out))
#prediction = neural_network_model(x)
cost =tf.reduce_mean(tf.squared_difference(out, Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
epochs = 1000
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for e in range(epochs):
# Shuffle training data
shuffle_indices = np.random.permutation(np.arange(len(y_data)))
x_data = x_data[shuffle_indices]
y_data = y_data[shuffle_indices]
# Minibatch training
for i in range(0, len(y_data) // batch_size):
start = i * batch_size
batch_x = x_data[start:start + batch_size]
batch_y = y_data[start:start + batch_size]
# Run optimizer with batch
sess.run(optimizer, feed_dict={X: batch_x, Y: batch_y})
mse_final = sess.run(cost, feed_dict={X: x_test, Y: y_test})
print(mse_final)
Any help is appreciated. :)
This is because you need to insert parentheses as follows,
W_hidden_1 = tf.Variable(weight_initializer([n_input, n_hl1])).
and not
W_hidden_1 = tf.Variable(weight_initializer[n_input, n_hl1])
Otherwise, python thinks that you are trying to access tf.variance_scaling_initializer.
Hope this helps.

Not run the model with test_data - TypeError: Cannot interpret feed_dict key as Tensor: is not an element of this graph

I build a Neural Network with two hidden layer.
from collections import namedtuple
def multilayer_perceptron():
tf.reset_default_graph()
inputs = tf.placeholder(tf.float32, shape=[None,train_x.shape[1]])
y = tf.placeholder(tf.float32, shape=[None, 1])
weights = {
'h1': tf.Variable(tf.random_normal([train_x.shape[1], n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, 1]))
}
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([1]))
}
# Hidden layer con funzione di attivazione ReLU
layer_1 = tf.add(tf.matmul(inputs, weights['h1']), biases['b1'])
layer_1 = tf.nn.relu(layer_1)
# Hidden layer with ReLU activation
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.relu(layer_2)
# Output layer with linear activation
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
learning_rate = tf.placeholder(tf.float32)
is_training=tf.Variable(True,dtype=tf.bool)
cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=y,logits=out_layer )
cost = tf.reduce_mean(cross_entropy)
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
predicted = tf.nn.sigmoid(out_layer)
correct_pred = tf.equal(tf.round(predicted), y)
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Export the nodes
export_nodes = ['inputs', 'y', 'learning_rate','is_training', 'out_layer',
'cost', 'optimizer', 'predicted', 'accuracy']
Graph = namedtuple('Graph', export_nodes)
local_dict = locals()
graph = Graph(*[local_dict[each] for each in export_nodes])
return graph
pred1 = multilayer_perceptron()
Next I create a function for determinate the batch for input and output value:
def get_batch(data_x,data_y,batch_size=32):
batch_n=len(data_x)//batch_size
for i in range(batch_n):
batch_x=data_x[i*batch_size:(i+1)*batch_size]
batch_y=data_y[i*batch_size:(i+1)*batch_size]
yield batch_x,batch_y
epochs = 25
train_collect = 20
train_print=train_collect*2
learning_rate_value = 0.001
batch_size=400
x_collect = []
train_loss_collect = []
train_acc_collect = []
valid_loss_collect = []
valid_acc_collect = []
saver = tf.train.Saver()
Finally I launch the session that print a Loss function and accuracy of train model. I save the result on file .ckpt
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
iteration=0
for e in range(epochs):
for batch_x,batch_y in get_batch(train_x,train_y,batch_size):
iteration+=1
feed = {pred1.inputs: train_x,
pred1.y: train_y,
pred1.learning_rate: learning_rate_value,
pred1.is_training:True
}
train_loss, _, train_acc = sess.run([pred1.cost, pred1.optimizer, pred1.accuracy], feed_dict=feed)
if iteration % train_collect == 0:
x_collect.append(e)
train_loss_collect.append(train_loss)
train_acc_collect.append(train_acc)
if iteration % train_print==0:
print("Epoch: {}/{}".format(e + 1, epochs),
"Train Loss: {:.4f}".format(train_loss),
"Train Acc: {:.4f}".format(train_acc))
feed = {pred1.inputs: valid_x,
pred1.y: valid_y,
pred1.is_training:False
}
val_loss, val_acc = sess.run([pred1.cost, pred1.accuracy], feed_dict=feed)
valid_loss_collect.append(val_loss)
valid_acc_collect.append(val_acc)
if iteration % train_print==0:
print("Epoch: {}/{}".format(e + 1, epochs),
"Validation Loss: {:.4f}".format(val_loss),
"Validation Acc: {:.4f}".format(val_acc))
saver.save(sess, "./insurance2.ckpt")
When I launch the session for data set the code give me an error:
model=multilayer_perceptron()
restorer=tf.train.Saver()
with tf.Session() as sess:
restorer.restore(sess,"./insurance2.ckpt")
feed={
pred1.inputs:test_data,
pred1.is_training:False
}
test_predict=sess.run(pred1.predicted,feed_dict=feed)
The two error are:
ValueError: Tensor Tensor("Placeholder:0", shape=(?, 125), dtype=float32) is not an element of this graph.
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(?, 125), dtype=float32) is not an element of this graph.
In my graph I export input.

Rank mismatch error in Tensorflow

I'm working on creating an image classifier that can differentiate between cats and dogs. I have the follwing code:
import cv2
import os
from tqdm import tqdm
import numpy as np
import tensorflow as tf
img_height = 128
img_width = 128
path = "./train"
# class info
file = os.listdir(path)
index = []
images = []
# image size and channels
channels = 3
n_inputs = img_width * img_height * channels
# First convolutional layer
conv1_fmaps = 96 # Number of feature maps created by this layer
conv1_ksize = 4 # kernel size 3x3
conv1_stride = 2
conv1_pad = "SAME"
# Second convolutional layer
conv2_fmaps = 192
conv2_ksize = 4
conv2_stride = 4
conv2_pad = "SAME"
# Third layer is a pooling layer
pool3_fmaps = conv2_fmaps # Isn't it obvious?
n_fc1 = 192 # Total number of output features
n_outputs = 2
with tf.name_scope("inputs"):
X = tf.placeholder(tf.float32, shape=[None, img_width, img_height, channels], name="X")
X_reshaped = tf.reshape(X, shape=[-1, img_height, img_width, channels])
y = tf.placeholder(tf.int32, shape=[None, 2], name="y")
conv1 = tf.layers.conv2d(X_reshaped, filters=conv1_fmaps, kernel_size=conv1_ksize, strides=conv1_stride, padding=conv1_pad, activation=tf.nn.relu, name="conv1")
conv2 = tf.layers.conv2d(conv1, filters=conv2_fmaps, kernel_size=conv2_ksize, strides=conv2_stride, padding=conv2_pad, activation=tf.nn.relu, name="conv2")
n_epochs = 10
batch_size = 250
with tf.name_scope("pool3"):
pool3 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="VALID")
pool3_flat = tf.reshape(pool3, shape=[-1, pool3_fmaps * 8 * 8])
with tf.name_scope("fc1"):
fc1 = tf.layers.dense(pool3_flat, n_fc1, activation=tf.nn.relu name="fc1")
with tf.name_scope("output"):
logits = tf.layers.dense(fc1, n_outputs, name="output")
Y_proba = tf.nn.softmax(logits, name="Y_proba")
with tf.name_scope("train"):
xentropy=tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)
loss = tf.reduce_mean(xentropy)
optimizer = tf.train.AdamOptimizer()
training_op = optimizer.minimize(loss)
with tf.name_scope("eval"):
correct = tf.nn.in_top_k(logits, y, 1)
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
init = tf.global_variables_initializer()
with tf.name_scope("init_and_save"):
saver = tf.train.Saver()
def next_batch(num):
index = []
images = []
# Data set Creation
print("Creating batch dataset "+str(num+1)+"...")
for f in tqdm(range(num * batch_size, (num+1)*batch_size)):
if file[f].find("dog"):
index.append(np.array([0, 1]))
else:
index.append(np.array([1, 0]))
image = cv2.imread(path + "/" + file[f])
image = cv2.resize(image, (img_width, img_height), 0, 0, cv2.INTER_LINEAR)
# image = image.astype(np.float32)
images.append(image)
images = np.array(images, dtype=np.uint8)
images = images.astype('float32')
images = images / 255
print("\nBatch "+str(num+1)+" creation finished.")
# print([images, index])
return [images, index]
with tf.Session() as sess:
init.run()
for epoch in range(n_epochs):
for iteration in range(25000 // batch_size):
X_batch, y_batch = next_batch(iteration)
sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch})
print(epoch, "Train accuracy:", acc_train)
save_path = saver.save(sess, "./dogvscat_mnist_model.ckpt")
But I'm getting this error:
ValueError: Rank mismatch: Rank of labels (received 2) should equal rank of logits minus 1 (received 2).
Can anyone point out the problem and help me to solve it. I'm totally new to this.
For tf.nn.sparse_softmax_corss_entropy_with_logits rank(labels) = rank(logits) - 1, so you need to redefine the labels placeholder as follows
...
y = tf.placeholder(tf.int32, shape=[None], name="y")
...
xentropy=tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,labels=y)
...
X_batch, y_batch = next_batch(iteration)
y_batch = np.argmax(y_batch, axis=1)
OR you can you just use tf.nn.softmax_cross_entropy_with_logits without changing labels placeholder.
xentropy=tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y)

Resources