首页 > 解决方案 > Keras 在极其简单的测试代码中拟合 ValueError

问题描述

我在一个更复杂的 Keras 程序中遇到了一个非常持久的问题,但归结为:答案一定很简单,但我找不到。

当我运行此代码时:

def __init__ (self):
    self.model = Sequential()
    self.model.add(Dense(4, input_shape=(4,), activation='linear'))
    self.model.compile(optimizer='adam', loss='mse')
def run(self):
    x = [1., 1., 1., 1.]
    print('x:', x, 'x shape:', np.shape(x))
    y = [0., 0., 0., 0.]
    print('y:', y, 'y shape:', np.shape(y))
    self.model.fit(x, y, batch_size=1, epochs=1, verbose=2)

打印语句显示 x 和 y 的形状为 (4,),但拟合线生成:

ValueError:检查输入时出错:预期dense_1_input的形状为(4,)但得到的数组形状为(1,)

我尝试过重塑x为 (1,4) 但没有帮助。我难住了。

标签: keras

解决方案


数据应该是二维的。将您的 x 和 y 数据设置为 2D by x = [[1., 1., 1., 1.]]。它变成了1x4数据。 1是数据的数量,4是您定义的维度input_shape。并且,将其设置为 numpy 数组x = np.array(x)。Keras 的fit方法需要numpy array. x: Numpy array of training data我从https://keras.io/models/model/看到。

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
import numpy as np

class A:
    def __init__ (self):
        self.model = Sequential()
        self.model.add(Dense(4, input_shape=(4,), activation='linear'))
        self.model.compile(optimizer='adam', loss='mse')

    def run(self):
        x = [[1., 1., 1., 1.]]
        print('x:', x, 'x shape:', np.shape(x))
        y = [[0., 0., 0., 0.]]
        print('y:', y, 'y shape:', np.shape(y))
        x = np.array(x)
        y = np.array(y)
        self.model.fit(x, y, batch_size=1, epochs=1, verbose=2)

a = A()
a.run()

推荐阅读