python神经网络分类_神经网络分类
这是一个多类分类任务。目标属性是“Class”。你知道吗我的代码如下-# Column names to be used for training and testing sets-col_names = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'Class']# Read in training and testing dat
这是一个多类分类任务。目标属性是“Class”。你知道吗
我的代码如下-# Column names to be used for training and testing sets-
col_names = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'Class']
# Read in training and testing datasets-
training_data = pd.read_csv("shuttle_training.csv", delimiter = ' ', names = col_names)
testing_data = pd.read_csv("shuttle_test.csv", delimiter = ' ', names = col_names)
print("\nTraining data dimension = {0} and testing data dimension = {1}\n".format(training_data.shape, testing_data.shape))
# Training data dimension = (43500, 10) and testing data dimension = (14500, 10)
# Data Preprocessing-
# Check for missing value(s) in training data-
training_data.isnull().values.any()
# False
# Get target attribute class distribution-
training_data["Class"].value_counts()
'''
1 34108
4 6748
5 2458
3 132
2 37
7 11
6 6
Name: Class, dtype: int64
'''
# NOTE: Majority of instances belong to class 1
# Visualizing the distribution of each attribute in dataset using boxplots-
fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')
sns.boxplot(data = training_data)
plt.xticks(rotation = 20)
plt.show()
# # To divide the data into attributes and labels, execute the following code:
# 'X' contains attributes
X = training_data.drop('Class', axis = 1)
# Convert 'X' to float-
X = X.values.astype("float")
# 'y' contains labels
y = training_data['Class']
# Normalize features (X)-
rb_scaler = RobustScaler()
X_std = rb_scaler.fit_transform(X)
# Divide attributes & labels into training & testing sets-
X_train, X_test, y_train, y_test = train_test_split(X_std, y, test_size = 0.30, stratify = y)
print("\nDimensions of training and testing sets are:")
print("X_train = {0}, y_train = {1}, X_test = {2} and y_test = {3}\n\n".format(X_train.shape, y_train.shape, X_test.shape, y_test.shape))
# Dimensions of training and testing sets are:
# X_train = (30450, 9), y_train = (30450,), X_test = (13050, 9) and y_test = (13050,)
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import Pipeline
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
# Create Neural Network model-
model = Sequential()
# Input layer-
model.add(Dense(9, input_dim = 9, kernel_initializer = 'normal', activation = 'relu'))
# Hidden layer(s)-
model.add(Dense(9, kernel_initializer = 'normal', activation='relu'))
# Output layer-
model.add(Dense(7, activation = 'softmax')) # 7 output neurons for 7 classes in target attribute
# Compile NN model-
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
'''
Layer (type) Output Shape Param #
=================================================================
dense_1 (Dense) (None, 9) 90
_________________________________________________________________
dense_2 (Dense) (None, 9) 90
_________________________________________________________________
dense_3 (Dense) (None, 7) 70
=================================================================
Total params: 250
Trainable params: 250
Non-trainable params: 0
_________________________________________________________________
''# Train model on training data-
history = model.fit(X_train, y_train, epochs = 200, batch_size = 50, validation_data = (X_test, y_test), verbose = 1, shuffle = False)
它给了我一个错误-ValueError: Error when checking target: expected dense_3 to have shape (7,) but got array with shape (1,)
好吧,根据‘Class’属性(这是我们的目标),似乎总共有7个类(尽管存在严重的类不平衡)。为什么我会有这个错误?有什么线索吗?你知道吗
谢谢!你知道吗
错误跟踪-
^{2}$

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)