Skip to content
Advertisement

Keras, simple neural network Error Code (model.predict)

Do any of you know why I get the following error code?

My Code :

import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as pl
from casadi import *
x = SX.sym("x",2)
f = vertcat(x[0]-x[0]*x[1],
            -x[1]+x[0]*x[1])
dae = dict(x = x,ode = f)

# Create integrator
def Simulation(xst):
    t=0
    X1=list()
    X2=list()
    T=list()
    while t<=10 :
        op = dict(t0=0, tf=t)
        F = integrator("F", "cvodes", dae, op)
        r = F(x0 = [xst[0],xst[1]])
        X1.append(float(r["xf"][0]))
        X2.append(float(r["xf"][1]))
        T.append(t)
        t=t+1
    return(X1,T)
Simulation([1,2])

model=tf.keras.Sequential([
    keras.layers.Dense(1,input_shape=[2]),
])

model.compile(optimizer="sgd" , loss="mean_squared_error")

input= np.array([[1,2],[2,3],[4,1],[5,3],[1,3],[3,1],[6,4],[5,2],[1,5],[8,3]])


def output():
    Out=[[]]
    for i in range(0,len(input)):
        X1,T=Simulation(input[i])
        maxA=max(X1)
        Out=np.append(Out,[maxA])
    return (Out)
model.fit(input,output(),epochs=10)
test=np.array([2,1])
print(model.predict(test))

You can ignore the Integrator Part, I just want to know why the model.predict wont work. Here is the error:

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/pythonProject3/main.py", line 47, in <module>
    print(model.predict(test))
  File "C:UsersUserPycharmProjectspythonProject1venvlibsite-packageskerasutilstraceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:UsersUserAppDataLocalTemp__autograph_generated_filedjega_6c.py", line 15, in tf__predict_function
    retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
ValueError: in user code:

    File "C:UsersUserPycharmProjectspythonProject1venvlibsite-packageskerasenginetraining.py", line 1845, in predict_function  *
        return step_function(self, iterator)
    File "C:UsersUserPycharmProjectspythonProject1venvlibsite-packageskerasenginetraining.py", line 1834, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:UsersUserPycharmProjectspythonProject1venvlibsite-packageskerasenginetraining.py", line 1823, in run_step  **
        outputs = model.predict_step(data)
    File "C:UsersUserPycharmProjectspythonProject1venvlibsite-packageskerasenginetraining.py", line 1791, in predict_step
        return self(x, training=False)
    File "C:UsersUserPycharmProjectspythonProject1venvlibsite-packageskerasutilstraceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "C:UsersUserPycharmProjectspythonProject1venvlibsite-packageskerasengineinput_spec.py", line 228, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" '

    ValueError: Exception encountered when calling layer "sequential" (type Sequential).
    
    Input 0 of layer "dense" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)
    
    Call arguments received by layer "sequential" (type Sequential):
      • inputs=tf.Tensor(shape=(None,), dtype=int32)
      • training=False
      • mask=None

Advertisement

Answer

The problem is with the lines:

test=np.array([2,1])
print(model.predict(test))

Here your model is setup to receive a rank 2 tensor as input, but you are only giving it a rank 1 tensor (vector) as input. You need to expand the dimension by 1, like this:

test=np.array([[2,1]])
print(model.predict(test))

You will then be giving it a test.shape = (1,2) tensor (rank 2) and it should now work without error.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement