密集层中的多个 Softmax

2024-01-25

I have a network, I want to apply softmax on dense layer. I have dense layer of shape (?, 312), I want to apply softmax on dense layer on units 1-9, 10-18...etc. I don't know how to do that. I mentioned an image below, I want something like this. enter image description here

我尝试了类似的方法,但这对我来说似乎并不正确,因为我正在采用整个 312 个单位并将其转换为另一个密集层。我想直接在312单位申请。

from keras.layers import Input, Dense, Conv2D, BatchNormalization, Activation, MaxPooling2D, Dropout, Flatten
from keras.models import Model
from keras.layers import concatenate
class CubNet:
    @staticmethod
    def main_network(inputs,chanDim):

        inputs = inputs
        x = Conv2D(32, (3, 3), padding="same")(inputs)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(3, 3))(x)
        x = Dropout(0.25)(x)
        #(CONV => RELU) * 2 => POOL
        x = Conv2D(64, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = Conv2D(64, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(2, 2))(x)
        x = Dropout(0.25)(x)

        # (CONV => RELU) * 2 => POOL
        x = Conv2D(128, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = Conv2D(128, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(2, 2))(x)
        x = Dropout(0.25)(x)
        return x
    @staticmethod
    def category_branch(inputs,numCategories,chanDim):
        inputs = inputs
        x = Conv2D(128, (3, 3), padding="same")(inputs)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(3, 3))(x)
        x = Dropout(0.25)(x)
        # (CONV => RELU) * 2 => POOL
        x = Conv2D(128, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = Conv2D(128, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(2, 2))(x)
        x = Dropout(0.25)(x)
        x = Flatten()(x)
        x = Dense(1024)(x)
        x = Activation("relu")(x)
        x = BatchNormalization()(x)
        x = Dropout(0.5)(x)

        # softmax classifier
        x = Dense(numCategories)(x)
        x = Activation("softmax", name = "category_output")(x)

        # return the constructed network architecture
        return x
    def Attribute_branch(inputs, numAtt, chanDim):
        inputs = inputs
        x = Conv2D(16, (3, 3), padding="same")(inputs)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(3, 3))(x)
        x = Dropout(0.25)(x)

        # CONV => RELU => POOL
        x = Conv2D(32, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(2, 2))(x)
        x = Dropout(0.25)(x)

        # CONV => RELU => POOL
        x = Conv2D(32, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(2, 2))(x)
        x = Dropout(0.25)(x)
        # define a branch of output layers for the number of different
        # colors (i.e., red, black, blue, etc.)
        x = Flatten()(x)
        x = Dense(312)(x)
        x = Activation("relu")(x)
        x = BatchNormalization()(x)
        print(x.shape)
        x1 = Dense(9)(x)
        x2 = Dense(15)(x)
        x3 = Dense(15)(x)
        x4 = Dense(15)(x)
        x5 = Dense(4)(x)
        x6 = Dense(15)(x)
        x7 = Dense(6)(x)
        x8 = Dense(15)(x)
        x9 = Dense(11)(x)
        x10 = Dense(15)(x)
        x11 = Dense(15)(x)
        x12 = Dense(14)(x)
        x13 = Dense(3)(x)
        x14 = Dense(15)(x)
        x15 = Dense(15)(x)
        x16 = Dense(15)(x)
        x17 = Dense(15)(x)
        x18 = Dense(5)(x)
        x19 = Dense(5)(x)
        x20 = Dense(14)(x)
        x21 = Dense(4)(x)
        x22 = Dense(4)(x)
        x23 = Dense(4)(x)
        x24 = Dense(15)(x)
        x25 = Dense(15)(x)
        x26 = Dense(15)(x)
        x27 = Dense(15)(x)
        #x28 = Dense(4)(x)
        x1 = Activation("softmax", name = "has_bill_shape")(x1)
        x2 = Activation("softmax", name = "has_wing_color")(x2)
        x3 = Activation("softmax", name = "has_upperpart_color")(x3)
        x4 = Activation("softmax", name = "has_underpart_color")(x4)
        x5 = Activation("softmax", name = "has_breast_pattern")(x5)
        x6 = Activation("softmax", name = "has_back_color")(x6)
        x7 = Activation("softmax", name = "has_tail_shape")(x7)
        x8 = Activation("softmax", name = "has_uppertail_color")(x8)
        x9 = Activation("softmax", name = "has_head_pattern")(x9)
        x10 = Activation("softmax", name = "has_breast_color")(x10)
        x11 = Activation("softmax", name = "has_throat_color")(x11)
        x12 = Activation("softmax", name = "has_eye_color")(x12)
        x13 = Activation("softmax", name = "has_bill_length")(x13)
        x14 = Activation("softmax", name = "has_forhead_color")(x14)
        x15 = Activation("softmax", name = "has_undertail_color")(x15)
        x16 = Activation("softmax", name = "has_nape_color")(x16)
        x17 = Activation("softmax", name = "has_belly_color")(x17)
        x18 = Activation("softmax", name = "has_wing_shape")(x18)
        x19 = Activation("softmax", name = "has_size")(x19)
        x20 = Activation("softmax", name = "has_shape")(x20)
        x21 = Activation("softmax", name = "has_back_pattern")(x21)
        x22 = Activation("softmax", name = "has_tail_pattern")(x22)
        x23 = Activation("softmax", name = "has_belly_pattrern")(x23)
        x24 = Activation("softmax", name = "has_primary_color")(x24)
        x25 = Activation("softmax", name = "has_leg_color")(x25)
        x26 = Activation("softmax", name = "has_bill_color")(x26)
        x27 = Activation("softmax", name = "has_crown_color")(x27)
        #x28 = Activation("softmax", name = "has_wing_pattern")(x28)
        x = concatenate([x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20,x21,x21,x22,x23
                        ,x24,x25,x26,x27], name="Attribute_output" )
        #print(x.shape)
        return x

    @staticmethod
    def Build(numCategories, numAttributes, finalAct="softmax"):
        inputshape = (299,299,3)
        chanDim = -1
        inputs = Input(shape=inputshape)
        main_output = CubNet.main_network(inputs, chanDim = chanDim)
        categoryBranch = CubNet.category_branch(main_output,numCategories, chanDim=chanDim)
        AttBranch = CubNet.Attribute_branch(main_output, numAttributes, chanDim=chanDim)

        model = Model(inputs=inputs, outputs=[categoryBranch, AttBranch], name ='Cub')
        return model
model = CubNet.Build(numCategories=200, numAttributes=312, finalAct="softmax")
losses = {"category_output" : "categorical_crossentropy",
         "Attribute_output" : "binary_crossentropy"}

loss_weight = {"category_output" : 1.0,
         "Attribute_output" : 1.0}

print("[INFO] Compiling Model....")
opt = Adam(lr = INIT_LR, decay = INIT_LR/EPOCHS)
model.compile(optimizer=opt, loss=losses, loss_weights=loss_weight, metrics=["accuracy"])

H = model.fit(trainX, {"category_output": trainCategoryY, "Attribute_output": trainAttY},
              validation_data = (valX,{"category_output": valCategoryY, "Attribute_output": valAttY}),
                        epochs= EPOCHS, verbose=1)
print("[INFO] serializing network....")
model.save("ATT_categorical.h5")

希望有人解答。Here https://datascience.stackexchange.com/questions/23614/keras-multiple-softmax-in-last-layer-possible是同一问题的链接,但这不起作用,因为密集层不接受 2 个参数。


我认为最简单的方法是使用Reshape层,然后沿正确的轴应用 softmax:

from keras.layers import Input, Lambda, Reshape
from keras.models import Model
from keras.activations import softmax
import numpy as np


inp = Input(shape=(312,1))
x = Reshape((78,4,1))(inp)
out = Lambda(lambda x: softmax(x, axis=2))(x)

model = Model(inp, out)

output = model.predict(np.zeros((1,312,1)))

请注意,Reshape 不需要批量大小。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

密集层中的多个 Softmax 的相关文章

  • ubuntu 20.04 上无法获取卷积算法错误~tensorflow-gpu

    我有一个 NVIDIA 2070 RTX GPU 我的操作系统是 Ubuntu20 04 我已经使用 conda 安装了tensorflow gpu 包 我有not安装了 CUDA toolkit 我相信它还会安装 CUDA toolkit
  • 是否可以忽略一行的pyright检查?

    我需要忽略一行的pyright 检查 有什么特别的评论吗 def create slog group SLogGroup data Optional dict None SLog insert one SLog group group da
  • 测试 python Counter 是否包含在另一个 Counter 中

    如何测试是否是pythonCounter https docs python org 2 library collections html collections Counter is 包含在另一个中使用以下定义 柜台a包含在计数器中b当且
  • 以编程方式停止Python脚本的执行? [复制]

    这个问题在这里已经有答案了 是否可以使用命令在任意行停止执行 python 脚本 Like some code quit quit at this point some more code that s not executed sys e
  • Python pickle:腌制对象不等于源对象

    我认为这是预期的行为 但想检查一下 也许找出原因 因为我所做的研究结果是空白 我有一个函数可以提取数据 创建自定义类的新实例 然后将其附加到列表中 该类仅包含变量 然后 我使用协议 2 作为二进制文件将该列表腌制到文件中 稍后我重新运行脚本
  • 如何加速Python中的N维区间树?

    考虑以下问题 给定一组n间隔和一组m浮点数 对于每个浮点数 确定包含该浮点数的区间子集 这个问题已经通过构建一个解决区间树 https en wikipedia org wiki Interval tree 或称为范围树或线段树 已经针对一
  • BeautifulSoup 中的嵌套标签 - Python

    我在网站和 stackoverflow 上查看了许多示例 但找不到解决我的问题的通用解决方案 我正在处理一个非常混乱的网站 我想抓取一些数据 标记看起来像这样 table tbody tr tr tr td td td table tr t
  • Jupyter Notebook 内核一直很忙

    我已经安装了 anaconda 并且 python 在 Spyder IPython 等中工作正常 但是我无法运行 python 笔记本 内核被创建 它也连接 但它始终显示黑圈忙碌符号 防火墙或防病毒软件没有问题 我尝试过禁用两者 我也无法
  • 向 Altair 图表添加背景实心填充

    I like Altair a lot for making graphs in Python As a tribute I wanted to regenerate the Economist graph s in Mistakes we
  • 对年龄列进行分组/分类

    我有一个数据框说df有一个柱子 Ages gt gt gt df Age 0 22 1 38 2 26 3 35 4 35 5 1 6 54 我想对这个年龄段进行分组并创建一个像这样的新专栏 If age gt 0 age lt 2 the
  • 如何在 Python 中追加到 JSON 文件?

    我有一个 JSON 文件 其中包含 67790 1 kwh 319 4 现在我创建一个字典a dict我需要将其附加到 JSON 文件中 我尝试了这段代码 with open DATA FILENAME a as f json obj js
  • 解释 Python 中的数字范围

    在 Pylons Web 应用程序中 我需要获取一个字符串 例如 关于如何做到这一点有什么建议吗 我是 Python 新手 我还没有找到任何可以帮助解决此类问题的东西 该列表将是 1 2 3 45 46 48 49 50 51 77 使用
  • Scrapy:如何使用元在方法之间传递项目

    我是 scrapy 和 python 的新手 我试图将 parse quotes 中的项目 item author 传递给下一个解析方法 parse bio 我尝试了 request meta 和 response meta 方法 如 sc
  • 如何解释tf.map_fn的结果?

    看代码 import tensorflow as tf import numpy as np elems tf ones 1 2 3 dtype tf int64 alternates tf map fn lambda x x x x el
  • 在 Qt 中自动调整标签文本大小 - 奇怪的行为

    在 Qt 中 我有一个复合小部件 它由排列在 QBoxLayouts 内的多个 QLabels 组成 当小部件调整大小时 我希望标签文本缩放以填充标签区域 并且我已经在 resizeEvent 中实现了文本大小的调整 这可行 但似乎发生了某
  • 导入错误:没有名为 site 的模块 - mac

    我已经有这个问题几个月了 每次我想获取一个新的 python 包并使用它时 我都会在终端中收到此错误 ImportError No module named site 我不知道为什么会出现这个错误 实际上 我无法使用任何新软件包 因为每次我
  • 如何使用 Pycharm 安装 tkinter? [复制]

    这个问题在这里已经有答案了 I used sudo apt get install python3 6 tk而且效果很好 如果我在终端中打开 python Tkinter 就可以工作 但我无法将其安装在我的 Pycharm 项目上 pip
  • 如何将输入读取为数字?

    这个问题的答案是社区努力 help privileges edit community wiki 编辑现有答案以改进这篇文章 目前不接受新的答案或互动 Why are x and y下面的代码中使用字符串而不是整数 注意 在Python 2
  • NotImplementedError:无法将符号张量 (lstm_2/strided_slice:0) 转换为 numpy 数组。时间

    张量流版本 2 3 1 numpy 版本 1 20 在代码下面 define model model Sequential model add LSTM 50 activation relu input shape n steps n fe
  • Statsmodels.formula.api OLS不显示截距的统计值

    我正在运行以下源代码 import statsmodels formula api as sm Add one column of ones for the intercept term X np append arr np ones 50

随机推荐