本篇blog介绍了tensorflow2.0的三种建模方式。
初学者建议前两种,学到后期强烈建议后一种,可以高度自定义。
顺序模型Sequential model
tf.keras.Sequential
就像搭积木一样,一层一层往上搭建。
第一种搭积木方式:
from tensorflow.keras import layers
import tensorflow as tf
model = tf.keras.Sequential()
model.add(layers.Dense(64, activation='relu'))#第一层
model.add(layers.Dense(64, activation='relu'))#第二层
model.add(layers.Dense(10))#第三层
#。。。未完待续
还有另外一种
model = tf.keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(32,)),#第一层
layers.Dense(64, activation='relu'),#第二层
layers.Dense(10)#第三层
#。。。。。全连接层
])
搭建好之后开始训练模型,定义损失函数,定义优化器,定义评估函数(可以不定义)。
model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
import numpy as np
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.fit(data, labels, epochs=10, batch_size=32)#开始训练model.fit()
Train on 1000 samples
Epoch 1/10
WARNING:tensorflow:Entity <function Function._initialize_uninitialized_variables.<locals>.initialize_variables at 0x000002CA715BB168> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: No module named 'tensorflow_core.estimator'
WARNING: Entity <function Function._initialize_uninitialized_variables.<locals>.initialize_variables at 0x000002CA715BB168> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: No module nam