蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行各层并逐个核对形状和值

PYTHONWindows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。inspect-keras-layers.py
inspect-keras-layers.py99 行
"""Execute representative Keras layers and check their real shapes and values."""
import json
import platform
from pathlib import Path
import numpy as np
import tensorflow as tf
from tensorflow import keras


def emit(cases):
    print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,keras=keras.__version__,
        system=platform.system(),devices=[d.name for d in tf.config.list_physical_devices()],cases=cases)))


def observed(cases,name,operation,inputs,expected,actual,measurement=None):
    assert expected==actual,(name,expected,actual)
    row=dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True)
    if measurement is not None:
        row["measurements"]=measurement
    cases.append(row)


def main():
    cases=[]
    keras.utils.set_random_seed(183)
    sample=tf.reshape(tf.range(1,13,dtype=tf.float32),(2,2,3))
    dense=keras.layers.Dense(2,use_bias=False,activation="relu",kernel_initializer="ones")
    actual=dense(sample)
    observed(cases,"dense_uses_last_axis","apply the same two-unit dense map across the last dimension",
        {"input_shape":[2,2,3]},[[2,2,2],[6.,6.],1],
        [list(actual.shape),actual[0,0].numpy().tolist(),len(dense.weights)])

    image=tf.reshape(tf.range(25,dtype=tf.float32),(1,5,5,1))
    first=keras.layers.Conv2D(2,(3,3),activation="relu",padding="valid",use_bias=False,kernel_initializer="ones")
    next_=keras.layers.Conv2D(2,3,strides=(2,2),padding="same",use_bias=False,kernel_initializer="ones")
    p,q=first(image),next_(image)
    observed(cases,"convolution_shapes","run fixed weights with real valid and same stride branches",
         {"input":[1,5,5,1]},[[1,3,3,2],[1,3,3,2],54.],
         [list(p.shape),list(q.shape),float(p[0,0,0,0])])

    rnn=tf.ones([2,5,3])
    single=keras.layers.LSTM(4)
    full=keras.layers.LSTM(4,return_sequences=True)
    observed(cases,"return_sequences_controls_rank","compare a final state and all time steps",
        {"timesteps":5,"units":4},[[2,4],[2,5,4]],
        [list(single(rnn).shape),list(full(rnn).shape)])
    drop_lstm=keras.layers.LSTM(4,dropout=.2,recurrent_dropout=.3,seed=22)
    out=drop_lstm(rnn,training=True)
    observed(cases,"both_lstm_dropout_options","exercise input and recurrent dropout with the CPU LSTM",
        {"dropout":.2,"recurrent_dropout":.3},[.2,.3,[2,4],True],
        [drop_lstm.dropout,drop_lstm.recurrent_dropout,list(out.shape),bool(tf.reduce_all(tf.math.is_finite(out)))])

    x=tf.ones((4,3,128))
    drop=keras.layers.Dropout(.5,noise_shape=(4,1,128),seed=139)
    dropped=drop(x,training=True).numpy()
    test=drop(x,training=False).numpy()
    observed(cases,"dropout_mask_and_inference","broadcast dropout masks along time and compare inference",
        {"rate":.5,"shape":[4,3,128],"noise_shape":[4,1,128]},
        [[0.,2.],True,True],[np.unique(dropped).tolist(),bool(np.all(dropped[:,0]==dropped[:,1])),bool(np.all(test==1))])
    drop2=keras.layers.Dropout(.5,noise_shape=(4,1,128),seed=139)
    observed(cases,"seed_reproducibility","compare the first training draw of two separately seeded layers",
        {"seed":139},True,bool(np.array_equal(drop2(x,training=True).numpy(),dropped)))

    batch=tf.constant([[0.],[2.],[4.],[6.]])
    norm=keras.layers.BatchNormalization(momentum=.5)
    train=norm(batch,training=True)
    mean=float(norm.moving_mean[0])
    infer=norm(batch,training=False)
    observed(cases,"normalization_training_state","confirm the moving mean and distinguish train from inference",
        batch.numpy().tolist(),[1.5,True,True],
        [mean,abs(float(tf.reduce_mean(train)))<1e-6,abs(float(tf.reduce_mean(infer)))>.1])

    tile=tf.reshape(tf.range(1,17,dtype=tf.float32),(1,4,4,1))
    pooled=keras.layers.MaxPooling2D((2,2))(tile)
    observed(cases,"max_pool_window","read all four two-by-two window maxima",
        {"shape":[1,4,4,1]},[[6.,8.],[14.,16.]],pooled.numpy()[0,:,:,0].tolist())
    flat=keras.layers.Flatten()(tf.repeat(tile,2,axis=0))
    observed(cases,"flatten_keeps_batch","collapse spatial dimensions independently for each row",
        {"shape":[2,4,4,1]},[[2,16],16.],[list(flat.shape),float(flat[1,-1])])

    emb=keras.layers.Embedding(3,2,embeddings_initializer=keras.initializers.Constant([[0.,1.],[2.,3.],[4.,5.]]))
    ids=tf.constant([[0,2,1]])
    embeddings=emb(ids)
    observed(cases,"embedding_gathers_valid_rows","look up indices including zero",
        ids.numpy().tolist(),[[[0.,1.],[4.,5.],[2.,3.]]],embeddings.numpy().tolist())

    net=keras.Sequential([keras.Input((28,28,1)),keras.layers.Conv2D(4,3,activation="relu"),keras.layers.MaxPooling2D(),
        keras.layers.Conv2D(6,3,activation="relu"),keras.layers.MaxPooling2D(),keras.layers.Flatten(),
        keras.layers.Dense(8,activation="relu"),keras.layers.Dropout(.4),keras.layers.Dense(10,activation="softmax")])
    values=net(tf.ones((2,28,28,1)),training=False).numpy()
    observed(cases,"compose_convolutional_model","evaluate the layered classifier with explicit spatial and class axes",
        {"shape":[2,28,28,1]},[[2,10],True],[list(values.shape),bool(np.allclose(values.sum(axis=-1),1))])
    emit(cases)


if __name__=="__main__":
    main()

本例需在 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

入口文件:projects/tensorflow-keras-layer-lab/inspect-keras-layers.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 inspect-keras-layers.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a370.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习