文章目录
-
-
- 1.如何自定义层
- 2.三种方法自定义层
-
- 3.自定义层的注意事项
-
- 4.案例讲解
1.如何自定义层
2.三种方法自定义层
方法一
import tensorflow as tf
class Linear(tf.keras.layers.Layer):
def __init__(self, units=1, input_dim=4):
super(Linear, self).__init__()
w_init = tf.random_normal_initializer()
self.w = tf.Variable(initial_value=w_init(shape=(input_dim, units),dtype='float32'), trainable=True)
b_init = tf.zeros_initializer()
self.b = tf.Variable(initial_value=b_init(shape=(units,),dtype='float32'),trainable=True)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
x = tf.constant(data)
linear_layer = Linear(units = 1, input_dim=4)
y = linear_layer(x)
print(y.shape)
方法二
class Linear(tf.keras.layers.Layer):
def __init__(self,units=1,input_dim=4):
super(Linear,self).__init__()
self.w = self.add_weight(shape=(input_dim,units),
initializer = 'random_normal',
trainable = True)
self.b = self.add_weight(shape=(units,),
initializer = 'zeros',
trainable = True)
def call(self,inputs):
return tf.matmul(inputs,self.w) + self.b
x = tf.constant(data)
linear_layer = Linear(units=1,input_dim=4)
y = linear_layer(x)
print(y.shape)
方法三
class Linear(tf.keras.layers.Layer):
def __init__(self,units = 32):
super(Linear,self).__init__()
self.units = units
def build(self,input_shape):
self.w = self.add_weight(shape=(input_shape[-1],self.units),
initializer = 'random_normal',
trainable = True)
self.b = self.add_weight(shape=(self.units,),
initializer = 'random_normal',
trainable = True)
super(Linear,self).build(input_shape)
def call(self,inputs):
return tf.matmul(inputs,self.w) + self.b
x = tf.constant(data)
linear_layer = Linear(units=1)
y = linear_layer(x)
print(y.shape)
添加不可训练参数
class Linear(tf.keras.layers.Layer):
def __init__(self, units=32):
super(Linear, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(shape=(input_shape[-1], self.units),
initializer='random_normal',
trainable=True)
self.b = self.add_weight(shape=(self.units,),
initializer='random_normal',
trainable=False)
super(Linear,self).build(input_shape)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
x = tf.constant(data)
linear_layer = Linear(units = 1)
y = linear_layer(x)
print(y.shape)
3.自定义层的注意事项
注意一
注意二
注意三
注意四
注意五
4.案例讲解
import tensorflow as tf
class MyDense(tf.keras.layers.Layer):
def __init__(self,units=32,**kwargs):
self.units = units
super(MyDense,self).__init__(**kwargs)
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)
def call(self,inputs):
return tf.matmul(inputs,self.w) + self.b
def get_config(self):
config = super(MyDense,self).get_config()
config.update({
'units':self.units})
return config
from sklearn import datasets
iris = datasets.load_iris()
data = iris.data
labels = iris.target
data.shape
labels.shape
import numpy as np
data = np.concatenate((data,labels.reshape(150,1)),axis=-1)
np.random.shuffle(data)
labels = data[:,-1]
data = data[:,:4]
inputs = tf.keras.Input(shape=(4,))
x = MyDense(units=16)(inputs)
x= tf.nn.tanh(x)
x = MyDense(units=3)(x)
predictions = tf.nn.softmax(x)
model = tf.keras.Model(inputs = inputs,outputs=predictions)
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.save('keras_model_tf_version.h5')
_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)