6 自定义层

自定义的层名不要与自带的层重名

from sklearn import datasets
import tensorflow as tf
import numpy as np

iris = datasets.load_iris()
data = iris.data
labels = iris.target

# 定义一个全连接层
class MyDense(tf.keras.layers.Layer):
    def __init__(self, units=32, **kwargs):
        self.units = units
        super(MyDense, self).__init__(**kwargs)
    
    # build方法一般定义Layer需要被训练的参数
    # trainable=True 参与训练 False 不参与训练
    # name需要命名,不然模型保存会出现错误
    def build(self, input_shape): 
        self.w = self.add_weight(shape=(input_shape[-1], self.units),
                                 initializer='random_normal',
                                 trainable=True,
                                 name='w')
        self.b = self.add_weight(shape=(self.units,),
                                 initializer='random_normal',
                                 trainable=True,
                                 name='b')
        super(MyDense,self).build(input_shape) # 相当于设置self.built = True
    
    #call方法一般定义正向传播运算逻辑,__call__方法调用了它。    
    def call(self, inputs): 
        return tf.matmul(inputs, self.w) + self.b
    
    #如果要让自定义的Layer通过Functional API 组合成模型时可以序列化,需要自定义get_config方法。
    # 不定义不能保存模型
    def get_config(self):  
        config = super(MyDense, self).get_config()
        config.update({'units': self.units})
        return config


# 函数式编程
inputs = tf.keras.Input(shape=(4,))
x = MyDense(units=16)(inputs) # 神经元个数设置为16
x = tf.nn.tanh(x) # 全连接层后接一个激活函数
x = tf.keras.layers.Dense(8)(x)
x = tf.nn.relu(x)
x = MyDense(units=3)(x) #三分类
predictions = tf.nn.softmax(x)
model = tf.keras.Model(inputs=inputs, outputs=predictions)

# 打乱
data = np.concatenate((data,labels.reshape(150,1)),axis=-1)
np.random.shuffle(data)

labels = data[:,-1]
data = data[:,:4]

#优化器 Adam
#损失函数 交叉熵损失函数
#评估函数 #acc
model.compile(optimizer=tf.keras.optimizers.Adam(),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])

# 训练
model.fit(data, labels, batch_size=32, epochs=100,shuffle=True)

显示网络结构

model.summary()

保存模型

model.save('keras_model_tf_version.h5')

加载模型预测

# 加载模型之前要把自定义层名称添加到字典里
# 需要把MyDense的网络写出来才能定义
_custom_objects = {
    "MyDense" : MyDense
}

new_model = tf.keras.models.load_model("keras_model_tf_version.h5",custom_objects=_custom_objects)

y_pred = new_model.predict(data)
np.argmax(y_pred,axis=1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值