keras - 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) 但没有帮助。我难住了。
解决方案
数据应该是二维的。将您的 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()
推荐阅读
- python - 为什么我得到正确的回文输出但没有输出常规数字?
- rest - 如何设置全局soap ui基本身份验证和Accept as application/json
- ipython - 为什么在 ipython 上的 if 块之后续行会立即中断?
- windows - 打包为 UWP 应用时,带有两个字母名称 ('bg') 的文件夹内的图像消失
- ember.js - ember 引擎 routes.js 中的嵌套路由?
- jquery - Handsontable 中的虚拟键盘
- assembly - EAFFFFFE 在 ARM 架构中是什么意思
- php - 执行 mysqli_query 有效,但它不返回 WHERE CLAUSE 中给出的确切行
- javascript - 全球 Firebase 参考
- ios - AVCaptureSession captureOutput 回调丢帧并抛出 OutOfBuffers 错误