ValueError : Weights for model sequential have not yet been created

Total
6
Shares

I’m testing a basic neural network model. But before go any further I’ve encountered this error shown in the screenshot.

Here is my code:

import numpy as np

# Training Data
x_train = np.array([[1.0,1.0]])
y_train = np.array([2.0])


for i in range(3,10000,2):
    x_train = np.append(x_train,[[i,i]],axis = 0)
    y_train = np.append(y_train,[i+i],axis = 0)


# Test Data
import numpy as np

x_test = np.array([[2.0,2.0]])
y_test = np.array([4.0])

for i in range(4,8000,4):
    x_test = np.append(x_test,[[i,i]],axis = 0)
    y_test = np.append(y_test,[i+i])

from tensorflow import keras    
from keras.layers import Flatten   # to flatten the input data
from keras.layers import Dense     # for the hidden layer

# We'll follow sequential method i.e. one after the other(input layer ---> hidden layer---> output layer) 

model = keras.Sequential()

# For input layer
model.add(Flatten(input_shape = x_train[0].shape))   # input layer

# For Hidden layer
model.add(Dense(2,activation = 'relu'))    # '2' represents a no. of neurons

# For Output layer
model.add(Dense(1))   # By default, activation = 'linear'

# before training
bf_train = model.get_weights()
bf_train

The error is :

ValueError: Weights for model sequential have not yet been created. Weights are created when the Model is first called on inputs or build() is called with an input_shape.


Solution

You should not mix tf 2.x and standalone keras. You should import as follows

from tensorflow import keras    
from tensorflow.keras.layers import Flatten   # to flatten the input data
from tensorflow.keras.layers import Dense     # for the hidden layer

Now, run the code and you will get some weight.

[array([[-0.43643105, -1.0268047 ],
        [ 1.0003897 ,  1.1105307 ]], dtype=float32),
 array([0., 0.], dtype=float32),
 array([[-0.19884515],
        [-0.78100944]], dtype=float32),
 array([0.], dtype=float32)]
Leave a Reply

Your email address will not be published. Required fields are marked *