以下是使用TensorFlow搭建一个全连接神经网络的完整攻略:
环境准备
首先需要安装好TensorFlow,可以通过pip安装或直接通过Anaconda安装,这里我们以pip安装TensorFlow为例:
pip install tensorflow
数据准备
在搭建神经网络之前,我们需要准备好训练数据和测试数据。以手写数字识别为例,我们可以使用sklearn库提供的手写数字数据集。
构建神经网络
接下来我们就可以开始构建全连接神经网络了。以下代码展示了如何搭建一个包含两个隐层的全连接神经网络:
import tensorflow as tf
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
#加载手写数字数据
digits = load_digits()
data = digits['data']
target = digits['target']
target_one_hot = tf.one_hot(target, depth=10).eval(session=tf.Session()) #将标签转换为one-hot编码
X_train, X_test, y_train, y_test = train_test_split(data, target_one_hot, test_size=0.2, random_state=42) #划分训练集和测试集
#定义神经网络结构
n_input = 64
n_hidden_1 = 32
n_hidden_2 = 16
n_classes = 10
X = tf.placeholder(tf.float32, shape=[None, n_input])
Y = tf.placeholder(tf.float32, shape=[None, n_classes])
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
#构建神经网络
def multilayer_perceptron(X, weights, biases):
layer_1 = tf.add(tf.matmul(X, weights['h1']), biases['b1'])
layer_1 = tf.nn.relu(layer_1)
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.relu(layer_2)
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
return out_layer
#组合网络模型
logits = multilayer_perceptron(X, weights, biases)
#定义交叉熵损失函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))
#定义准确率统计函数
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#定义梯度下降优化器
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)
#训练神经网络
n_epochs = 50
batch_size = 32
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
n_batches = int(X_train.shape[0] / batch_size)
for epoch in range(n_epochs):
avg_cost = 0
idx = 0
for batch in range(n_batches):
X_batch = X_train[idx:idx+batch_size]
Y_batch = y_train[idx:idx+batch_size]
_, c = sess.run([optimizer, cross_entropy], feed_dict={X: X_batch, Y: Y_batch})
avg_cost += c / n_batches
idx += batch_size
if epoch % 5 == 0:
train_acc = accuracy.eval(feed_dict={X: X_train, Y: y_train})
test_acc = accuracy.eval(feed_dict={X: X_test, Y: y_test})
print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost), "train accuracy={:.6f}".format(train_acc), "test accuracy={:.6f}".format(test_acc))
print("Optimization Finished!")
评估网络模型
我们通过准确率指标来评估网络模型的性能。以下代码通过打印训练集和测试集的准确率来评估网络模型的性能:
with tf.Session() as sess:
sess.run(init)
n_batches = int(X_train.shape[0] / batch_size)
for epoch in range(n_epochs):
avg_cost = 0
idx = 0
for batch in range(n_batches):
X_batch = X_train[idx:idx+batch_size]
Y_batch = y_train[idx:idx+batch_size]
_, c = sess.run([optimizer, cross_entropy], feed_dict={X: X_batch, Y: Y_batch})
avg_cost += c / n_batches
idx += batch_size
if epoch % 5 == 0:
train_acc = accuracy.eval(feed_dict={X: X_train, Y: y_train})
test_acc = accuracy.eval(feed_dict={X: X_test, Y: y_test})
print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost), "train accuracy={:.6f}".format(train_acc), "test accuracy={:.6f}".format(test_acc))
print("Optimization Finished!")
示例说明
我们使用手写数字数据集进行全连接神经网络的建立和训练,其中我们使用tf.one_hot函数将标签转换为one-hot编码,使用准确率指标评估网络模型性能。经过50轮训练,我们得到了训练集的准确率为0.651379和测试集的准确率为0.594444的结果。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:使用TensorFlow搭建一个全连接神经网络教程 - Python技术站