TensorFlow is an open source software library developed by Google for machine learning. It can run cpus and Gpus on all Linux, Windows, and MacOS platforms. Tensorflow can be used to design, implement, and train deep learning models.

Today we are going to show you how to build a simple neural network using TensorFlow to implement Hello World in TensorFlow. In this article we train the model using the famous iris (remember the name, you’ll come across it a lot later) data set, and then get the model to correctly classify a given flower.

The iris data set contains three flowers, including “Setosa”, “Versicolor” and “Virginica”. To identify each flower type, we set up four flower attributes, including sepal length, sepal width, petal length and petal width. Next, we will use TensorFlow to build a neural network and let it correctly identify the species of iris according to these factors.

Next, we will use TensorFlow to build a neural network and let it correctly identify the species of iris according to these factors.

First, we train our model with a training data set, and then we test its accuracy with a test data set. You can download the training dataset here and the test dataset here.

The first step

First, we need to read the data from the.csv file and import it. Pandas can handle this problem easily.

The read_csv () function in the Pandas library reads the file and loads the contents as the specified variables. For the arguments to the function, we need to specify the path to the file, and the names argument can be used to specify the name of each column.

The second step

The types of flowers in the dataset are coded as 0,1, and 2. We need to encode them as [1,0,0], [0,1,0] and [0,0,1] using the one hot method. This makes it easy to train and optimize the network because the output of the network is also generated in one HOT format.

And then we need to define x and y for the training set and x and y for the test set.

The third step

It then needs to define placeholders for inputs (X), outputs (Y), and weights and biases for the network. Here we have four columns of input because the dataset has four features and three columns of output to map three types of flowers. The shape of the placeholder should satisfy this. In addition, the shape of the weight matrix must be 4×3, and the deviation must be a vector of 3 to map the input to the output (no hidden layer).

The fourth step

We then need to send the output through an activation function, using the soft-max function in Tensorflow. In order to train the model, we need to calculate the cost of the model, that is, how many errors there are in the output of the model, and here we calculate the mean variance. We can then train the model and use AdamOptimizer to reduce the cost.

Step 5

To check whether our model is accurate after training, we need to compare our model predictions with the actual results. We can then calculate the accuracy of our model by calculating the correct results we get.

After that, we need to start training the model. To do this, we first need to initialize all global variables using the global_variables_initializer function.

Step 6

Now let’s start training the model. Each Tensor execution must be done in a Tensorflow session. Therefore, we need to create a session before training, and we need to close the session after all the work is done.

First, execute the variables that initialize the tensor, and then train the model 1000 times. When training, we need to specify the training data set as X and the corresponding result as Y, because we need them to train the tensor. Here, as we pass Y, we iterate over and create a new array to ensure that its shape is the same as defined above. In each iteration, the cost is graphed to see the actual training effect.

Step 7

Finally, when the training process is over, the cost variation graph is drawn and the accuracy of the model is tested through the test data set.

After 1000 training iterations, the model achieved an accuracy of 96.67%, which is really impressive, and the cost variation chart clearly shows the huge improvement in model performance after each iteration of cost reduction.

This article will help novice Tensorflow users understand the concept of Tensorflow through this simple example and open up the starry sea of Tensorflow.

Here is the full Python code for this tutorial, which you can do yourself in the teaming environment:

import tensorflow as tf
import pandas as pd
from matplotlib import pyplot as plt

Read data from CSV
train_data = pd.read_csv("iris_training.csv", names=['f1'.'f2'.'f3'.'f4'.'f5'])
test_data = pd.read_csv("iris_test.csv", names=['f1'.'f2'.'f3'.'f4'.'f5'])

# Encode data as unique heat
train_data['f5'] = train_data['f5'].map({0: [1, 0, 0], 1: [0, 1, 0], 2: [0, 0, 1]})
test_data['f5'] = test_data['f5'].map({0: [1, 0, 0], 1: [0, 1, 0], 2: [0, 0, 1]})

# Separate training data
train_x = train_data[['f1'.'f2'.'f3'.'f4']]
train_y = train_data.ix[:, 'f5']

# Separate test data
test_x = test_data[['f1'.'f2'.'f3'.'f4']]
test_y = test_data.ix[:, 'f5']

# input and output folders
X = tf.placeholder(tf.float32, [None, 4])
Y = tf.placeholder(tf.float32, [None, 3])

# Weight and bias
weight = tf.Variable(tf.zeros([4, 3]))
bias = tf.Variable(tf.zeros([3]))

Output after running the activation function
output = tf.nn.softmax(tf.matmul(X, weight) + bias)
#cost funciton
cost = tf.reduce_mean(tf.square(Y-output))
#train model"Train" = tf. Train. AdamOptimizer (0.01). Minimize (cost)Check success
success = tf.equal(tf.argmax(output, 1), tf.argmax(Y, 1))
#c Calculation accuracy
accuracy = tf.reduce_mean(tf.cast(success, tf.float32))*100

Initialize variables
init = tf.global_variables_initializer()

Start a TensorFlow session
with tf.Session() as sess:
    costs = []
    sess.run(init)
    # Train the model 1000 times
    for i in range(1000):
        _,c = sess.run([train, cost], {X: train_x, Y: [t for t in train_y.as_matrix()]})
        costs.append(c)

    print("Training finished!")

    # Chart the costs
    plt.plot(range(1000), costs)
    plt.title("Cost Variation")
    plt.show()
    print("Accuracy: %.2f" %accuracy.eval({X: test_x, Y: [t for t in test_y.as_matrix()]}))
Copy the code

For this tutorial, Google has previously published a video version, which we have translated. You can check it out on the main website of Jizhi: Poke here.


New welfare

If you are a machine learning person, but want to learn AI knowledge in the most efficient way, we have a free opportunity to learn AI, let you from zero to master the transformation of AI engineer.

Portal of opportunity:Stamp here!!!!!

This may be your best chance to catch the AI on time, so don’t miss it.