簡體   English   中英

Keras,簡單神經網絡錯誤代碼(model.predict)

[英]Keras, simple neural network Error Code (model.predict)

你們中有人知道為什么我會收到以下錯誤代碼嗎?

我的代碼:

import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as pl
from casadi import *
x = SX.sym("x",2)
f = vertcat(x[0]-x[0]*x[1],\
            -x[1]+x[0]*x[1])
dae = dict(x = x,ode = f)

# Create integrator
def Simulation(xst):
    t=0
    X1=list()
    X2=list()
    T=list()
    while t<=10 :
        op = dict(t0=0, tf=t)
        F = integrator("F", "cvodes", dae, op)
        r = F(x0 = [xst[0],xst[1]])
        X1.append(float(r["xf"][0]))
        X2.append(float(r["xf"][1]))
        T.append(t)
        t=t+1
    return(X1,T)
Simulation([1,2])

model=tf.keras.Sequential([
    keras.layers.Dense(1,input_shape=[2]),
])

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

input= np.array([[1,2],[2,3],[4,1],[5,3],[1,3],[3,1],[6,4],[5,2],[1,5],[8,3]])


def output():
    Out=[[]]
    for i in range(0,len(input)):
        X1,T=Simulation(input[i])
        maxA=max(X1)
        Out=np.append(Out,[maxA])
    return (Out)
model.fit(input,output(),epochs=10)
test=np.array([2,1])
print(model.predict(test))

您可以忽略積分器部分,我只想知道為什么 model.predict 不起作用。 這是錯誤:

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/pythonProject3/main.py", line 47, in <module>
    print(model.predict(test))
  File "C:\Users\User\PycharmProjects\pythonProject1\venv\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\User\AppData\Local\Temp\__autograph_generated_filedjega_6c.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\User\PycharmProjects\pythonProject1\venv\lib\site-packages\keras\engine\training.py", line 1845, in predict_function  *
        return step_function(self, iterator)
    File "C:\Users\User\PycharmProjects\pythonProject1\venv\lib\site-packages\keras\engine\training.py", line 1834, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\User\PycharmProjects\pythonProject1\venv\lib\site-packages\keras\engine\training.py", line 1823, in run_step  **
        outputs = model.predict_step(data)
    File "C:\Users\User\PycharmProjects\pythonProject1\venv\lib\site-packages\keras\engine\training.py", line 1791, in predict_step
        return self(x, training=False)
    File "C:\Users\User\PycharmProjects\pythonProject1\venv\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "C:\Users\User\PycharmProjects\pythonProject1\venv\lib\site-packages\keras\engine\input_spec.py", line 228, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" '

    ValueError: Exception encountered when calling layer "sequential" (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" (type Sequential):
      • inputs=tf.Tensor(shape=(None,), dtype=int32)
      • training=False
      • mask=None

問題出在以下幾行:

test=np.array([2,1])
print(model.predict(test))

在這里,您的 model 設置為接收 2 級張量作為輸入,但您只給它一個 1 級張量(向量)作為輸入。 您需要將維度擴大 1,如下所示:

test=np.array([[2,1]])
print(model.predict(test))

然后你會給它一個test.shape = (1,2)張量(等級 2),它現在應該可以正常工作了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM