简体   繁体   English

ValueError:形状(无,2)和(无,3)不兼容

[英]ValueError: Shapes (None, 2) and (None, 3) are incompatible

So this is the code I'm trying to run所以这是我试图运行的代码

from sklearn.datasets import make_blobs
from tensorflow.keras.utils import to_categorical
from keras.layers import *
from keras import metrics 
from tensorflow.keras.optimizers import SGD
from keras.models import Sequential
from keras.layers import Dense
import numpy as np


def prepa ():
X, y = make_blobs(n_samples=1000,centers=3, n_features=2,random_state=2)

testX=X[:499]
trainX=X[500:999]
testy=y[:499]
trainy=y[500:999]

return trainX,trainy,testX,testy


trainX, testX, trainy,testy=prepa()


#define the model
model = Sequential()  # Création d'un réseau de neurones vide 
model.add(Dense(50,input_dim=2,activation="relu",kernel_initializer='he_uniform'))
model.add(Dense(3,activation="Softmax"))

#compile the model
opt = SGD(learning_rate=0.001)
model.compile(loss='categorical_crossentropy',optimizer=opt,metrics=['accuracy'])

fit the model 
history=model.fit(trainX, trainy, validation_data=(testX, testy), epochs=200, verbose=0)

But I receive this Error:但我收到此错误:

ValueError Traceback (most recent call last) ValueError 回溯(最近一次调用)

in () 1 #fit the model ----> 2 history=model.fit(trainX, trainy, validation_data=(testX, testy), epochs=200, verbose=0) in () 1 #拟合模型----> 2 history=model.fit(trainX, trainy, validation_data=(testX, testy), epochs=200,verbose=0)

9 frames 9帧

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) 992 except Exception as e: # pylint:disable=broad-except 993 if hasattr(e, "ag_error_metadata"): --> 994 raise e.ag_error_metadata.to_exception(e) 995 else: 996 raise /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) 992 除了异常为 e: # pylint:disable=broad-except 993 if hasattr(e, "ag_error_metadata"): --> 994 raise e.ag_error_metadata.to_exception(e) 995 else: 996 raise

ValueError: in user code:值错误:在用户代码中:

/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:853 train_function  *
    return step_function(self, iterator)
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:842 step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1286 run
    return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:2849 call_for_each_replica
    return self._call_for_each_replica(fn, args, kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:3632 _call_for_each_replica
    return fn(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:835 run_step  **
    outputs = model.train_step(data)
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:789 train_step
    y, y_pred, sample_weight, regularization_losses=self.losses)
/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py:201 __call__
    loss_value = loss_obj(y_t, y_p, sample_weight=sw)
/usr/local/lib/python3.7/dist-packages/keras/losses.py:141 __call__
    losses = call_fn(y_true, y_pred)
/usr/local/lib/python3.7/dist-packages/keras/losses.py:245 call  **
    return ag_fn(y_true, y_pred, **self._fn_kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper
    return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/keras/losses.py:1666 categorical_crossentropy
    y_true, y_pred, from_logits=from_logits, axis=axis)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper
    return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/keras/backend.py:4839 categorical_crossentropy
    target.shape.assert_is_compatible_with(output.shape)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_shape.py:1161 assert_is_compatible_with
    raise ValueError("Shapes %s and %s are incompatible" % (self, other))

ValueError: Shapes (None, 2) and (None, 3) are incompatible

As, your error depicts, there is something wrong with the shapes.正如您的错误所描述的那样,形状有问题。 You should always check your data shapes before training the model to avoid any inconsistency issues.在训练模型之前,您应该始终检查数据形状,以避免出现任何不一致问题。

So, when I checked, the shape of testX is (501,) which should be (501,2) and this is happening because testX is getting assigned to trainy in your code.因此,当我检查时, testX的形状是(501,) ,它应该是(501,2) ,这是因为testX在您的代码中被分配给trainy

Replace代替

trainX,testX,trainy,testy = prepa()

with

trainX,trainy,testX,testy = prepa()

because this is what you are returning from the prepa() function and unpacking should be in suitable/similar order to maintain the assignments.因为这是您从prepa()函数返回的内容,并且解包应该以合适/相似的顺序来维护分配。


Also, you should use following indexing in prepa() function to get the whole dataset.此外,您应该在prepa()函数中使用以下索引来获取整个数据集。

testX = X[:499]
trainX = X[499:]
testy = y[:499]
trainy = y[499:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “ValueError:形状 (None, 1) 和 (None, 6) 不兼容” - “ValueError: Shapes (None, 1) and (None, 6) are incompatible” ValueError:形状 (None, 2) 和 (None, 1) 不兼容 - ValueError: Shapes (None, 2) and (None, 1) are incompatible ValueError:形状 (None, 1) 和 (None, 3) 不兼容 - ValueError: Shapes (None, 1) and (None, 3) are incompatible ValueError:形状 (None, 0, 5) 和 (None, 5) 不兼容 - ValueError: Shapes (None, 0, 5) and (None, 5) are incompatible ValueError:形状(无,无)和(无,无,无,3)不兼容 - ValueError: Shapes (None, None) and (None, None, None, 3) are incompatible ValueError:形状(无,无)和(无,无,无,43)不兼容 - ValueError: Shapes (None, None) and (None, None, None, 43) are incompatible ValueError: Shapes (None, 3, 2) 和 (None, 2) 不兼容使用 tfrecord - ValueError: Shapes (None, 3, 2) and (None, 2) are incompatible using tfrecord Tensorflow:ValueError:形状(None,1)和(None,2)不兼容 - Tensorflow: ValueError: Shapes (None, 1) and (None, 2) are incompatible ValueError:形状(无,1)和(无,101)不兼容 - ValueError: Shapes (None, 1) and (None, 101) are incompatible ValueError:形状 (None, 22) 和 (None, 10) 不兼容 - ValueError: Shapes (None, 22) and (None, 10) are incompatible
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM