所以我在udemy上看了一个tensorflow的教程,决定自己试试,他说如果你想要2个以上的类别,就把激活改为 "softmax",单位改为4,因为我有4个不同的类别(从0:1改为1:4),如果 "y "中只有2个不同的值,一切都能正常工作,但是一旦我把它改为4个单位和4个类别,我就会得到错误。
ValueError: 检查目标时出错:预期dense_3的形状为(4,),但得到的是形状为(1,)的数组。
即使改回 "1 "的形状,结果也是真假不分。
我的数据集在Y中。
import numpy as np
dataset = np.load('/Users/alex/desktop/ANN_dataset_for_brightness.npy')
X = dataset[:, 0:17]
y = dataset[:, 17:19]
for i in range (27):
if y[i] == 400:
y[i] = 4
elif y[i] == 300:
y[i] = 3
elif y[i] == 200:
y[i] = 2
elif y[i] == 100:
y[i] = 1
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Dense
# Initialising the ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer // input dim for input layer
classifier.add(Dense(activation="relu", input_dim=17, units=6, kernel_initializer="uniform"))
# Adding the second hidden layer
classifier.add(Dense(activation="relu", units=6, kernel_initializer="uniform"))
# units = categories, softmax = more than 2
classifier.add(Dense(activation="softmax", units=4, kernel_initializer="uniform"))
# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Fitting the ANN to the Training set
classifier.fit(X_train, y_train, batch_size = 27, nb_epoch = 100)
# Part 3 - Making the predictions and evaluating the model
# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
与多类任务,你的y_train和y_test必须是一个热编码。这意味着它们必须有维度(number_of_samples, 4),其中4表示类的数量。
你需要在训练-测试拆分之前对它们应用 tensorflow.keras.utils.to_categorical。
y = to_categorical(y, 4)
参考文献 https:/www.tensorflow.orgapi_docspythontfkerasutilsto_categorical