bp神经网络tensorflow代码
时间: 2023-09-01 07:12:52 浏览: 86
bp神经网络代码
以下是一个简单的使用 TensorFlow 实现的 BP 神经网络的代码:
```python
import tensorflow as tf
# 定义神经网络模型
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
# 定义输入层、隐层和输出层的神经元数量
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
# 定义神经网络的权重和偏置项
self.weights = {
'hidden': tf.Variable(tf.random_normal([input_size, hidden_size])),
'output': tf.Variable(tf.random_normal([hidden_size, output_size]))
}
self.biases = {
'hidden': tf.Variable(tf.random_normal([hidden_size])),
'output': tf.Variable(tf.random_normal([output_size]))
}
# 定义输入、输出和隐层的占位符
self.x = tf.placeholder(tf.float32, [None, input_size])
self.y = tf.placeholder(tf.float32, [None, output_size])
self.hidden_layer = tf.add(tf.matmul(self.x, self.weights['hidden']), self.biases['hidden'])
self.hidden_layer = tf.nn.sigmoid(self.hidden_layer)
self.output_layer = tf.add(tf.matmul(self.hidden_layer, self.weights['output']), self.biases['output'])
# 定义训练函数
def train(self, x_data, y_data, learning_rate, epochs):
# 定义损失函数和优化器
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.output_layer, labels=self.y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(epochs):
_, cost = sess.run([optimizer, loss], feed_dict={self.x: x_data, self.y: y_data})
if (epoch + 1) % 100 == 0:
print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(cost))
print('Optimization Finished!')
# 使用训练好的模型进行预测
correct_prediction = tf.equal(tf.argmax(self.output_layer, 1), tf.argmax(self.y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('Accuracy:', accuracy.eval({self.x: x_data, self.y: y_data}))
```
使用方法如下:
```python
# 定义输入层神经元数量、隐层神经元数量和输出层神经元数量
input_size = 4
hidden_size = 8
output_size = 3
# 创建一个神经网络模型
neural_network = NeuralNetwork(input_size, hidden_size, output_size)
# 定义训练数据和标签
x_data = [[0, 0, 1, 0], [0, 1, 1, 0], [1, 0, 1, 0], [1, 1, 1, 0], [0, 0, 0, 1], [0, 1, 0, 1], [1, 0, 0, 1], [1, 1, 0, 1]]
y_data = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 0]]
# 训练神经网络模型
neural_network.train(x_data, y_data, 0.1, 1000)
```
在训练完成后,使用训练好的模型进行预测,并计算准确率。
阅读全文