用 keras 预测数据错误

问题描述 投票:0回答:1

嗨,我正在尝试在 keras 中构建一个模型,该模型可以根据训练值预测一些数据。 我已经在互联网上看到这项工作成功,但我的示例代码不起作用:

from keras.models import Sequential
from keras.layers import Dense, Activation

import numpy as np

model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(4,))) #input shape of 50
model.add(Dense(28, activation='relu')) #input shape of 50
model.add(Dense(4, activation='sigmoid'))

xtrain=np.asarray([[3,4,3,2],[1,0,1,2],[1,1,1,1]])
ytrain=np.asarray([[1,1,1,1],[0,0,0,0],[2,2,2,2]])

model.compile(optimizer="sgd",loss="categorical_crossentropy")

model.fit(xtrain,ytrain,epochs=10)

xtest=xtrain[0]

data=model.predict(xtest)
print(data)

出现错误:

WARNING:tensorflow:Model was constructed with shape (None, 4) for input 
KerasTensor(type_spec=TensorSpec(shape=(None, 4), dtype=tf.float32, name='dense_input'), 
name='dense_input', description="created by layer 'dense_input'"), but it was called on 
an input with incompatible shape (None,).
Traceback (most recent call last):
File "C:\Users\macla\Downloads\kerasmartai.py", line 30, in <module>
data=model.predict(xtest)
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\macla\AppData\Local\Temp\__autograph_generated_filefmg_w5bl.py", line 15, in tf__predict_function
retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
ValueError: in user code:

File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 2041, in predict_function  *
    return step_function(self, iterator)
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 2027, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 2015, in run_step  **
    outputs = model.predict_step(data)
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 1983, in predict_step
    return self(x, training=False)
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
File "C:\Users\macla\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\input_spec.py", line 250, in assert_input_compatibility
    raise ValueError(

ValueError: Exception encountered when calling layer "sequential" "                 f"(type Sequential).

Input 0 of layer "dense" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)

Call arguments received by layer "sequential" "                 f"(type Sequential):
  • inputs=tf.Tensor(shape=(None,), dtype=int32)
  • training=False
  • mask=None

然而,运行看起来完全相同的一段代码却完美无缺:

from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import make_blobs
from sklearn.preprocessing import MinMaxScaler
# generate 2d classification dataset
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
scalar = MinMaxScaler()
scalar.fit(X)
X = scalar.transform(X)
# define and fit the final model
model = Sequential()
model.add(Dense(4, input_shape=(2,), activation='relu'))
model.add(Dense(4, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(X, y, epochs=500, verbose=0)
# new instances where we do not know the answer
Xnew, _ = make_blobs(n_samples=3, centers=2, n_features=2, random_state=1)
Xnew = scalar.transform(Xnew)
# make a prediction
ynew = model.predict(Xnew)
# show the inputs and predicted outputs
for i in range(len(Xnew)):
    print("X=%s, Predicted=%s" % (Xnew[i], ynew[i]))

那么我如何使用我使用的代码像第二个示例中那样训练我的数据?

python keras deep-learning
1个回答
1
投票

据我所知,它训练得很好,但在预测步骤失败了。 当您设置 xtest = xtrain 而不仅仅是第一个切片时,看看它是否运行正常。或者重塑 xtrain:

xtest=xtrain[0].reshape(-1,4)
© www.soinside.com 2019 - 2024. All rights reserved.