Изменения

Перейти к: навигация, поиск

Обзор библиотек для машинного обучения на Python

992 байта добавлено, 01:28, 23 января 2019
Сверточная нейронная сеть
'''import''' tensorflow '''as''' tf
<pre style="color: green"># Import MNIST data</pre>
'''from''' tensorflow.examples.tutorials.mnist '''import''' input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot='''True''')
<pre style="color: green"># Training Parameters</pre>
learning_rate = 0.001
num_steps = 200
display_step = 10
<pre style="color: green"># Network Parameters</pre>
num_input = 784 # MNIST data input (img shape: 28*28)
num_classes = 10 # MNIST total classes (0-9 digits)
dropout = 0.75 # Dropout, probability to keep units
<pre style="color: green"># tf Graph input</pre>
X = tf.placeholder(tf.float32, ['''None''', num_input])
Y = tf.placeholder(tf.float32, ['''None''', num_classes])
keep_prob = tf.placeholder(tf.float32) <pre style="color: green"># dropout (keep probability)</pre>
<pre style="color: green"># Create some wrappers for simplicity</pre>
'''def''' conv2d(x, W, b, strides=1):
<pre style="color: green"># Conv2D wrapper, with bias and relu activation</pre>
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
'''def''' maxpool2d(x, k=2):
<pre style="color: green"># MaxPool2D wrapper</pre>
'''return''' tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
padding='SAME')
<pre style="color: green"># Create model</pre>
'''def''' conv_net(x, weights, biases, dropout):
<pre style="color: green"># MNIST data input is a 1-D vector of 784 features (28*28 pixels)
# Reshape to match picture format [Height x Width x Channel]
# Tensor input become 4-D: [Batch Size, Height, Width, Channel]</pre>
x = tf.reshape(x, shape=[-1, 28, 28, 1])
<pre style="color: green"># Convolution Layer</pre>
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
<pre style="color: green"># Max Pooling (down-sampling)</pre>
conv1 = maxpool2d(conv1, k=2)
<pre style="color: green"># Convolution Layer</pre>
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
<pre style="color: green"># Max Pooling (down-sampling)</pre>
conv2 = maxpool2d(conv2, k=2)
<pre style="color: green"># Fully connected layer # Reshape conv2 output to fit fully connected layer input</pre>
fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
<pre style="color: green"># Apply Dropout</pre>
fc1 = tf.nn.dropout(fc1, dropout)
<pre style="color: green"># Output, class prediction</pre>
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
'''return''' out
<pre style="color: green"># Store layers weight & bias</pre>
weights = {
<pre style="color: green"># 5x5 conv, 1 input, 32 outputs</pre>
'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
<pre style="color: green"># 5x5 conv, 32 inputs, 64 outputs</pre>
'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
<pre style="color: green"># fully connected, 7*7*64 inputs, 1024 outputs</pre>
'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
<pre style="color: green"># 1024 inputs, 10 outputs (class prediction)</pre>
'out': tf.Variable(tf.random_normal([1024, num_classes]))
}
}
<pre style="color: green"># Construct model</pre>
logits = conv_net(X, weights, biases, keep_prob)
prediction = tf.nn.softmax(logits)
<pre style="color: green"># Define loss and optimizer</pre>
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
train_op = optimizer.minimize(loss_op)
<pre style="color: green"># Evaluate model</pre>
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
<pre style="color: green"># Initialize the variables (i.e. assign their default value)</pre>
init = tf.global_variables_initializer()
<pre style="color: green"># Start training</pre>
'''with''' tf.Session() '''as''' sess:
<pre style="color: green"># Run the initializer</pre>
sess.run(init)
'''for''' step '''in''' '''range'''(1, num_steps+1):
batch_x, batch_y = mnist.train.next_batch(batch_size)
<pre style="color: green"># Run optimization op (backprop)</pre>
sess.run(train_op, feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.8})
'''if''' step % display_step == 0 '''or''' step == 1:
<pre style="color: green"># Calculate batch loss and accuracy</pre>
loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
Y: batch_y,
"{:.3f}".format(acc))
print("Optimization Finished!")
<pre style="color: green"># Calculate accuracy for 256 MNIST test images</pre>
print("Testing Accuracy:", \
sess.run(accuracy, feed_dict={X: mnist.test.images[:256],
333
правки

Навигация