代码

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from datetime import datetime
from packaging import version

import tensorflow as tf 
from tensorflow import keras

import numpy  as np 
import matplotlib.pyplot as plt 


print("Tensorflow version:", tf.__version__)
assert(version.parse(tf.__version__).release[0] >=2)


def realModel():
    x_data = np.linspace(-1, 1, 1000)
    # np.random.shuffle(x)
    # Generate the output data.
    # y_data = 0.5x_data + 2 + noise
    y_data = 0.5 * x_data + 2 + np.random.normal(0, 0.05, 1000)
    return x_data, y_data

# 模型
def realModel2():
    x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
    noise = np.random.normal(0, 0.05, x_data.shape)
    y_data = np.power(x_data, 3) + np.square(x_data) - 0.05 + noise
    return x_data, y_data



# 建模
def buildModel():
    model = keras.models.Sequential([
        keras.layers.Dense(16, input_dim=1),
        keras.layers.Dense(1)
    ])

    model.compile(
        loss='mse',
        optimizer=keras.optimizers.SGD(lr=0.2)
    )

    return model

# 建模
def buildModel2():
    model = tf.keras.Sequential([
        tf.keras.layers.Flatten(input_shape=(1,)),  # 将输入的维度压缩成一个维度
        tf.keras.layers.Dense(30, activation='relu'),   # 1个隐藏层,10个units,激活函数为relu(实现非线性变换是因为relu能把小于0部分消掉,实现矩阵的稀疏性)
        # tf.keras.layers.Dense(10, activation='relu'),  #这里我屏蔽了,有需要可以自己加层数
        tf.keras.layers.Dropout(0.2),   # 随机丢弃0.2,防止过拟合
        tf.keras.layers.Dense(1)
    ])

    optimizer = tf.keras.optimizers.Adam(0.001)  
    model.compile(optimizer=optimizer, loss="mse")

    return model


if __name__ == "__main__":
    # x_train, y_train= realModel()
    x_train, y_train= realModel2()
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x_train, y_train)
    plt.ion()
    plt.show()
    
    # model = buildModel()
    model = buildModel2()

    logdir = "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S")
    tensorboard_callbacks = keras.callbacks.TensorBoard(
        log_dir=logdir,
        histogram_freq=True,
        write_graph=True,
        write_grads=True
    )


    for i in range(100):
        model.fit(
            x_train,
            y_train,
            batch_size=150,
            version=0,
            epochs=5,
            callbacks=[tensorboard_callbacks]
        )

        if i % 2 == 0:
            y_pred = model.predict(x_train)
            try:
                # 移除上一条曲线
                ax.lines.remove(lines[0])
            except Exception:
                pass
            lines = ax.plot(x_train, y_pred)
            plt.pause(1)

    plt.pause(0)
    model.save(logdir)

训练动态图

train.gif

启动 tensorboard

tensorboard --logdir logs\scalars

浏览器打开: http://localhost:6006/

image.png

image.png

image.png

image.png


zeroyl
156 声望2 粉丝

引用和评论

0 条评论