运行Python中的TensorFlow库进行神经网络拟合的示例代码

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,所以使用命令行的方式运行

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值