Tensorflow ValueError:检查输入时出错:预期密集_1_输入具有形状(3),但获得具有形状(2)的数组

Tensorflow ValueError:检查输入时出错:预期密集_1_输入具有形状(3),但获得具有形状(2)的数组,tensorflow,machine-learning,keras,model,reshape,Tensorflow,Machine Learning,Keras,Model,Reshape,我是机器学习新手。我正在尝试训练一个ANN,拟合方法会生成一个关于数组形状的错误“ValueError:检查输入时出错:预期密集_1_输入具有形状(3),但得到了具有形状(2,)的数组”。 知道我有3个输入(年龄、性别、标签)。 数据集包含3356行。显示前5行数据的图像 如下代码所示: import pandas as pd from keras.models import Sequential from keras.layers import Dense from sklearn.model

我是机器学习新手。我正在尝试训练一个ANN,拟合方法会生成一个关于数组形状的错误“ValueError:检查输入时出错:预期密集_1_输入具有形状(3),但得到了具有形状(2,)的数组”。 知道我有3个输入(年龄、性别、标签)。 数据集包含3356行。显示前5行数据的图像

如下代码所示:

import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder, OneHotEncoder

# Importing the dataset
dataset = pd.read_csv('Train_data1.csv')

X = dataset.iloc[:, 1:3].values # age, sex
y = dataset.iloc[:, 3].values #label

# Encoding categorical data
# Encoding the Independent Variable
labelencoder_X = LabelEncoder()
X[:, 1] = labelencoder_X.fit_transform(X[:, 1])
labelencoder_X_1 = LabelEncoder()
# Encoding the Dependent Variable
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)
print(X.shape) #after run : (3356, 2)
print(y.shape) #after run : (3356,)

# Splitting the dataset into the Training set and Test set

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

# Feature Scaling

sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
print(X_train.shape)
print(y_train.shape)

# Initialising the ANN
model = Sequential()
model.add(Dense(10, input_dim = 3, activation = 'relu'))
model.add(Dense(10, activation = 'relu'))
model.add(Dense(2, activation = 'softmax'))

# Compiling the ANN
model.compile(loss = 'categorical_crossentropy' , optimizer = 'adam' , metrics = ['accuracy'] )

# Fitting the ANN to the Training set
model.fit(X_train, y_train, batch_size = 10, epochs = 100)
运行后出现错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-fc00dae1105e> in <module>
      1 # Fitting the ANN to the Training set
----> 2 model.fit(X_train, y_train, batch_size = 10, epochs = 100)

~\Anaconda3\lib\site-packages\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, **kwargs)
    950             sample_weight=sample_weight,
    951             class_weight=class_weight,
--> 952             batch_size=batch_size)
    953         # Prepare validation data.
    954         do_validation = False

~\Anaconda3\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    749             feed_input_shapes,
    750             check_batch_axis=False,  # Don't enforce the batch size.
--> 751             exception_prefix='input')
    752 
    753         if y is not None:

~\Anaconda3\lib\site-packages\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    136                             ': expected ' + names[i] + ' to have shape ' +
    137                             str(shape) + ' but got array with shape ' +
--> 138                             str(data_shape))
    139     return data
    140 

ValueError: Error when checking input: expected dense_1_input to have shape (3,) but got array with shape (2,)
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在里面
1#将ANN安装到训练集
---->2型号配合(X系列,y系列,批量尺寸=10,历代=100)
~\Anaconda3\lib\site packages\keras\engine\training.py适合(self、x、y、批量大小、历元、详细、回调、验证分割、验证数据、随机、类权重、样本权重、初始历元、每历元的步骤、验证步骤、**kwargs)
950样品重量=样品重量,
951类重量=类重量,
-->952批次大小=批次大小)
953#准备验证数据。
954 do_验证=错误
~\Anaconda3\lib\site packages\keras\engine\training.py in\u standarding\u user\u数据(自身、x、y、样本重量、类别重量、检查数组长度、批次大小)
749馈送输入形状,
750检查批处理轴=False,#不强制执行批处理大小。
-->751异常(前缀为“输入”)
752
753如果y不是无:
标准化输入数据(数据、名称、形状、检查批处理轴、异常前缀)中的~\Anaconda3\lib\site packages\keras\engine\training\u utils.py
136':预期“+名称[i]+”具有形状”+
137 str(shape)+'但得到了具有shape的数组'+
-->138街(数据_形))
139返回数据
140
ValueError:检查输入时出错:预期密集_1_输入具有形状(3),但获得具有形状(2)的数组

标签为Y。X的尺寸为2。因此,将
input\u dim=3
更改为
input\u dim=2

y\u train=to\u category(y\u train)

输入y dim=X.shape[1],它会解决问题。

谢谢你的帮助,我这样做了,但它不起作用:我将输入y dim=3改为输入y dim=2,并将y\u train=添加到了y\u category(y\u train)。现在,它起作用了