import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# 输入数据
x_inputs = np.array([[100, 6.5],
[50, 4],
[50, 2],
[70, 2],
[70, 4],
[0, 0]])
# 输出数据
y_outputs = np.array([[4, 0],
[2.125, 1.625],
[1.75, 1],
[1.75, 0.75],
[2.25, 1.25],
[0, 0]])
# 创建神经网络模型
model = tf.keras.Sequential([
tf.keras.layers.Dense(16, activation='relu', input_shape=(2,)),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dense(2)
])
# 编译模型
model.compile(optimizer='adam', loss='mse')
# 训练模型
history = model.fit(x_inputs, y_outputs, epochs=1000, verbose=0)
# 绘制训练损失曲线
plt.plot(history.history['loss'])
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()
# 使用训练好的模型进行预测
x_range = np.linspace(0, 100, 100)
y_range = np.linspace(0, 6.5, 100)
x_mesh, y_mesh = np.meshgrid(x_range, y_range)
inputs_mesh = np.column_stack((x_mesh.flatten(), y_mesh.flatten()))
outputs_mesh = model.predict(inputs_mesh).reshape(x_mesh.shape)
# 绘制拟合曲面
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x_inputs[:, 0], x_inputs[:, 1], y_outputs[:, 0], c='r', label='Output 1')
ax.scatter(x_inputs[:, 0], x_inputs[:, 1], y_outputs[:, 1], c='b', label='Output 2')
ax.plot_surface(x_mesh, y_mesh, outputs_mesh[:, :, 0], alpha=0.5)
ax.plot_surface(x_mesh, y_mesh, outputs_mesh[:, :, 1], alpha=0.5)
ax.set_xlabel('X1')
ax.set_ylabel('X2')
ax.set_zlabel('Y')
ax.legend()
plt.show()
需要运行上面代码
提示
使用 pip 安装 TensorFlow
使用 pip 安装 TensorFlow (google.cn)
验证安装效果:
运行代码
我是使用虚拟环境安装的TensorFlow,所以使用命令行的方式运行