The Dude
The Dude

Reputation: 681

Building a 2D to 2D Neural Network Model in Tensorflow -- Invalid Shapes

I want to design a neural network in Tensorflow2 that maps 2D values to other 2D values. I can't figure out how to initialize my model to do this without giving me a dimension error.

import numpy
import tensorflow as tf

def euclidean_distance_loss(y_true, y_pred):
    return numpy.sqrt(sum((y_true - y_pred)**2.0))

#===Make Data====#
x_train = numpy.asarray([ [1, 2], [3, 1], [2, 2] ])
x_test = numpy.asarray([ [10, 1], [2, 0], [5, 1] ])
y_train = numpy.asarray([ [3, 8], [2, 7], [3, 3] ])
y_test = numpy.asarray([ [1, 0], [0, 1], [4, 9] ])

#===Make Model===#
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(128,input_shape=(1, x_train_points.shape[1]), activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(5, activation='relu')
]) 


#===Run Model===#
model.compile(optimizer='adam', loss=euclidean_distance_loss, metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)

When I try and run this, I get:

ValueError: Dimensions must be equal, but are 2 and 5 for '{{node euclidean_distance_lowss/sub}} = Sub[T=DT_Float](IteratorGetNext:1, sequential/dense_1/Relu)' with input schapes: [?,2], [?,5].

How am I suppose to setup this neural network so that it can take in this type of 2D data? Sorry for the basic question -- I am just starting to use Tensorflow2!


Edit: Given a 2D vector as input, I want the model to output another 2D vector.

Upvotes: 0

Views: 233

Answers (1)

Zachary Garrett
Zachary Garrett

Reputation: 2941

The final layer of the model is defining a shape [5] output tensor per example:

tf.keras.layers.Dense(5, activation='relu')

However the labels (y_train and y_test) have shape [2] per example:

y_train = numpy.asarray([ [3, 8], [2, 7], [3, 3] ])
y_test = numpy.asarray([ [1, 0], [0, 1], [4, 9] ])

Trying changing the last layer to have 2 units.

Upvotes: 1

Related Questions