tensorflow - 如何在 Python 中运行条件神经网络(类似于 R/Stata 中的 clogit)?

标签 tensorflow machine-learning keras neural-network statistics

我正在寻找在 Keras(或如果需要的话 tensorflow )中训练一个神经网络来预测哪三个玩家被指定 stars在每场 NHL 曲棍球比赛中。我的 X 矩阵包含每个玩家的标准得分信息,例如上场时间、进球数、助攻数等,目标变量可以是四个类别之一(0 - 不在最佳三名中,1 - 最佳球员,2 - 第二最佳球员,3 - 第三最佳球员)。

到目前为止,这是一个非常标准的问题,普通神经网络在预测玩家被指定为明星的概率方面做得相当不错。问题是我想添加一个约束,强制单个游戏中第 1、2、3 类的概率总和为 1(所有玩家),同时保持 softmax 约束,即每个玩家的所有类的概率总和也必须为一。我注意到 conditional logistic regression模型实现了二元分类,但我还没有看到它在机器学习框架中实现。

我相信这需要 Keras 可以实现的自定义激活函数。但是我不确定数学/代码会是什么样子。

到目前为止我运行的示例代码是这样的:

# import packages
import numpy as np
from keras.layers import Dense
from keras.models import Sequential
from keras.optimizers import Adam

# generate data
games, m = 50, 40
X = np.zeros((games * m, 11))
Y = np.zeros((games * m, 4))

for i in range(games):
    rowStart, rowEnd = (i) * m, (1 + i) * m
    X[rowStart:rowEnd, 0] = i
    X[rowStart:rowEnd, 1:] = np.random.rand(m, 10)  

    for j in range(1, 4):
        rowInd = rowStart + np.random.randint(0, m)
        while np.sum(Y[rowInd]) != 0.0:
            rowInd = rowStart + np.random.randint(0, m)
        Y[rowInd, j] = 1    

# run model   
mod2 = Sequential()
mod2.add(Dense(10, activation='relu', input_shape=(X.shape[1]-1,)))
mod2.add(Dense(6, activation='relu'))
mod2.add(Dense(4, activation='softmax'))
adam = Adam(lr=0.001)
mod2.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['categorical_accuracy'])
hist = mod2.fit(X[:,1:], Y, epochs=10, batch_size=m)

最佳答案

我真的很喜欢你关于“双向 softmax”的想法。抱歉,但过了一段时间我能够证明这样的 softmax 在一般情况下是不可能的(如果感兴趣,我可以添加一个简化的描述为什么)。

但是还有其他方法可以解决这个问题,无需“双向 softmax”,并且不会违反您的限制。我建议您使用具有 10 个特征的 40 名玩家的完整游戏作为输入,并对 40 名玩家中的每一位进行排名作为输出。 我建议您不要将每个玩家分为 4 个类别,而是给每个玩家一个分数(例如 -1 表示未进入最佳三名玩家,0 表示第三最佳玩家,1 表示第二最佳玩家,2 表示最佳玩家)。在预测时,您可以选择得分最大的玩家为最佳玩家,第二大的为第二好,第三大的为第三好,其余的为未进入前三名。 这样,您就不会违反每个玩家都应获得“类别”的限制,并且只有一名玩家获得第一、第二和第三名。

请参阅下面的最小工作示例:

# import packages
import numpy as np
from tensorflow.keras.layers import Dense, Input, Flatten#, Reshape
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam

# generate data
games, m = 50, 40
X = np.zeros((games, m, 11))
Y = np.zeros((games, m))

for i in range(games):
    X[i, :, 0] = i
    X[i, :, 1:] = np.random.rand(m, 10)  

    y_indexes = np.arange(m)
    np.random.shuffle(y_indexes)
    # score players
    Y[i,y_indexes[0]] = 2 # best
    Y[i,y_indexes[1]] = 1 # second best
    Y[i,y_indexes[2]] = 0 # third best
    Y[i,y_indexes[3:]] = -1 # not best

# run model   
inputs = Input(shape=(m,10)) # -1 as we dont use fist column (game number)
inputs_flatten = Flatten()(inputs)
x = Dense(1024, activation='relu')(inputs_flatten)
x = Dense(512, activation='relu')(x)
x = Dense(256, activation='relu')(x)
outputs = Dense(m, activation=None)(x)
model = Model(inputs = inputs, outputs = outputs)

adam = Adam(lr=0.001)
model.compile(optimizer=adam, loss='mse', metrics=['accuracy'])
hist = model.fit(X[:,:,1:], Y, epochs=20, batch_size=10)

# predict third, second and best players for the first game
# the print number, is the player number
Y_pred = model.predict(X[0:1,:,1:])
print(np.argsort(Y_pred.reshape(-1))[-3:])
#[7 29 19]
# True best players fist game
print(np.argsort(Y[0,:].reshape(-1))[-3:])
#[7 29 19]

请注意,对于如此小的数据集(只有 50 个事件,每个游戏一个),此模型架构比建议的更深并且具有更多的节点。

关于tensorflow - 如何在 Python 中运行条件神经网络(类似于 R/Stata 中的 clogit)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56679166/

相关文章:

python - Tensorflow:从输入到输出的梯度计算

Python - NLTK 训练/测试分割

machine-learning - 异常: The passed model is not callable and cannot be analyzed directly with the given masker

python - Keras 性能不佳(损失和优化功能?)

python - 在 Keras 中下载 ResNet50 生成 "SSL: CERTIFICATE_VERIFY_FAILED"

python - 联邦学习训练期间模型性能没有提高

python - 如何在 TensorFlow 中更改 csv 文件的 dtype?

python - 如何在训练和测试阶段使用不同的损失函数

machine-learning - 具有不同基础学习器的 AdaBoostClassifier

tensorflow - 如何将训练有素的 Tensorflow 模型转换为 Keras?