3 使用class类搭建神经网络结构(鸢尾花分类)

学习使用类封装神经网络层

import tensorflow as tf
from tensorflow.keras.models import  Model
from tensorflow.keras.layers import  Dense
from sklearn.datasets import load_iris
import numpy as np
import matplotlib.pyplot as plt

# 使用class类封装一个神经网络结构
class MyModel(Model):
    '''
    __init__()  :定义所需的网络结构块
    call()      : 写出前向传播
    '''
    def __init__(self):
        super(MyModel, self).__init__()
        self.d1 = Dense(units=3,activation='softmax',kernel_regularizer=tf.keras.regularizers.l1())
    def call(self, x):
        y = self.d1(x)
        return y


# 加载数据集
iris_data = load_iris()
x_data = iris_data['data']
y_data = iris_data['target']

# 打乱数据
np.random.seed(1)
np.random.shuffle(x_data)
np.random.seed(1)
np.random.shuffle(y_data)
tf.random.set_seed(1)

model = MyModel()
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.1),loss = tf.keras.losses.SparseCategoricalCrossentropy(),
              metrics=['sparse_categorical_accuracy'])
history = model.fit(x_data,y_data,batch_size=32,epochs=500,validation_split=0.2,validation_freq=20)
model.summary()

plt.plot(history.history['loss'],'r')
plt.plot(history.history['sparse_categorical_accuracy'],'g')

plt.legend(['loss','sparse_categorical_accuracy'])

plt.show()


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