在3分钟内:用Python编写你的第一个神经网络

这是对神经网络的非数学介绍。我强烈建议深入研究它背后的数学 - 因为它可以提供全面的理解。但在Python中编写这个代码并检查输出是非常棒的。我相信你会明白为什么有这么多的深度学习炒作!

目标 :使用手写数字数据集(MNIST),其中包含60,000个手写数字示例和分类(0-9)。将它传递到神经网络来预测正确的数字。

在3分钟内:用Python编写你的第一个神经网络

MNIST数据

第1步 :使用tensorflow导入MNIST数据集



Python学习裙:肆捌叁伍肆陆肆壹陆

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data",one_hot=True)

第2步:创建3个隐藏层,每个层包含1000个节点,并将类的数量初始化为10(这是数字的数量,即0-9)。此外,创建两个占位符变量x和y,它们将存储tensorflow图中的值。此外,将批量大小设置为100--尽管我们可以完全处理MNIST数据集,但我们将在100个不同的批次中进行优化。

#Three hidden layers

n_nodes_hl1 = 1000

n_nodes_hl2 = 1000

n_nodes_hl3 = 1000

#Number of classes

n_classes = 10

#Will go through 100 features at a time

batch_size = 100

#Placeholder variables (height * width)

#These are placeholders for some values in the graph

x = tf.placeholder('float',[None,784])

y = tf.placeholder('float')

第3步:神经网络建模

  • 为所有层定义权重和偏差,并根据它们各自的维度。(3隐藏层+ 1输出层)
  • 将值输入到所有层中,这就是:(input_data*weight) +偏差
  • 从输出层返回输出

def neural_network_model(data):

#Define weights and biases with their dimensions

hidden_1_layer = {'weights' : tf.Variable(tf.random_normal([784,n_nodes_hl1])),

'biases' : tf.Variable(tf.random_normal([n_nodes_hl1]))}

#bias is used to make some neurons fire even if all inputs is 0

hidden_2_layer = {'weights' : tf.Variable(tf.random_normal([n_nodes_hl1,n_nodes_hl2])),

'biases' : tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'weights' : tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl3])),

'biases' : tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights' : tf.Variable(tf.random_normal([n_nodes_hl3,n_classes])),

'biases' : tf.Variable(tf.random_normal([n_classes]))}

# Layer values =(input_data*weights) + biases

l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']),hidden_1_layer['biases'])

l1 = tf.nn.relu(l1)

l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']),hidden_2_layer['biases'])

l2 = tf.nn.relu(l2)

l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']),hidden_3_layer['biases'])

l3 = tf.nn.relu(l3)

output = tf.matmul(l3,output_layer['weights'])+ output_layer['biases']

return output

第4步:现在我们已经建模了我们的神经网络,让我们来运行它!

  • 首先,从上面的模型中检索预测
  • 定义成本函数(我们试图最小化的变量)
  • 选择优化器来优化成本函数 - 我们使用“AdamOptimizer”
  • 初始化前馈和后向传播的周期数(称为epoch)为10
  • 对于每个时期和每批数据(在for循环中),运行优化器并输出成本函数的值。成本函数应该在最初时大量减少,然后停滞。
  • 计算精度

def train_neural_network(x):

prediction = neural_network_model(x)

#Cost function is cross entropy with logits

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))

#Choose the optimizer

optimizer = tf.train.AdamOptimizer().minimize(cost)

#Cycles feed forward + backprop

hm_epochs = 10

with tf.Session() as sess:

sess.run(tf.global_variables_initializer())

#Training the network

for epoch in range(hm_epochs):

epoch_loss = 0

for _ in range(int(mnist.train.num_examples/batch_size)):

epoch_x,epoch_y = mnist.train.next_batch(batch_size)

_, c = sess.run([optimizer,cost], feed_dict = {x:epoch_x,y:epoch_y})

epoch_loss += c

print('Epoch',epoch,'Completed out of',hm_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:mnist.test.images,y:mnist.test.labels}))

第5步 :运行你的神经网络!

train_neural_network(x)

输出:我们将在每个阶段中完成时间的数量以及损失函数的值。此外,该网络的精度高达95.93%

欢迎关注薇信公众号:程序员大牛。每天分享更多干活!


猜你喜欢

转载自blog.csdn.net/qq_41396296/article/details/80543658