python - ValueError:形状 (None, 2) 和 (None, 3) 不兼容
问题描述
所以这是我要运行的代码
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)
但我收到此错误:
ValueError Traceback(最近一次调用最后一次)
in () 1 #fit the model ----> 2 history=model.fit(trainX, trainy, validation_data=(testX, testy), epochs=200, verbose=0)
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
ValueError:在用户代码中:
/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
解决方案
正如您的错误所描述的那样,形状有问题。在训练模型之前,您应该始终检查您的数据形状以避免任何不一致问题。
所以,当我检查时,应该是testX
的形状,这是因为在你的代码中被分配了。(501,)
(501,2)
testX
trainy
代替
trainX,testX,trainy,testy = prepa()
和
trainX,trainy,testX,testy = prepa()
因为这是您从prepa()
函数返回的内容,并且解包应该以合适/相似的顺序来维护分配。
此外,您应该在函数中使用以下索引prepa()
来获取整个数据集。
testX = X[:499]
trainX = X[499:]
testy = y[:499]
trainy = y[499:]
推荐阅读
- python - python 3 ,0 中的除模 2
- c++ - 如何使用 Visual Studio C++ 将 2 个列表框添加到 1 个窗口?
- java - 有什么方法可以提高我的程序生成代码的性能吗?
- php - Laravel Eloquent whereDoesntHave() 文档让我感到困惑
- sql - 优化 SQL 中的查询
- php - 在 PHP 中重组一系列活动,将参与者与公共位置结合起来
- kubernetes - 使用过期时间注释 Kubernetes 资源
- vba - 为什么这要求我表达?
- javascript - 按元数据过滤器排序的数据表 - 最近激活的优先
- azure-ad-b2c - 密码保护不适用于自定义 B2C 流程