×

tensorflow:实现二维平面模拟三维数据教程

作者:Terry2023.08.20来源:Web前端之家浏览:1186评论:0
关键词:tensorflow

在开始使用 tensorflow 实现二维平面模拟三维数据之前,我们需要先进行以下的准备工作:

  • 安装 TensorFlow

  • 导入相关的库和模块

  • 准备数据

【2.导入相关库和模块】

我们需要导入以下的库和模块:

import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt

其中,tensorflow 是我们需要使用的深度学习框架,numpy 是一个科学计算库,matplotlib.pyplot 则是数据可视化的工具包。

【3.生成数据】

在这个示例中,我们需要生成一个二维平面内的多个点,每个点都对应一个三维坐标 (x, y, z)。我们可以使用 numpy 库的 random 函数来生成这些点:

n_samples = 1000x_values = np.random.normal(0.0, 0.55, [n_samples, 1])y_values = np.random.normal(0.0, 0.55, [n_samples, 1])z_values = np.sin(x_values) + np.cos(y_values)

其中,n_samples 指定了生成的点的个数,np.random.normal() 用于生成服从正态分布的随机数,在这里生成了 x 和 y 坐标的值。z 坐标则是根据 x 和 y 坐标计算得到的。在这个示例中,我们使用了 sin 和 cos 两个函数来生成 z 坐标的值。

【4.构建模型】

接下来,我们需要构建一个深度学习模型来学习这些点的规律。在这个示例中,我们使用的是一个简单的神经网络模型。

input_layer = tf.keras.layers.Input(shape=(2,))hidden_layer = tf.keras.layers.Dense(units=50, activation=tf.keras.activations.relu)(input_layer)output_layer = tf.keras.layers.Dense(units=1)(hidden_layer)model = tf.keras.models.Model(inputs=input_layer, outputs=output_layer)

其中,输入层包含了 2 个神经元,即 x 和 y 坐标。隐层包含了 50 个神经元,并使用 relu 激活函数。输出层包含了一个神经元,用于预测对应的 z 坐标值。

【5.训练模型】

构建好模型之后,我们需要将生成的数据集分为训练集和测试集,并开始训练模型:

train_size = int(n_samples * 0.8)train_x, test_x = x_values[:train_size], x_values[train_size:]train_y, test_y = y_values[:train_size], y_values[train_size:]train_z, test_z = z_values[:train_size], z_values[train_size:]model.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.MeanSquaredError())history = model.fit(x=[train_x, train_y], y=train_z, batch_size=32, epochs=100, verbose=0, validation_split=0.2)plt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.title('Model loss')plt.ylabel('Loss')plt.xlabel('Epoch')plt.legend(['Train', 'Validation'], loc='upper left')plt.show()

在这里,我们使用了 Adam 优化器和均方误差作为损失函数进行训练。同时,我们还使用了 20% 的训练数据作为验证集,得到了一个训练历史的结果。

【6.预测结果】

最后,我们可以使用训练好的模型对测试集进行预测,并将预测结果可视化:

predictions = model.predict([test_x, test_y])fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.scatter(test_x, test_y, test_z, c='b', marker='o', label='Real points')ax.scatter(test_x, test_y, predictions, c='r', marker='o', label='Predicted points')ax.legend()plt.show()

在这里,我们使用了 matplotlib 库中的 3D 散点图来可视化真实点和预测点的对比情况。

【示例二】

【1.准备工作】

在开始使用 tensorflow 实现二维平面模拟三维数据之前,我们需要先进行以下的准备工作:

  • 安装 TensorFlow

  • 导入相关的库和模块

  • 准备数据

【2.导入相关库和模块】

我们需要导入以下的库和模块:

import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt

其中,tensorflow 是我们需要使用的深度学习框架,numpy 是一个科学计算库,matplotlib.pyplot 则是数据可视化的工具包。

【3.生成数据】

在这个示例中,我们需要生成一个二维平面内的多个点,每个点都对应一个三维坐标 (x, y, z)。我们可以使用 numpy 库的 random 函数来生成这些点:

n_samples = 1000x_values = np.random.normal(0.0, 0.55, [n_samples, 1])y_values = np.random.normal(0.0, 0.55, [n_samples, 1])z_values = np.sin(np.sqrt(x_values ** 2 + y_values ** 2)) + np.random.normal(0, 0.05, [n_samples, 1])

其中,n_samples 指定了生成的点的个数,np.random.normal() 用于生成服从正态分布的随机数,在这里生成了 x 和 y 坐标的值。z 坐标则是根据 x 和 y 坐标计算得到的。在这个示例中,我们使用了 sin 函数来生成 z 坐标的值。

【4.构建模型】

接下来,我们需要构建一个深度学习模型来学习这些点的规律。在这个示例中,我们使用的是一个简单的神经网络模型。

input_layer = tf.keras.layers.Input(shape=(2,))hidden_layer_1 = tf.keras.layers.Dense(units=50, activation=tf.keras.activations.relu)(input_layer)hidden_layer_2 = tf.keras.layers.Dense(units=25, activation=tf.keras.activations.relu)(hidden_layer_1)output_layer = tf.keras.layers.Dense(units=1)(hidden_layer_2)model = tf.keras.models.Model(inputs=input_layer, outputs=output_layer)

其中,输入层包含了 2 个神经元,即 x 和 y 坐标。隐层包含了 50 个神经元和 25 个神经元,并使用 relu 激活函数。输出层包含了一个神经元,用于预测对应的 z 坐标值。

【5.训练模型】

构建好模型之后,我们需要将生成的数据集分为训练集和测试集,并开始训练模型:

train_size = int(n_samples * 0.8)train_x, test_x = x_values[:train_size], x_values[train_size:]train_y, test_y = y_values[:train_size], y_values[train_size:]train_z, test_z = z_values[:train_size], z_values[train_size:]model.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.MeanSquaredError())history = model.fit(x=[train_x, train_y], y=train_z, batch_size=32, epochs=100, verbose=0, validation_split=0.2)plt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.title('Model loss')plt.ylabel('Loss')plt.xlabel('Epoch')plt.legend(['Train', 'Validation'], loc='upper left')plt.show()

在这里,我们使用了 Adam 优化器和均方误差作为损失函数进行训练。同时,我们还使用了 20% 的训练数据作为验证集,得到了一个训练历史的结果。

【6.预测结果】

最后,我们可以使用训练好的模型对测试集进行预测,并将预测结果可视化:

predictions = model.predict([test_x, test_y])fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.scatter(test_x, test_y, test_z, c='b', marker='o', label='Real points')ax.scatter(test_x, test_y, predictions, c='r', marker='o', label='Predicted points')ax.legend()plt.show()

在这里,我们使用了 matplotlib 库中的 3D 散点图来可视化真实点和预测点的对比情况。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/tensorflow169219868230.html

网友评论文明上网理性发言 已有0人参与

发表评论: