Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create a CNN using TensorFlow

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to use TensorFlow to create CNN". In daily operation, I believe many people have doubts about how to use TensorFlow to create CNN. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use TensorFlow to create CNN"! Next, please follow the editor to study!

Use TensorFlow to create CNN#-*-coding:utf-8-*-import tensorflow as tfimport numpy as np# download mnist dataset from tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets ('. / mnist_data/', one_hot=True) # from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets## mnist = read_data_sets ('. / mnist_data/') One_hot=True) n_output_layer = 1 defines the neural network def convolutional_neural_network (data) to be trained: weights = {'walled conv1: tf.Variable (tf.random_normal ([5, 5, 1, 32]),' wicked conv2: tf.Variable ([5, 5, 32, 64])) Tf.Variable: tf.Variable (tf.random_normal ([7 * 7 * 64, 1024]), 'out': tf.Variable (tf.random_normal ([1024, n_output_layer]))} biases = {' baked conv1: tf.Variable (tf.random_normal ([32])), 'baked conv2: tf.Variable (tf.random_normal ([64])) 'bounded FCC: tf.Variable (tf.random_normal ([1024])), 'out': tf.Variable (tf.random_normal ([n_output_layer]))} data = tf.reshape (data, [- 1,28,28,1]) conv1 = tf.nn.relu (tf.nn.conv2d (data, weights [' walled conv1'], strides= [1,1,1,1] Padding='SAME'), biases ['baked conv1']) conv1 = tf.nn.max_pool (conv1, ksize= [1, 2, 2, 1], strides= [1, 2, 2, 1], padding='SAME') conv2 = tf.nn.relu (tf.nn.conv2d (conv1, weights ['walled conv2'], strides= [1, 1, 1], padding='SAME') Biases ['baked conv2']) conv2 = tf.nn.max_pool (conv2, ksize= [1, 2, 2, 1], strides= [1, 2, 2, 1], padding='SAME') fc = tf.reshape (conv2, [- 1, 7 * 7 * 64]) fc = tf.nn.relu (tf.matmul (fc, weights ['werefc']) Biases ['breadfc']) # dropout removes some "neurons" # fc = tf.nn.dropout (fc, 0.8) output = tf.add (tf.matmul (fc, weights [' out']), biases ['out']) return output# uses 100 pieces of data at a time for training batch_size = 100x = tf.placeholder (' float', [None]) 28 * 28]) Y = tf.placeholder ('float') # using data to train neural network def train_neural_network (X, Y): predict = convolutional_neural_network (X) # cost_func = tf.reduce_mean (tf.nn.softmax_cross_entropy_with_logits (logits=predict,labels=Y)) cost_func = tf.reduce_mean (tf.nn.softmax_cross_entropy_with_logits_v2 (logits=predict) Labels=Y) optimizer = tf.train.AdamOptimizer (). Minimize (cost_func) # learning rate default 0.001 epochs = 1 with tf.Session () as session: # session.run (tf.initialize_all_variables ()) session.run (tf.global_variables_initializer ()) epoch_loss = 0 for epoch in range (epochs): for i in range (int (mnist.train.num_) Examples / batch_size)): X Y = mnist.train.next_batch (batch_size) _, c = session.run ([optimizer, cost_func], feed_dict= {X: X, Y: y}) epoch_loss + = c print (epoch,':', epoch_loss) correct = tf.equal (tf.argmax (predict, 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})) train_neural_network (X, Y)

Execution result:

Accuracy: 0.9789tflearn

The above code is rewritten using tflearn, which is an advanced wrapper for TensorFlow, similar to Keras.

Tflearn provides a simpler and intuitive interface. Similar to scikit-learn, the code is as follows:

#-*-coding:utf-8-*-import tflearnfrom tflearn.layers.conv import conv_2d, max_pool_2dfrom tflearn.layers.core import input_data, dropout, fully_connectedfrom tflearn.layers.estimator import regressiontrain_x, train_y, test_x, test_y = tflearn.datasets.mnist.load_data (data_dir= ". / mnist_data/", one_hot=True) train_x = train_x.reshape (- 1,28,28,1) test_x = test_x.reshape (- 1,28,28) 1) # define neural network model conv_net = input_data (shape= [None, 28,28,1], name='input') conv_net = conv_2d (conv_net, 32, 2, activation='relu') conv_net = max_pool_2d (conv_net, 2) conv_net = conv_2d (conv_net, 64, 2, activation='relu') conv_net = max_pool_2d (conv_net, 2) conv_net = fully_connected (conv_net, 1024) Activation='relu') conv_net = dropout (conv_net, 0.8) conv_net = fully_connected (conv_net, 10, activation='softmax') conv_net = regression (conv_net, optimizer='adam', loss='categorical_crossentropy', name='output') model = tflearn.DNN (conv_net) # training model.fit ({'input': train_x}, {' output': train_y}, n_epoch=13, validation_set= ({'input': test_x}) {'output': test_y}), snapshot_step=300, show_metric=True, run_id='mnist') model.save ('. / mnist.model') # Save model "" model.load ('mnist.model') # load model model.predict ([test_x [1]]) # Forecast ""

At this point, the study on "how to use TensorFlow to create CNN" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report