Python 实现神经网络模型训练:带注释的完整代码示例
导入所需模块
import tensorflow as tf # 导入 TensorFlow 库,用于构建和训练神经网络模型 import numpy as np # 导入 NumPy 库,用于处理数值数据
定义一个神经网络模型
def neural_network_model(data): # 定义网络结构,这里使用 3 个隐藏层,每层有 256 个神经元 hidden_layer_1 = {'weights': tf.Variable(tf.random_normal([len(data[0]), 256])), # 第一个隐藏层的权重,使用随机正态分布初始化 'biases': tf.Variable(tf.random_normal([256]))} # 第一个隐藏层的偏置,使用随机正态分布初始化
hidden_layer_2 = {'weights': tf.Variable(tf.random_normal([256, 256])), # 第二个隐藏层的权重
'biases': tf.Variable(tf.random_normal([256]))} # 第二个隐藏层的偏置
hidden_layer_3 = {'weights': tf.Variable(tf.random_normal([256, 256])), # 第三个隐藏层的权重
'biases': tf.Variable(tf.random_normal([256]))} # 第三个隐藏层的偏置
output_layer = {'weights': tf.Variable(tf.random_normal([256, len(output[0])])), # 输出层的权重
'biases': tf.Variable(tf.random_normal([len(output[0])]))} # 输出层的偏置
# 定义每一层的计算方式
l1 = tf.add(tf.matmul(data, hidden_layer_1['weights']), hidden_layer_1['biases']) # 第一个隐藏层的计算结果
l1 = tf.nn.relu(l1) # 使用 ReLU 激活函数
l2 = tf.add(tf.matmul(l1, hidden_layer_2['weights']), hidden_layer_2['biases']) # 第二个隐藏层的计算结果
l2 = tf.nn.relu(l2) # 使用 ReLU 激活函数
l3 = tf.add(tf.matmul(l2, hidden_layer_3['weights']), hidden_layer_3['biases']) # 第三个隐藏层的计算结果
l3 = tf.nn.relu(l3) # 使用 ReLU 激活函数
output = tf.matmul(l3, output_layer['weights']) + output_layer['biases'] # 输出层的计算结果
return output
定义训练函数
def train_neural_network(x, y): # 定义 batch_size 和训练次数 batch_size = 100 # 每个批次的样本数量 num_epochs = 10 # 训练的轮数
# 调用神经网络模型
prediction = neural_network_model(x) # 获取模型的预测结果
# 定义损失函数
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) # 使用 Softmax 交叉熵作为损失函数
# 使用 Adam 优化器进行优化
optimizer = tf.train.AdamOptimizer().minimize(cost) # 使用 Adam 优化器最小化损失函数
# 开始训练
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) # 初始化所有变量
for epoch in range(num_epochs):
epoch_loss = 0 # 初始化每一轮的损失值
# 将数据分 batch 进行训练
for i in range(int(len(train_x) / batch_size)):
epoch_x, epoch_y = train_x[i * batch_size:(i + 1) * batch_size], train_y[i * batch_size:(i + 1) * batch_size] # 获取当前批次的训练数据
_, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y}) # 训练模型并计算损失值
epoch_loss += c # 累加每一批次的损失值
print('Epoch', epoch, 'completed out of', num_epochs, 'loss:', epoch_loss) # 打印训练进度
# 计算准确率
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) # 计算预测值与真实值是否一致
accuracy = tf.reduce_mean(tf.cast(correct, 'float')) # 计算准确率
print('Accuracy:', accuracy.eval({x: test_x, y: test_y})) # 打印测试集上的准确率
定义训练数据和测试数据
train_x = np.array(...) # 训练集的输入数据 train_y = np.array(...) # 训练集的标签数据 test_x = np.array(...) # 测试集的输入数据 test_y = np.array(...) # 测试集的标签数据
调用训练函数进行训练
train_neural_network(train_x, train_y) # 使用训练数据训练神经网络模型
原文地址: https://www.cveoy.top/t/topic/ndBT 著作权归作者所有。请勿转载和采集!