Tensor
Tensor
Introduction to TensorFlow
Read Discuss Courses Practice
Introduction
TensorFlow APIs
In this article, we first discuss the basics of TensorFlow Core and then
explore the higher level API, tf.contrib.learn.
TensorFlow Core
1. Installing TensorFlow
import tensorflow as tf
Any TensorFlow Core program can be divided into two discrete sections:
Now, let us write our very first TensorFlow program to understand above
concept:
Python
# importing tensorflow
import tensorflow as tf
C++
#include <iostream>
using namespace std;
int main() {
Output:
node3 is of tf.add type. It takes two tensors as input and returns their
sum as output tensor.
Here, node3 gets evaluated which further invokes node1 and node2.
Finally, we close the session using:
sess.close()
The benefit of this approach is that you do not need to close the session
explicitly as it gets automatically closed once control goes out of the scope
of with block.
3. Variables
TensorFlow has Variable nodes too which can hold variable data. They are
mainly used to hold and update parameters of a training model. Variables
are in-memory buffers containing tensors. They must be explicitly initialized
and can be saved to disk during and after training. You can later restore
saved values to exercise or analyze the model. An important difference to
note between a constant and Variable is:
Python
# importing tensorflow
import tensorflow as tf
# evaluating node
print("Tensor value before addition:\n",sess.run(node))
Output:
In above program:
node = tf.Variable(tf.zeros([2,2]))
sess.run(tf.global_variables_initializer())
To assign a new value to a variable node, we can use assign method like
this:
Python
# importing tensorflow
import tensorflow as tf
Output:
[[3 6 9]
[2 4 6]
[1 2 3]]
a = tf.placeholder(tf.int32, shape=(3,1))
b = tf.placeholder(tf.int32, shape=(1,3))
The first argument is the data type of the tensor and one of the optional
argument is shape of the tensor.
We define another node c which does the operation of matrix
multiplication (matmul). We pass the two placeholder nodes as
argument.
c = tf.matmul(a,b)
Finally, when we run the session, we pass the value of placeholder nodes
in feed_dict argument of sess.run:
After sess.run:
Python
# Model Parameters
learning_rate = 0.01
training_epochs = 2000
display_step = 200
# Training Data
train_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
2.827,3.465,1.65,2.904,2.42,2.94,1.3])
n_samples = train_X.shape[0]
# Test Data
test_X = np.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])
test_y = np.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03])
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Graphic display
plt.plot(train_X, train_y, 'ro', label='Original data')
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
plt.legend()
plt.show()
First of all, we define some parameters for training our model, like:
learning_rate = 0.01
training_epochs = 2000
display_step = 200
X = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
W = tf.Variable(np.random.randn(), name="weight")
b = tf.Variable(np.random.randn(), name="bias")
linear_model = W*X + b
Loss (or cost) per gradient descent is calculated as the mean squared
error and its node is defined as:
optimizer =
tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
Now, the training data is fit into the linear model by applying the Gradient
Descent Algorithm. The task is repeated training_epochs number of
times. In each epoch, we perform the gradient descent step like this:
tf.contrib.learn
Python
# function to feed dict of numpy arrays into the model for training
input_fn = tf.contrib.learn.io.numpy_input_fn({"X":train_X}, train_y,
batch_size=4, num_epochs=2000)
# function to feed dict of numpy arrays into the model for testing
test_input_fn = tf.contrib.learn.io.numpy_input_fn({"X":test_X}, test_y)
W: 0.252928 b: 0.802972
Final training loss: 0.153998
Final testing loss: 0.0777036
The shape and type of feature matrix is declared using a list. Each
element of the list defines the structure of a column. In above example,
we have only 1 feature which stores real values and has been given a
name X.
features = [tf.contrib.layers.real_valued_column("X")]
estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)
input_fn = tf.contrib.learn.io.numpy_input_fn({"X":train_X},
train_y, batch_size=4, num_epochs=2000)
estimator.fit(input_fn=input_fn)
W = estimator.get_variable_value('linear/X/weight')[0][0]
b = estimator.get_variable_value('linear/bias_weight')[0]
train_loss = estimator.evaluate(input_fn=input_fn)['loss']
test_loss = estimator.evaluate(input_fn=test_input_fn)['loss']
Whether you're preparing for your first job interview or aiming to upskill in
this ever-evolving tech landscape, GeeksforGeeks Courses are your key to
success. We provide top-quality content at affordable prices, all geared
towards accelerating your growth in a time-bound manner. Join the millions
we've already empowered, and we're here to do the same for you. Don't
miss out - check it out now!
Similar Reads
Why TensorFlow is So Introduction to Tensor with
Popular - Tensorflow Tensorflow
Features
Related Tutorials
OpenAI Python API - ChatGPT Tutorial: ChatGPT-
Complete Guide 3.5 Guide for Beginners
Previous Next
Article Contributed By :
GeeksforGeeks
Improved By : vijaytakbhate20
Article Tags : Tensorflow , GBlog , Python
Practice Tags : python
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Terms & Conditions GfG Weekly Contest
Careers Offline Classes (Delhi/NCR)
In Media DSA in JAVA/C++
Contact Us Master System Design
Advertise with us Master CP
GFG Corporate Solution GeeksforGeeks Videos
Placement Training Program
Apply for Mentor
Commerce UPSC
Accountancy Polity Notes
Business Studies Geography Notes
Economics History Notes
Human Resource Management (HRM) Science and Technology Notes
Management Economics Notes
Income Tax Important Topics in Ethics
Finance UPSC Previous Year Papers
Statistics for Economics