TensorFlow笔记【五】六步法搭建神经网络

一、六步介绍

六步法:
1、import:导入模块
2、train、test:定义训练集、验证集
3、model = tf.keras.models.Sequential(【网络结构】):搭建网络结构,逐层描述网络结构
   网络结构:
        ①拉直层:tf.keras.layers.Flatten() : 形状转换不计算,拉成一维数组
        ②全连接层:tf.keras.layers.Dense(神经元个数,activation="激活函数",kernel_regularizer=正则化)
            activation(字符串):relu,softmax,sigmoid,tanh
            kernel_regularizer: tf.keras.regularizers.l1()、tf.keras.regularizers.l2()
        ③卷积层:tf.keras.layers.Conv2D(filter=卷积核个数,kernel_size=卷积核尺寸,strides=卷积步长,padding="valid" or "same")
        ④LSTM层[循环神经网络层]:tf.keras.layers.LSTM()
4、model.compile:配置训练方法,配置选择的优化器、损失函数、评测指标
    model.compile(optimizer=优化器,loss=损失函数,metrics=["准确率"])
            optimizer:sgd、adadelta、adam、mse、sparse_categorical_crossentropy
            loss:mse、sparse_categorical_crossentropy | tf.keras.losses.SparseCategoricalCrossentropy(from_logits=Flase)
            metrics:accuracy、categorical_accuracy、sparse_categorical_accuracy
5、model.fit: 执行训练过程,特征标签、batch、epoch
        model.fit(训练集的输入特征,训练集的标签,
                  batch_size=,epochs=,
                  validation_data=(测试集的输入特征,测试集的标签),
                  validation_split=从训练集中划分多少比例作为测试集,
                  validation_freq=多少次epocj测试一次)
6、model.summary : 打印网络结构和参数统计

二、六步实现iris

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

x_train = datasets.load_iris().data
y_train = datasets.load_iris().target

np.random.seed(116)
np.random.shuffle(x_train)
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(3, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2())
])

model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.1),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy']
              )

model.fit(x_train,y_train,batch_size=32,epochs=500,validation_split=0.2,validation_freq=20)
model.summary()

三、class封装

import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras import Model
from sklearn import datasets
import numpy as np

x_train = datasets.load_iris().data
y_train = datasets.load_iris().target

np.random.seed(116)
np.random.shuffle(x_train)
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)

# 封装为类
class Iris(Model):
    def __init__(self):
        super(Iris,self).__init__()
        self.d1 = Dense(3,activation='softmax',kernel_regularizer=tf.keras.regularizers.l2())

    def call(self,x):
        y = self.d1(x)
        return y

#初始化模型参数
model = Iris()
model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.1),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])
#定义训练效果
model.fit(x_train,y_train,batch_size=32,epochs=500,validation_split=0.2,validation_freq=20

你可能感兴趣的:(深度学习,tensorflow,神经网络,深度学习)