1. Using TensorBoard's text classification model
import keras
from keras import layers
from keras.datasets import imdb
from keras.preprocessing import sequence
max_features = 2000 #作为特征的单词个数
max_len = 500 #在这么多单词之后截断文本
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
x_train = sequence.pad_sequences(x_train, maxlen=max_len)
print(x_train.shape) #(25000, 500)
x_test = sequence.pad_sequences(x_test, maxlen=max_len)
print(x_test.shape)
(25000, 500)
(25000, 500)
model = keras.models.Sequential()
model.add(layers.Embedding(max_features, 128, input_length=max_len, name='embed'))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.MaxPooling1D(5))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(1))
model.summary()
#由于电脑内存过小,无法写入25000行的数据,因此取前1000行
print(x_train[:1000].shape) #(1000, 500)
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
2. Before using TensorBoard, you first need to create a directory to save the generated log files, which can be created manually or using terminal commands.
$ mkdir my_log_dir
3. Use a TensorBoard callback function to train the model
callbacks = [
keras.callbacks.TensorBoard(
log_dir='my_log_dir', #将日志写入这个位置
histogram_freq=1, #每一轮之后记录激活的直方图
embeddings_freq=1, #每一轮之后记录嵌入数据
embeddings_data=x_train[:1000].astype('float32') #指定embeddings_data的值
)
]
history = model.fit(x_train, y_train,
epochs=20,
batch_size=128,
validation_split=0.2,
callbacks=callbacks
)
4. Start the TensorBoard server on the command line cmd , instructing it to read the log currently being written by the callback function
tensorboard --logdir "D:\Deep Learning with Python\Code\my_log_dir"
Open the given localhost address in the browser, you can view:
5. Use the keras.utils.plot_model function to draw the model as a graph composed of layers
Note that Keras also provides another more concise method - the keras.utils.plot_model function, which can draw the model as a graph composed of layers instead of a graph composed of Tensorflow operations. To use this function, you need to install Python's pydot library and pydot-ng library, and you also need to install the graphviz library. (Installation tutorial: keras visualization pydot and graphviz installation )
Let's take a quick look:
from keras.utils import plot_model
plot_model(model,to_file='model.png')
from keras.utils import plot_model
plot_model(model,show_shapes=True,to_file='model.png')
2021-11-23 Tues. 15:50 p.m.