结果可视化plot_result

本文介绍如何使用TensorFlow 2.5.0实现自定义网络层,通过实例展示了如何添加ReLU激活函数,训练一个简单的线性回归模型,并实时展示预测结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import matplotlib.pyplot as plt
import tensorflow.compat.v1 as tfc
import tensorflow as tf
import numpy as np
# tensorflow 2.5.0

# 添加层函数
def add_layer(inputs, in_size, out_size, activation_function=None):
    Weights = tf.Variable(tf.random.normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases # y = W*x + b
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

x_data = np.linspace(-1,1,300)[:,np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

xs = tfc.placeholder(tf.float32, [None, 1])
ys = tfc.placeholder(tf.float32, [None, 1])

# 建立网络结构
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
prediction = add_layer(l1, 10, 1, activation_function=None)

# 计算loss并拟定训练参数
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), axis=[1]))
train_step = tfc.train.GradientDescentOptimizer(0.1).minimize(loss)   # 学习率0.1

init = tfc.global_variables_initializer()    # 初始化
sess = tfc.Session()
sess.run(init)

fig = plt.figure()            # 建立空白图片框
ax = fig.add_subplot(1,1,1)   # 图片序号
ax.scatter(x_data, y_data)    # 原始数据
plt.ion()   # show了以后用于连续显示
plt.show()

for i in range(1000):
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})    # 训练网络
    if i % 50 == 0:
#         to see the step improvement
#         print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
        try:
            ax.lines.remove(lines[0]) # 抹除上一时刻的线
        except Exception:  # 如果没有线
            pass  # 什么都不做
        prediction_value = sess.run(prediction, feed_dict={xs: x_data, ys: y_data})
        lines = ax.plot(x_data, prediction_value, 'r-', lw=5) # 重画线,红色,宽度5
        plt.pause(0.1) # 刷新的时间间隔0.1s
### 使用 `plot_wireframe` 方法绘制三维线框图 在 Python 的 Matplotlib 库中,`plot_wireframe` 是一种用于创建三维线框图的方法。该方法通过指定一组二维网格上的点来定义曲面,并以线条的形式连接这些点形成框架结构。 以下是关于如何使用 `plot_wireframe` 方法的具体说明: #### 导入必要的模块 为了能够绘制三维图表,需要从 `mpl_toolkits.mplot3d` 中导入 `Axes3D` 模块[^3]。这一步骤是必不可少的,因为标准的 Matplotlib 并不支持三维绘图功能。 ```python from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np ``` #### 准备数据 通常情况下,我们需要准备三个维度的数据:X、Y 和 Z。可以利用 NumPy 提供的功能生成网格化的 X 和 Y 数据,并基于它们计算对应的 Z 值。 ```python x = np.linspace(-5, 5, 100) # 定义 x 轴范围和分辨率 y = np.linspace(-5, 5, 100) # 定义 y 轴范围和分辨率 X, Y = np.meshgrid(x, y) # 将一维数组转换成二维网格 Z = np.sin(np.sqrt(X ** 2 + Y ** 2)) # 计算 z 值作为某种函数的结果 ``` #### 创建图形对象并设置投影方式 接着,我们创建一个 Figure 对象以及一个具有 '3d' 投影属性的子图(Subplot)。这样就可以实现三维可视化效果。 ```python fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ``` #### 绘制三维线框图 调用 `plot_wireframe` 方法即可完成实际的绘图操作。此方法接受多个参数,其中最基础的是 X、Y 和 Z 数组;还可以调整其他选项比如颜色 (`color`) 或者步幅大小 (`rstride`, `cstride`) 来控制细节程度[^4]。 ```python ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5, color='blue', linewidth=0.5) ``` 上述代码片段中的 `rstride` 和 `cstride` 参数分别表示沿行方向和列方向上每隔多少个采样点画一条线。较小数值会增加图像复杂度但也更精确[^1]。 #### 添加标注信息 为了让图表更加清晰易懂,建议加上各轴名称以及其他描述性文字。 ```python ax.set_title('3D Wireframe Example') ax.set_xlabel('X Axis Label') ax.set_ylabel('Y Axis Label') ax.set_zlabel('Z Axis Label') ``` 最后展示整个图形: ```python plt.show() ``` 完整的示例程序如下所示: ```python from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np # Prepare data. x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = np.sin(np.sqrt(X**2 + Y**2)) # Create figure and axis with 3D projection. fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Draw the wireframe chart using plot_wireframe(). ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5, color='blue', linewidth=0.5) # Set labels for each dimension. ax.set_title('3D Wireframe Example') ax.set_xlabel('X Axis Label') ax.set_ylabel('Y Axis Label') ax.set_zlabel('Z Axis Label') # Show result. plt.show() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值