简体   繁体   中英

Data cardinality is ambiguous

Could you help me? This is the full code

ValueError: Data cardinality is ambiguous: x sizes: 3 y sizes: 20 Make sure all arrays contain the same number of samples.

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt


x_data=np.array([[1,1,1,1,1,5,5,5,5,5,1,1,1,1,1,5,5,5,5,5],
                [3,5,1,3,5,1,3,5,1,3,5,1,3,5,1,3,5,1,3,5],
                [1,2,3,4,5,4,3,2,1,2,3,4,5,4,3,2,1,2,3,4]])
y_data=np.array([11,6,10,6,5,19,14,14,27,15,5,9,5,5,10,15,19,21,14,12])


model=Sequential()
model.add(Dense(11,input_dim=3, activation='sigmoid'))
model.add(Dense(1,activation='sigmoid'))


sgd=tf.keras.optimizers.SGD(lr = 0.01, momentum= 0.45)
model.compile(loss='mse',optimizer=sgd,metrics=['accuracy'])

batch_size=1
epochs=500
                                                                    
result=model.fit(np.array(x_data),np.array(y_data), batch_size, epochs=epochs, shuffle=True, verbose=0)

result.history.keys()
plt.plot(result.history['loss'])

The Data cardinality error is due to x_data.shape and y_data.shape are mismatching.

You can fix this error by reshaping the x_data shape before feeding it to the model using the below code.

x_data = x_data.reshape(x_data.shape[1],x_data.shape[0])
x_data.shape   # Output: (20, 3)

Please check this fixed code:

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt

x_data=np.array([[1,1,1,1,1,5,5,5,5,5,1,1,1,1,1,5,5,5,5,5],
                [3,5,1,3,5,1,3,5,1,3,5,1,3,5,1,3,5,1,3,5],
                [1,2,3,4,5,4,3,2,1,2,3,4,5,4,3,2,1,2,3,4]])
x_data.shape    # (3, 20)

y_data=np.array([11,6,10,6,5,19,14,14,27,15,5,9,5,5,10,15,19,21,14,12])
y_data.shape  # (20,)

x_data = x_data.reshape(x_data.shape[1],x_data.shape[0])
x_data.shape  # (20, 3)

model=Sequential()
model.add(Dense(16, activation='relu'))
model.add(Dense(1,activation='sigmoid'))


sgd=tf.keras.optimizers.SGD(learning_rate = 0.01, momentum= 0.45)
model.compile(loss='mse',optimizer=sgd,metrics=['accuracy'])

batch_size=1
epochs=500
                                                                    
result=model.fit(x_data,y_data, batch_size, epochs=epochs, shuffle=True, verbose=0)

result.history.keys()
plt.plot(result.history['loss'])

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