tensorflow2.0 单输入 通过不同的神经元 多输出

一,前言

有这么个需求,输入一张图,返回多个特征。比如输入一个数字,返回他的数字意义和字符颜色。这两个特征可以使用不同的训练参数。

二 ,代码部分

代码。线性。适合获取操作值, 比如弄个赛车游戏,给一张图像训练他的油门值和左右值。
import tensorflow as tf
import numpy as np
import scipy as sp
# import skimage as io
# import matplotlib as plt

#获取训练数据
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#训练数据归一化
x_train, x_test = x_train / 255.0, x_test / 255.0

class multipleOutputNet(object):
    @staticmethod #第一个特征的网络结构
    def netOne(input, numCategories, finalAct = "softmax", chanDim=-1):
        h1 = tf.keras.layers.Conv2D(16, 3, padding="same", activation='relu')(input)
        h1 = tf.keras.layers.MaxPool2D(3)(h1)
        h1 = tf.keras.layers.Conv2D(32, 3, activation='relu')(h1)
        h1 = tf.keras.layers.MaxPool2D(3)(h1)
        h1 = tf.keras.layers.Dense(256, activation='relu')(h1)
        h1 = tf.keras.layers.Dropout(0.2)(h1)(h1)
        h1 = tf.keras.layers.Dense(1, activation='tanh')(h1)
        return h1

    @staticmethod #第二个特征的网络结构
    def netTwo(input, numCategories, finalAct="softmax", chanDim=-1):
        h1 = tf.keras.layers.Flatten()(input)
        h1 = tf.keras.layers.Dense(256, activation='relu')(h1)
        h1 = tf.keras.layers.Dropout(0.2)(h1)
        # h1 = tf.keras.layers.Dense(10, activation='softmax')(h1)
        h1 = tf.keras.layers.Dense(1, activation='tanh')(h1)
        return h1

    @staticmethod  #合并两个特征的网络结构
    def buildNet(width, height, chanal, netOneCount, netTwoCount, finalAct = "softmax"):
        #输入图像的形状
        inputShape = (height, width, chanal)
        chanDim = -1
        #定义输入
        input = tf.keras.Input(shape=inputShape)
        #分别建立两个分支
        netOneBranch = multipleOutputNet.netOne(input, netOneCount, finalAct=finalAct, chanDim=chanDim)
        netTwoBranch = multipleOutputNet.netTwo(input, netTwoCount, finalAct=finalAct, chanDim=chanDim)

        #建立模型 ***  合并两个分支
        model = tf.keras.Model(input, [netOneBranch, netTwoBranch])
        return model


#获取模型
model = multipleOutputNet.buildNet(28, 28, 1, netOneCount=1, netTwoCount=1, finalAct="softmax")
#损失函数
losses = (
    'sparse_categorical_crossentropy',
    'sparse_categorical_crossentropy'
)
losses1 = (
    'mean_squared_error',
    'mean_squared_error'
)
lossWeights = (0.1, 0.1)
#优化器
model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.01),
              loss=losses1,
              # loss_weights=lossWeights,
              metrics=['accuracy']
              )
#准备训练数据
x_train = np.reshape(x_train, (60000, 28, 28, 1))
# 把y变一下,当作第二种特征结果

y_train_r = y_train * 0.1
y_train_r1 = y_train * 0.01

#开始训练
model.fit(x_train, (y_train_r, y_train_r1), epochs=50)
model.save('t1.h5')

代码 。非线性。 即适合多分类的。比如给一个水果图像,获取他的品种和颜色
import tensorflow as tf
import numpy as np
import scipy as sp
# import skimage as io
# import matplotlib as plt

#获取训练数据
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#训练数据归一化
x_train, x_test = x_train / 255.0, x_test / 255.0

class multipleOutputNet(object):
    @staticmethod #第一个特征的网络结构
    def netOne(input, numCategories, finalAct = "softmax", chanDim=-1):
        h1 = tf.keras.layers.Conv2D(16, 3, padding="same", activation='relu')(input)
        h1 = tf.keras.layers.MaxPool2D(3)(h1)
        h1 = tf.keras.layers.Conv2D(32, 3, activation='relu')(h1)
        h1 = tf.keras.layers.MaxPool2D(3)(h1)
        h1 = tf.keras.layers.Conv2D(32, 3, activation='relu')(h1)
        h1 = tf.keras.layers.Flatten()(h1)
        h1 = tf.keras.layers.Dense(256, activation='relu')(h1)
        h1 = tf.keras.layers.Dropout(0.2)(h1)
        h1 = tf.keras.layers.Dense(10, activation='softmax')(h1)
        return h1

    @staticmethod #第二个特征的网络结构
    def netTwo(input, numCategories, finalAct="softmax", chanDim=-1):
        h1 = tf.keras.layers.Flatten()(input)
        h1 = tf.keras.layers.Dense(256, activation='relu')(h1)
        h1 = tf.keras.layers.Dropout(0.2)(h1)
        h1 = tf.keras.layers.Dense(10, activation='softmax')(h1)
        return h1

    @staticmethod  #合并两个特征的网络结构
    def buildNet(width, height, chanal, netOneCount, netTwoCount, finalAct = "softmax"):
        #输入图像的形状
        inputShape = (height, width, chanal)
        chanDim = -1
        #定义输入
        input = tf.keras.Input(shape=inputShape)
        #分别建立两个分支
        netOneBranch = multipleOutputNet.netOne(input, netOneCount, finalAct=finalAct, chanDim=chanDim)
        netTwoBranch = multipleOutputNet.netTwo(input, netTwoCount, finalAct=finalAct, chanDim=chanDim)

        #建立模型 ***  合并两个分支
        model = tf.keras.Model(input, [netOneBranch, netTwoBranch])
        return model


#获取模型
model = multipleOutputNet.buildNet(28, 28, 1, netOneCount=10, netTwoCount=10, finalAct="softmax")
#损失函数
losses = (
    'sparse_categorical_crossentropy',
    'sparse_categorical_crossentropy'
)
# losses = {
#     'netOne': 'mean_squared_error',
#     'netTwo': 'mean_squared_error'
# }
lossWeights = (0.1, 0.1)
#优化器
model.compile(optimizer='adam',
              loss=losses,
              # loss_weights=lossWeights,
              metrics=['accuracy']
              )
#准备训练数据
x_train = np.reshape(x_train, (60000, 28, 28, 1))
# 把y变一下,当作第二种特征结果
y_train_r = y_train * 0.1

#开始训练
model.fit(x_train, (y_train, y_train_r), epochs=50)
model.save('t1.h5')

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

千年奇葩

从来没受过打赏,这玩意好吃吗?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值