Hi im trying to build a model in keras that can predict some data based on training values. I've seen this work succesfully all over the internet but my example code doesn't work:
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(4,))) #input shape of 50
model.add(Dense(28, activation='relu')) #input shape of 50
model.add(Dense(4, activation='sigmoid'))
xtrain=np.asarray([[3,4,3,2],[1,0,1,2],[1,1,1,1]])
ytrain=np.asarray([[1,1,1,1],[0,0,0,0],[2,2,2,2]])
model.compile(optimizer="sgd",loss="categorical_crossentropy")
model.fit(xtrain,ytrain,epochs=10)
xtest=xtrain[0]
data=model.predict(xtest)
print(data)
this comes up with the error:
WARNING:tensorflow:Model was constructed with shape (None, 4) for input
KerasTensor(type_spec=TensorSpec(shape=(None, 4), dtype=tf.float32, name='dense_input'),
name='dense_input', description="created by layer 'dense_input'"), but it was called on
an input with incompatible shape (None,).
Traceback (most recent call last):
File "C:\Users\macla\Downloads\kerasmartai.py", line 30, in <module>
data=model.predict(xtest)
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\macla\AppData\Local\Temp\__autograph_generated_filefmg_w5bl.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:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 2041, in predict_function *
return step_function(self, iterator)
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 2027, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 2015, in run_step **
outputs = model.predict_step(data)
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 1983, in predict_step
return self(x, training=False)
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\input_spec.py", line 250, in assert_input_compatibility
raise ValueError(
ValueError: Exception encountered when calling layer "sequential" " f"(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" " f"(type Sequential):
• inputs=tf.Tensor(shape=(None,), dtype=int32)
• training=False
• mask=None
however running what appears to be an exactly same piece of code works perfectly:
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import make_blobs
from sklearn.preprocessing import MinMaxScaler
# generate 2d classification dataset
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
scalar = MinMaxScaler()
scalar.fit(X)
X = scalar.transform(X)
# define and fit the final model
model = Sequential()
model.add(Dense(4, input_shape=(2,), activation='relu'))
model.add(Dense(4, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(X, y, epochs=500, verbose=0)
# new instances where we do not know the answer
Xnew, _ = make_blobs(n_samples=3, centers=2, n_features=2, random_state=1)
Xnew = scalar.transform(Xnew)
# make a prediction
ynew = model.predict(Xnew)
# show the inputs and predicted outputs
for i in range(len(Xnew)):
print("X=%s, Predicted=%s" % (Xnew[i], ynew[i]))
so how can I train my data like in the second example with the code im using?
From what I can see, it trains fine and fails at the predict step. see if it runs fine when you set xtest = xtrain and not just the first slice. Or reshape xtrain:
xtest=xtrain[0].reshape(-1,4)