错误代码

def load_mat(path_data,name_data,reshapeSize,dtype='float32'):

    dataFile = path_data
    data1 = scio.loadmat(dataFile)
    r2 = data1[name_data]
    dataArr = np.reshape(r2, reshapeSize)
    return dataArr
Path = 'E:\**\PycharmProjects/testHandsTensor2/'  #自定义路径要正确
DataFile='covNum.mat'
LabelFile='label.mat'

print("Loading data and labels...")
Data=load_mat(Path+DataFile,'covNum',(6,60))

Label=np.hstack((np.ones((1,30)),np.zeros((1,30))))
print(Label)
print(np.shape(Label))

Indices=np.arange(Data.shape[1]) #随机打乱索引并切分训练集与测试集
np.random.shuffle(Indices)
print("Divide training and testing set...")
train_x=Data[:,Indices[:50]]
train_y=Label[:,Indices[:50]]
test_x=Data[:,Indices[50:]]
test_y=Label[:,Indices[50:]]
print("======================================")

tf.random.set_seed(0)
model = tf.keras.Sequential([tf.keras.layers.Dense(10,activation='relu',input_shape=(6,)),
                             tf.keras.layers.Dense(20,activation='relu',input_shape=(10,)),
                             tf.keras.layers.Dense(1,activation='sigmoid')])
model.summary()  #显示网络结构
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])  #定义优化方法为随机梯度下降,损失函数
# #x->训练集,y——>bia标签,epochs=10000训练的次数,validation_data=(test_x,test_y)——>验证集

print(np.shape(train_x),np.shape(train_y))
history = model.fit(train_x,train_y,epochs=1000,validation_data=(test_x,test_y))

错误原因

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

数据中训练集数据的shape是(6,50),标签格式是(1,50)。但是在tensorflow的网络中对数据的读取是横向选取一行作为一个样本,所以需要将train_x和test_x进行转置;
而且网络要求的一位普通标签格式需要是(50,)的,所以再对label再次reshape。

代码改动

Path = 'E:\*\PycharmProjects/testHandsTensor2/'  #自定义路径要正确
DataFile='covNum.mat'
LabelFile='label.mat'
print("Loading data and labels...")
Data=load_mat(Path+DataFile,'covNum',(6,60))
Label=np.hstack((np.ones((1,30)),np.zeros((1,30))))
Label=Label.reshape((60,))
print(Label)
print(np.shape(Label))
Indices=np.arange(Data.shape[1]) #随机打乱索引并切分训练集与测试集
np.random.shuffle(Indices)
print("Divide training and testing set...")
train_x=Data[:,Indices[:50]].T
train_y=Label[Indices[:50]]
test_x=Data[:,Indices[50:]].T
test_y=Label[Indices[50:]]
print("==================训练集数据和标签====================")
print(np.shape(train_x),np.shape(train_y))

结果
(50, 6) (50,)
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐