简体   繁体   中英

How to specify input_shape for Keras Sequential model

How do you deal with this error?

Error when checking target: expected dense_3 to have shape (1,) but got array with shape (398,)

I Tried changing the input_shape=(14,) which is the amount of columns in the train_samples, but i still get the error.

set = pd.read_csv('NHL_DATA.csv')
set.head()

train_labels = [set['Won/Lost']] 
train_samples = [set['team'], set['blocked'],set['faceOffWinPercentage'],set['giveaways'],set['goals'],set['hits'],
            set['pim'], set['powerPlayGoals'], set['powerPlayOpportunities'], set['powerPlayPercentage'],
           set['shots'], set['takeaways'], set['homeaway_away'],set['homeaway_home']]

train_labels = np.array(train_labels)
train_samples = np.array(train_samples)

scaler = MinMaxScaler(feature_range=(0,1))
scaled_train_samples = scaler.fit_transform(train_samples).reshape(-1,1)

model = Sequential()

model.add(Dense(16, input_shape=(14,), activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.compile(Adam(lr=.0001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(scaled_train_samples, train_labels, batch_size=1, epochs=20, shuffle=True, verbose=2)

1) You reshape your training example with .reshape(-1,1) which means all training samples have 1 dimension. However, you define the input shape of the network as input_shape=(14,) that tells the input dimension is 14. I guess this is one problem with your model.

2) You used sparse_categorical_crossentropy which means the ground truth labels are sparse ( train_labels should be sparse) but I guess it is not.

Here is an example of how your input should be:

import numpy as np
from tensorflow.python.keras.engine.sequential import Sequential
from tensorflow.python.keras.layers import Dense

x = np.zeros([1000, 14])
y = np.zeros([1000, 2])

model = Sequential()

model.add(Dense(16, input_shape=(14,), activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.compile('adam', 'categorical_crossentropy')
model.fit(x, y, batch_size=1, epochs=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM