【问题标题】:Keras neural network: ValueError - input shape is wrongKeras 神经网络:ValueError - 输入形状错误
【发布时间】:2020-03-16 17:37:22
【问题描述】:

我正在尝试编写一个小型回归神经网络作为学习基础知识的起点。

这是我正在使用的简单数据集:

https://i.stack.imgur.com/xx6mm.png

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
import pandas as pd
import io
import os
import requests
import numpy as np
from sklearn import metrics

df = pd.read_csv("C:\\Users\\Dan\\y_sinx.csv")

x = df['x'].values #Pandas to Numpy
y = df['y'].values


print(type(x)) #check type
print(np.shape(x)) #check dimensions
print(x) #check x

#Network
model = Sequential()
model.add(Dense(7, input_shape = x.shape, activation='relu')) #Hidden layer 1
model.add(Dense(4, activation='relu')) #Hidden layer 2
model.add(Dense(1)) #Output layer
model.compile(loss='mean_squared_error', optimizer = 'adam')
model.fit(x, y, verbose = 2, epochs = 20)

这段代码给出了输出:

<class 'numpy.ndarray'>
(7,)
[0.         0.78539816 1.57079633 2.35619449 3.14159265 3.92699082
 4.71238898]

所以它看起来是正确的大小 (7,),但也许 x 本身的输出看起来不对,应该是一列?我得到了错误:

ValueError                                Traceback (most recent call last)
<ipython-input-1-5db977397f3e> in <module>
     24 model.add(Dense(1)) #Output layer
     25 model.compile(loss='mean_squared_error', optimizer = 'adam')
---> 26 model.fit(x, y, verbose = 2, epochs = 20)
     27 
     28 #Prediction

~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    641         max_queue_size=max_queue_size,
    642         workers=workers,
--> 643         use_multiprocessing=use_multiprocessing)
    644 
    645   def evaluate(self,

~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, **kwargs)
    630         steps=steps_per_epoch,
    631         validation_split=validation_split,
--> 632         shuffle=shuffle)
    633 
    634     if validation_data:

~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split, shuffle, extract_tensors_from_dataset)
   2426           feed_input_shapes,
   2427           check_batch_axis=False,  # Don't enforce the batch size.
-> 2428           exception_prefix='input')
   2429 
   2430     if y is not None:

~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    519                              ': expected ' + names[i] + ' to have shape ' +
    520                              str(shape) + ' but got array with shape ' +
--> 521                              str(data_shape))
    522   return data
    523 

ValueError: Error when checking input: expected dense_input to have shape (7,) but got array with shape (1,)

我不确定它是如何得到一个形状为 (1,) 的数组以及如何修复它,将不胜感激!

【问题讨论】:

    标签: python tensorflow machine-learning keras valueerror


    【解决方案1】:

    Keras 期望输入层中 X 的属性或变量的数量,但您将输入层定义为

    model.add(Dense(7, input_shape = x.shape, activation='relu')) #Hidden layer 1
    

    所以,这意味着输入层中将有 7 个隐藏单元,这不应该是真的,因为 X 中只有 1 个变量。 尝试做:

    model.add(Dense(1, input_dim = x.shape[0], activation='relu')) #Input layer
    

    【讨论】:

    • 当我尝试得到:ValueError: Error when checking input: expected dense_32_input to have shape (7,) but got array with shape (1,)
    • 是的,对不起。删除input_dim参数就没有问题了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 2020-12-28
    • 2019-09-09
    • 2018-01-24
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多