神经网络曲线拟合

通过TensorFlow2.4搭建一个简单的神经网络二次曲线拟合。
之前无意间在博客上看到的一个代码,如下:

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

# 生成数据集
x = np.linspace(-1, 1, 100)
y = x ** 2 + np.random.randn(100) * 0.05

# 定义网络架构
model = tf.keras.Sequential([
    tf.keras.layers.Dense(10, input_shape=(1,), activation="elu"),
    tf.keras.layers.Dense(1)
])

# 设置训练参数
model.compile(optimizer="adam", loss="mse")

# 训练并查看训练进度
history = model.fit(x, y, epochs=1000)
y_predict = model.predict(x)

plt.scatter(x, y)
plt.plot(x, y_predict, 'r')
plt.show()

后来自己整理了一下代码,如下:

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf


# 神经网络参数配置
def compile_model(model):
    model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss="mse", metrics=["mae", "mse"])


# 使用keras新建神经网络
def create_model():
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(1,), name="layer1"),
        tf.keras.layers.Dense(1, name="outputs")])
    # 编译模型
    compile_model(model)
    return model


# 生成数据
def gen_datas():
    inputs = np.linspace(-1, 1, 500, dtype=np.float32)[:, np.newaxis]
    outputs = np.square(inputs) + np.random.randn(100) * 0.05
    return inputs, outputs


# 训练神经网络
def train_model(model, inputs, outputs):
    history = model.fit(inputs, outputs, epochs=1000)


# 神经网络预测
def prediction(model, inputs):
    pres = model.predict(inputs)
    return pres


if __name__ == "__main__":
    x = np.linspace(-1, 1, 100)
    y = np.square(x) + np.random.randn(100) * 0.05
    model = create_model()
    train_model(model, x, y)
    y_predict = model.predict(x)
    plt.scatter(x, y)
    plt.plot(x, y_predict, 'r')
    plt.show()

运行结果如下:
请添加图片描述

おすすめ

転載: blog.csdn.net/weixin_44359479/article/details/121003676
おすすめ