tensorflow中使用class构建神经网络的网络结构块
class用来声明网络结构
class MyModel(Model): #MyModel表示声明神经网络的名字
def __init__(self):
super(MyModel, self).__init__() #初始化父类的参数
//初始化网络结构,构建神经网络所需的各种网络结构块
def call(self, x): #call()方法调用__init__()方法中完成初始化的网络结构块
y = self.d1(x) #使用网络结构块
return y
代码演示:
#第一步,import import tensorflow as tf #导入模块 from sklearn import datasets #从sklearn中导入数据集 import numpy as np #导入科学计算模块 from tensorflow.keras.layers import Dense from tensorflow.keras import Model #第二步,train, test x_train = datasets.load_iris().data #导入iris数据集的输入 y_train = datasets.load_iris().target #导入iris数据集的标签 np.random.seed(120) #设置随机种子,让每次结果都一样,方便对照 np.random.shuffle(x_train) #使用shuffle()方法,让输入x_train乱序 np.random.seed(120) #设置随机种子,让每次结果都一样,方便对照 np.random.shuffle(y_train) #使用shuffle()方法,让输入y_train乱序 tf.random.set_seed(120) #让tensorflow中的种子数设置为120 # #第三步,models.Sequential() # model = tf.keras.models.Sequential([ #使用models.Sequential()来搭建神经网络 # tf.keras.layers.Dense(3, activation = "softmax", kernel_regularizer = tf.keras.regularizers.l2()) #全连接层,三个神经元,激活函数为softmax,使用l2正则化 # ]) class irisModel(Model): def __init__(self): super(irisModel, self).__init__() self.d1 = Dense(3, activation="softmax", kernel_regularizer=tf.keras.regularizers.l2()) #搭建网络块,这一层命名为d1 def call(self, x): y = self.d1(x) #实现前向传播 return y model = irisModel() #第四步,model.compile() model.compile( #使用model.compile()方法来配置训练方法 optimizer = tf.keras.optimizers.SGD(lr = 0.1), #使用SGD优化器,学习率为0.1 loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits = False), #配置损失函数 metrics = ['sparse_categorical_accuracy'] #标注网络评价指标 ) #第五步,model.fit() model.fit( #使用model.fit()方法来执行训练过程, x_train, y_train, #告知训练集的输入以及标签, batch_size = 32, #每一批batch的大小为32, epochs = 500, #迭代次数epochs为500 validation_split = 0.2, #从数据集中划分20%给测试集 validation_freq = 20 #测试的间隔次数为20,每迭代20次测试一次准确率 ) #第六步,model.summary() model.summary() #打印神经网络结构,统计参数数目
结果为:
E:\Anaconda3\envs\TF2\python.exe C:/Users/Administrator/PycharmProjects/untitled8/keras实现iris数据集.py
Train on 120 samples, validate on 30 samples
Epoch 1/50032/120 [=======>......................] - ETA: 2s - loss: 5.2685 - sparse_categorical_accuracy: 0.4375
120/120 [==============================] - 1s 7ms/sample - loss: 2.7204 - sparse_categorical_accuracy: 0.4833
Epoch 2/50032/120 [=======>......................] - ETA: 0s - loss: 0.8763 - sparse_categorical_accuracy: 0.6875
120/120 [==============================] - 0s 67us/sample - loss: 0.8910 - sparse_categorical_accuracy: 0.6500
Epoch 3/50032/120 [=======>......................] - ETA: 0s - loss: 1.0462 - sparse_categorical_accuracy: 0.5000
120/120 [==============================] - 0s 67us/sample - loss: 1.0107 - sparse_categorical_accuracy: 0.6167
Epoch 4/500省略.....
32/120 [=======>......................] - ETA: 0s - loss: 0.3444 - sparse_categorical_accuracy: 0.9375
120/120 [==============================] - 0s 58us/sample - loss: 0.3559 - sparse_categorical_accuracy: 0.9333
Epoch 500/50032/120 [=======>......................] - ETA: 0s - loss: 0.3086 - sparse_categorical_accuracy: 0.9688
120/120 [==============================] - 0s 158us/sample - loss: 0.3302 - sparse_categorical_accuracy: 0.9833 - val_loss: 0.3695 - val_sparse_categorical_accuracy: 0.9333
Model: "iris_model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) multiple 15
=================================================================
Total params: 15
Trainable params: 15
Non-trainable params: 0
_________________________________________________________________Process finished with exit code 0