Keras神经网络:ValueError-输入形状错误

时间:2019-11-20 21:47:10

标签: python tensorflow machine-learning keras valueerror

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

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

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,)的数组以及如何修复它的,将不胜感激!

1 个答案:

答案 0 :(得分: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