# softmax 将实数值转换为概率值
# 使用Keras接口如何操作
# import 导入模块,每次使用模块中的函数都要是定是哪个模块。
# from…import * 导入模块,每次使用模块中的函数,直接使用函数就可以了;
# 注因为已经知道该函数是那个模块中的了。
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers ,Sequential
tf.__version__
1 自定义网络层类
class MyDense(tf.keras.layers.Layer):
def __init__(self,units):
super().__init__()
self.units = units
def build(self,input_shape):
# 60000,784
self.w = self.add_variable(name='w',
shape=[input_shape[-1],self.units],
initializer = tf.initializers.RandomNormal())
self.b = self.add_variable(name='b',
shape = [self.units],
initializer = tf.initializers.Zeros())
def call(self,inputs):
# w*x +b
# w [input_shape[-1],units]
# x[60000,784]
return inputs @ self.w + self.b
class MyDense_relu(tf.keras.layers.Layer):
def __init__(self,units):
super().__init__()
self.units = units
def build(self,input_shape):
# 60000,784
self.w = self.add_variable(name='w',
shape=[input_shape[-1],self.units],
initializer = tf.initializers.RandomNormal())
self.b = self.add_variable(name='b',
shape = [self.units],
initializer = tf.initializers.Zeros())
def call(self,inputs):
# w*x +b
# w [input_shape[-1],units]
# x[60000,784]
return tf.nn.relu(inputs @ self.w + self.b )
class MyDense_softmax(tf.keras.layers.Layer):
def __init__(self,units):
super().__init__()
self.units = units
def build(self,input_shape):
# 60000,784
self.w = self.add_variable(name='w',
shape=[input_shape[-1],self.units],
initializer = tf.initializers.RandomNormal())
self.b = self.add_variable(name='b',
shape = [self.units],
initializer = tf.initializers.Zeros())
def call(self,inputs):
# w*x +b
# w [input_shape[-1],units]
# x[60000,784]
return tf.nn.softmax(inputs @ self.w + self.b )
2 自定义模型类
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.fc1 = MyDense_relu(512)
self.fc2 = MyDense_relu(256)
self.fc3 = MyDense_relu(128)
self.fc4 = MyDense_softmax(10)
def call(self,inputs):
fc1_out = self.fc1(inputs)
fc2_out = self.fc2(fc1_out)
fc3_out = self.fc3(fc2_out)
fc4_out = self.fc4(fc3_out)
return fc4_out
转载自https://blog.csdn.net/jiayoudangdang/article/details/111500103