Let’s begin with TensorFlow!

In this article, we will be implementing TensorFlow in the most unlikely way. Yes, you heard it right! We won’t even be using 0.00001% of what TensorFlow offers us, but yes this will give us an insight into what TensorFlow has in its hood. Here we will be implementing a simple linear regression problem using a neural network. Astonished, right?

Let’s dive in!

First I assume that you know what Linear Regression means. In simple words, Linear Regression is a type of problem where we predict the result of a problem whose input variables are in continuous form. For implementing Linear Regression, we hardly require a neural network! In fact, the neural network won’t be as accurate as other algorithms available to solve Linear Regression problems. This is just for demonstration purposes!!

We will be using python to implement the TensorFlow library here.

The foremost thing is to import the TensorFlow library in your program. We will also be requiring the NumPy library to initialize array inputs.

import tensorflow as tf
import numpy as np

Now you are ready to use the most powerful tool.

First, let’s define the neural network which we want to use. Here’s how we define our neural network:

model = tf.keras.Sequential([tf.keras.layers.Dense(units = 1, input_shape = [1])])

Here we use only one neuron as indicated by ‘units = 1’.Once you have your neural network ready, here’s where the magic of TensorFlow kicks in. If you are familiar with Machine Learning, then you must know that you have to code the loss functions and optimizer as well, but with TensorFlow, it’s just a matter of one line. Here’s how:

model.compile(optimizer = ‘sgd’, loss = ‘mean_squared_error’)

Now you are ready with all of your initial setup, now you just have to feed the data. For demonstration purposes, we will use very less amount of data. By ‘very less’ is really mean very very very very less amount of data.

xs = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
ys = np.array([-1, 1, 3, 5, 7, 9, 11, 13, 15, 17])

Here we define an array of input elements, i.e. xs and we also provide the outputs in the form of ys. Now we are ready to train our neural network:

model.fit(xs, ys, epochs = 30)

Now we are all set to check our neural network. Here’s how:

print(model.predict([30]))

Now instead of 30 as an input parameter, you can use any other value.

Congratulations! We have just completed our first neural network program in TensorFlow, and it was just a few lines long!
Here’s the link to complete code:
https://github.com/AmanMulani/Machine-Learning-using-Tensorflow/blob/master/hello_World_in_TensorFlow.py

Thank You!

--

--

Aman Mulani
Bye-bye Machine Learning, TensorFlow: A new paradigm

Flutter and TensorFlow enthusiastic. I believe in leadership in everyday life.