9951 explained code solutions for 126 technologies


python-tensorflowHow can I use Python and TensorFlow to create a neural network example?


Using Python and TensorFlow, you can create a neural network example with the following steps:

  1. Import the needed libraries:
import tensorflow as tf
import numpy as np
  1. Create placeholders for the inputs and labels:
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
  1. Create the weights and biases for the network:
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
  1. Define the model:
y = tf.nn.softmax(tf.matmul(x, W) + b)
  1. Define the cost function:
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
  1. Train the model:
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
  1. Initialize the variables and run the session:
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

Helpful links

Edit this code on GitHub