tensorflow07——使用tf.keras中的Sequential搭建神经网络——六步法——鸢尾花数据集分类

使用tf.keras中的Sequential搭建神经网络
六步法——鸢尾花数据集分类

01 导入相关包
02 导入数据集,打乱顺序
03 建立Sequential模型
04 编译——确定优化器,损失函数,评测指标(用哪一种准确率)
05 训练模型——把各项参入填入模型
06 总结——打印网络结构


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

# 02
x_train = datasets.load_iris().data
y_train = datasets.load_iris().target
# 测试集可以在此处按照上述方法划分
# 本案例把测试集放到训练过程fit中,按照比例直接从训练集中划分(validation_split)

# 乱序步骤
np.random.seed(116)
np.random.shuffle(x_train)
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)

# 03
model = tf.keras.models.Sequential([
    # 定义全连接层
    tf.keras.layers.Dense(3,activation='softmax',kernel_regularizer=tf.keras.regularizers.l2())
])

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

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

)

# 06
model.summary()

输出结果

Train on 120 samples, validate on 30 samples
Epoch 1/500
120/120 [==============================] - 0s 3ms/sample - loss: 2.2022 - sparse_categorical_accuracy: 0.3833
Epoch 2/500
120/120 [==============================] - 0s 36us/sample - loss: 1.0013 - sparse_categorical_accuracy: 0.6083
Epoch 3/500
120/120 [==============================] - 0s 36us/sample - loss: 0.8497 - sparse_categorical_accuracy: 0.6333
。
。
此处省略500回合
。
。
。

> Epoch 496/500 120/120 [==============================] - 0s
> 21us/sample - loss: 0.3384 - sparse_categorical_accuracy: 0.9583 Epoch
> 497/500 120/120 [==============================] - 0s 22us/sample -
> loss: 0.3442 - sparse_categorical_accuracy: 0.9750 Epoch 498/500
> 120/120 [==============================] - 0s 22us/sample - loss:
> 0.3394 - sparse_categorical_accuracy: 0.9583 Epoch 499/500 120/120 [==============================] - 0s 21us/sample - loss: 0.3394 -
> sparse_categorical_accuracy: 0.9333 Epoch 500/500 120/120
> [==============================] - 0s 168us/sample - loss: 0.4425 -
> sparse_categorical_accuracy: 0.8583 - val_loss: 0.3130 -
> val_sparse_categorical_accuracy: 0.9667 Model: "sequential"
> _________________________________________________________________ Layer (type)                 Output Shape              Param #   
> ================================================================= dense (Dense)                multiple                  15        
> ================================================================= Total params: 15 Trainable params: 15 Non-trainable params: 0
> _________________________________________________________________

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