# encoding:utf-8
# 使用TensorFlow构建三层神经网络

# 导入必要的库
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 is 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) 

这段代码演示了如何使用TensorFlow构建一个简单的三层神经网络,并通过拟合函数y=x^3+1来学习神经网络的基本原理和训练过程。

代码解释:

  1. 导入库: 导入必要的库,包括TensorFlow、NumPy和Matplotlib。
  2. 创建神经网络层函数: 定义一个函数layer,用于创建神经网络层,包括权重初始化、激活函数应用等操作。
  3. 生成训练数据: 使用NumPy生成x和y的训练数据,并添加一些噪声以模拟真实数据。
  4. 定义占位符: 创建占位符xsys,用于在训练时传入输入数据和对应的输出数据。
  5. 创建神经网络: 使用layer函数创建三层神经网络,包括一个隐藏层和一个输出层。
  6. 定义损失函数和训练过程: 使用均方误差作为损失函数,并使用梯度下降优化器来最小化损失函数。
  7. 创建图形窗口: 使用Matplotlib创建一个图形窗口,用于实时绘制训练过程中的拟合曲线。
  8. 初始化变量: 初始化所有变量。
  9. 训练神经网络: 在一个会话中运行训练过程,迭代训练模型并定期打印损失函数的值和绘制拟合曲线。

通过运行这段代码,你可以观察到神经网络在训练过程中逐渐拟合目标函数的过程,并最终得到一个能够较好地预测新数据的模型。

Python TensorFlow教程:构建三层神经网络拟合曲线

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

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