Tensorflow InvalidArgumentError矩阵大小不兼容

时间:2019-07-28 19:02:26

标签: python tensorflow keras

当我启动简单的神经网络时,出现错误。顺便说一句,代码应该输出测试数组的第一个数字。

还有其他错误(与数据的dtype有关。)

import tensorflow as tf
import numpy as np
from tensorflow import keras

data = np.array([[0, 1, 1], [0, 0, 1], [1, 1, 1]])
labels = np.array([0, 0, 1])
data.dtype = float
print(data.dtype)
model = keras.Sequential([
keras.layers.Dense(3, activation=tf.nn.relu),
keras.layers.Dense(2, activation=tf.nn.softmax)])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(data, labels)
prediction = model.predict([0, 1, 0])
print(prediction)

我收到此错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [3,1], In[1]: [3,3]
     [[{{node sequential/dense/Relu}}]]

1 个答案:

答案 0 :(得分:0)

由于下面一行,您遇到了错误:

    <?php
        ob_start();

        function cook($user, $pass, $time){
            setcookie("user", $user, time() + $time, "/", "localhost", 0);
            setcookie("pass", $pass, time() + $time, "/", "localhost", 0);
        }

        header('Content-Type: application/json');

        //login code(receive data, check password, ...)

        cook($user, hash("sha512", $pass), 7200);

        $output = //my code output object

        echo json_encode($output);

        ob_end_flush();

您传递的prediction = model.predict([0, 1, 0]) 应该是一个numpy数组,形状为list,其中Nx3基本上是批处理大小,可以为1、2等。在这种情况下,将会是N

为了使其正确,请将其更改为

1

prediction = model.predict(np.expand_dims(np.array([0, 1, 0], dtype=np.float32), 0))

然后将prediction = model.predict(np.array([[0, 1, 0]], dtype=np.float32))更改为data.dtype = float