Kears中的可视化

1.使用 keras 中的Tensorboard实现可视化

注意:

np.array ( ), 如果要使用数组的话,必须要用 【】

1.对 .shape 的理解:从 第一个大括号 看最里面有多少层,从里往外看。

import numpy as np

a=np.array([[1,2,3],[4,5,6]])
print(a.shape)
print(a)

b=np.array([1,2,3])
print(b.shape)

输出是:
(2, 3)
[[1 2 3]
 [4 5 6]]
(3,)

2.对 np.expand_dims(a,axis=0) 的理解

代码:

a=np.array([[1,2,3],[4,5,6]])
print(a.shape)
print(a)

print("*************************")

b=np.expand_dims(a,axis=0)
print(b.shape)
print(b)

print("*********************")

b=np.expand_dims(a,axis=1)
print(b.shape)
print(b)

结果如下图:
在这里插入图片描述
3.对Flatten层的理解:

Flatten层用来将输入“压平”,即把多维的输入一维化,常用在从卷积层到全连接层的过渡。Flatten不影响batch的大小。
在这里插入图片描述
在pycharm中如何用 tensorboard 可视化:

tensorboard可视化

2.代码:

import numpy as np

from keras.layers import Input, Dense, Dropout, Activation,Conv2D,MaxPool2D,Flatten

#Flatten 用来输入“压平”,把多维的输入一维化,常用在从卷积层到全连接层的过度,Flatten不影响batch大小。

from keras.datasets import mnist
from keras.models import Model
from keras.utils import to_categorical

#可以查看模型的损失函数和准确率
#一般acc是用在分类问题上,目标检测问题上一般只使用loss
from keras.callbacks import TensorBoard  #在回掉库里导入 Tensorboard


if __name__=="__main__":
    (x_train,y_train),(x_test,y_test) = mnist.load_data()

    x_train=np.expand_dims(x_train,axis=-1)
    x_test=np.expand_dims(x_test,axis=-1)
    y_train=to_categorical(y_train,num_classes=10)
    y_test=to_categorical(y_test,num_classes=10)
    batch_size=128
    epochs=10

    inputs = Input([28,28,1])
    x = Conv2D(32, (5,5), activation='relu')(inputs)
    x = Conv2D(64, (5,5), activation='relu')(x)
    x = MaxPool2D(pool_size=(2,2))(x)
    x = Flatten()(x)
    x = Dense(128, activation='relu')(x)
    x = Dropout(0.5)(x)
    x = Dense(10, activation='softmax')(x)

    model = Model(inputs,x)

    model.compile(loss='categorical_crossentropy', optimizer="adam",metrics=['acc'])
    Tensorboard= TensorBoard(#tensorboard是在这里创建的。
        log_dir="./TensorboardModel",  #模型中日志文件保存的位置
        #如果只要获得acc和loss 可以直接把后边的 改成=0, =flase 即可
        histogram_freq=1,              #对于模型中 各个层计算激活函数的值和模型权重直方图频率。
        write_grads=True    #是否进行可视化图像
    )
    history=model.fit(x_train, y_train, batch_size=batch_size,
                      epochs=epochs, shuffle=True, validation_split=0.2,callbacks=[Tensorboard])

最后可以运用命令行,查看最后生成的日志文件,能可视化损失函数和精度。具体我也没调出来,用的时候再调吧。

参考链接:
b站bubbliiing

posted @ 2020-08-15 15:50  沧海一声笑rush  阅读(49)  评论(0编辑  收藏  举报