Python Keras NN,处理 n_samples 的浮点输出

数据挖掘 Python 神经网络 分类 喀拉斯
2022-02-15 09:04:46

我在 Python 中使用 Keras 和 Theanos 后端。

我有 2117 个样本,每个样本都有一个单独的目标(故意),即。2117 个输出。

与类别相反,目标是评级,例如。(16.4714494876, 17.4129353234, 17.4476570289) 整个数字很重要。

我有问题/不知道从哪里开始。

1)当我运行 NN 时,它只将目标输出为整数,而不是实际值的格式。例如。16 而不是 16.xxxxxx

2)大概我只能根据输出与目标的接近程度来衡量预测的准确性,因为有这么多目标,这种类型的分类问题有我可以研究的名称吗?

3)在我读过的 3 篇研究论文中,将 NN 应用于我的特定分类问题,他们将输出层列为只有 1 个神经元,但没有提供进一步的解释,这怎么可能?

这是我的模型。

# fix random seed for reproducibility
seed = 7
np.random.seed(seed)

X = np.array(df[FEATURES].values)
Y = np.array(df["MTPS"].values)

# define baseline model
def baseline_model():
    # create model
    model = Sequential()
    model.add(Dense(10, input_dim=(len(FEATURES)), init='normal', activation='relu'))
    model.add(Dense(2117, init='normal', activation='softmax'))
    # Compile model
    model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model
#build model
estimator = KerasClassifier(build_fn=baseline_model, nb_epoch=100, batch_size=5, verbose=2)

#cross validation
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=seed)
estimator.fit(X_train, Y_train)

#print class predictions
print estimator.predict(X_test)
print Y_test

谢谢你的帮助。

1个回答

我很困惑。正如你所说,目标是收视率。这对我来说绝对是一个回归问题,而不是分类问题。

您的代码中有几个问题:

  1. 对于回归问题,我们通常使用linear作为最后一层的激活函数(有时relu,甚至sigmoid)。
  2. 我们也将mse其用作度量(有时maemsle等)。categorical_crossentropy用于分类问题,sparse_categorical_crossentropy用于稀疏输入分类问题。参考
  3. KerasClassifier用于分类问题,KerasRegressor改为使用。
  4. metrics=['accuracy']用于分类问题,在回归问题中没有意义。参考
  5. 假设df是 Pandas DataFrame,那么df.values自然是 a ndarrary,就不用强制转换了np.array

现在回答你的问题:

  1. 因为我从来没有为 scikit-learn API 使用过包装器,所以我不太确定为什么你有整数输出,我最好的猜测是因为KerasClassifier.predict(在 scikit-learn APIs 中,.predict返回整数,基本上是预测的类并.predict_proba返回浮点数,表示每个类别的概率)。尝试使用.predict_proba,它会有所帮助。顺便说一句,你真的应该使用KerasRegressor.
  2. 正如你所提到的,有很多类要预测。事实上,这是一个回归问题。
  3. 能否请您添加这 3 篇论文的链接?输出层中只有 1 个神经元的神经网络对我来说似乎是回归 NN。回归 NN 通常Dense(1, activation='linear')用作输出层。

这是我的代码版本,它可能有效:

# fix random seed for reproducibility
seed = 7
np.random.seed(seed)

X = df[FEATURES].values  # no need to cast np.array
Y = df["MTPS"].values

# define baseline model
def baseline_model():
    # create model
    model = Sequential()
    model.add(Dense(10, input_dim=(len(FEATURES)), init='normal', activation='relu'))
    model.add(Dense(1, init='normal', activation='linear'))  # one neuron, linear activation
    # Compile model
    model.compile(loss='mse', optimizer='adam')  # mse loss
    return model
#build model
estimator = KerasRegressor(build_fn=baseline_model, nb_epoch=100, batch_size=5, verbose=2)  # KerasRegressor for regression problem

#cross validation
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=seed)
estimator.fit(X_train, Y_train)

#print class predictions
print estimator.predict(X_test)
print Y_test

参考