神经网络曲线拟合

通过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()

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明德zhuang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值