使用TensorFlow构建三层神经网络拟合曲线

本文将使用 Python 和 TensorFlow 构建一个简单的神经网络,目标是拟合函数 y=x^3+1。

代码实现

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt

# 创建神经网络层
def layer(input, in_size, out_size, activation_function=None):
    '''
    input: 数据输入
    in_size: 输入大小
    out_size: 输出大小
    activation_function: 激活函数(默认没有)
    output:数据输出
    '''
    Weight = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    W_mul_x_plus_b = tf.matmul(input, Weight) + biases
    # 根据是否有激活函数
    if activation_function == None:
        output = W_mul_x_plus_b
    else:
        output = activation_function(W_mul_x_plus_b)
    return output


# 创建训练数据
x_data = np.linspace(-2, 2, 800)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.power(x_data, 3) + 1 + noise

# 定义输入数据的占位符
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])

# 定义神经网络结构
hidden_layer1 = layer(xs, 1, 10, activation_function=tf.nn.relu)  # 隐藏层
prediction = layer(hidden_layer1, 10, 1, activation_function=None)  # 输出层

# 定义损失函数和训练方法
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

# 绘制初始图形
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
plt.ion()
plt.show()

# 初始化变量
init = tf.global_variables_initializer()

# 训练模型
with tf.Session() as sess:
    sess.run(init)
    for i in range(5000):
        sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
        if i % 100 == 0:
            try:
                ax.lines.remove(lines[0])
            except Exception:
                pass
            print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
            prediction_value = sess.run(prediction, feed_dict={xs: x_data})
            lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
            plt.pause(0.1)

print('finish!')
plt.pause(300)

代码详解

  1. 导入库: 导入 tensorflow.compat.v1numpymatplotlib.pyplot
  2. 创建神经网络层: layer 函数用于创建神经网络层,包括权重初始化、偏置设置和激活函数选择。
  3. 创建训练数据: 使用 numpy 生成输入数据 x_data 和带有噪声的输出数据 y_data
  4. 定义占位符: 使用 tf.placeholder 创建占位符,用于接收训练数据。
  5. 定义神经网络结构: 创建一个隐藏层 hidden_layer1 和一个输出层 prediction,并指定激活函数。
  6. 定义损失函数和训练方法: 使用均方误差作为损失函数,并使用梯度下降优化器进行训练。
  7. 绘制初始图形: 使用 matplotlib.pyplot 绘制训练数据的散点图。
  8. 初始化变量: 使用 tf.global_variables_initializer() 初始化所有变量。
  9. 训练模型: 在 tf.Session() 中运行训练过程,迭代训练模型并实时更新拟合曲线。
  10. 显示结果: 训练结束后,输出 'finish!' 并暂停程序,以便观察最终的拟合曲线。

总结

本文介绍了如何使用 TensorFlow 构建一个简单的神经网络来拟合曲线。通过调整神经网络的结构、激活函数、损失函数和优化器等参数,可以进一步提高模型的拟合能力。

Python TensorFlow入门:构建三层神经网络拟合曲线

原文地址: https://www.cveoy.top/t/topic/bIJ1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录