Beginning TensorFlow at 2nd day


I started to learn Machine Learning and TensorFlow at 2nd day.
This article shows TensorFlow tutorial codes and some description for ML term.


๐Ÿฏ Basic Usage

To use TensorFlow you need to understand how TensorFlow

  • Represents computations as graphs
  • Executes graphs in the context of Sessions
  • Represents data as tensors
  • Maintains state with Variables

๐Ÿš• Terms

  • ops (short for operations) : Nodes in the graph
  • Tensors : Data structure as an n-dimensional array or list having Rank, Shape and Type
  • Tensor : A typed multi-dimensional array
  • Construction phase : Assembling a graph to represent and train a neural network
  • Execution phase : Using a session to execute repeatedly a set of training ops in the graph

๐ŸŽƒ Building the graph

import tensorflow as tf

# Create a Constant op that produces a 1x2 matrix. The op is
# added as a node to the default graph.
#
# The value returned by the constructor represents the output
# of the Constant op.
matrix1 = tf.constant([[3., 3.]])

# Create another Constant that produces a 2x1 matrix.
matrix2 = tf.constant([[2.],[2.]])

# Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs.
# The returned value, 'product', represents the result of the matrix
# multiplication.
product = tf.matmul(matrix1, matrix2)

The default graph now has three nodes: two constant() ops and one matmul() op.

๐Ÿ˜ธ Launching the graph in a session

# Launch the default graph.
sess = tf.Session()

# To run the matmul op we call the session 'run()' method, passing 'product'
# which represents the output of the matmul op. This indicates to the call
# that we want to get the output of the matmul op back.
#
# All inputs needed by the op are run automatically by the session. They
# typically are run in parallel.
#
# The call 'run(product)' thus causes the execution of three ops in the
# graph: the two constants and matmul.
#
# The output of the op is returned in 'result' as a numpy `ndarray` object.
result = sess.run(product)
print(result)
# ==> [[ 12.]]

# Close the Session when we're done.
sess.close()

๐Ÿ˜€ Interactive Usage

# Enter an interactive TensorFlow Session.
import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

# Initialize 'x' using the run() method of its initializer op.
x.initializer.run()

# Add an op to subtract 'a' from 'x'. Run it and print the result
sub = tf.sub(x, a)
print(sub.eval())
# ==> [-2. -1.]

# Close the Session when we're done.
sess.close()

๐Ÿ„ Variables

Variables maintain state across executions of the graph

import tensorflow as tf

# Create a Variable, that will be initialized to the scalar value 0.
state = tf.Variable(0, name="counter")

# Create an Op to add one to `state`.

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# Variables must be initialized by running an `init` Op after having
# launched the graph. We first have to add the `init` Op to the graph.
init_op = tf.initialize_all_variables()

# Launch the graph and run the ops.
with tf.Session() as sess:
# Run the 'init' op
sess.run(init_op)
# Print the initial value of 'state'
print(sess.run(state))
# Run the op that updates 'state' and print 'state'.
for _ in range(3):
sess.run(update)
print(sess.run(state))

# output:

# 0
# 1
# 2
# 3

๐Ÿž Fetches

import tensorflow as tf

input1 = tf.constant([3.0])
input2 = tf.constant([2.0])
input3 = tf.constant([5.0])
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)

with tf.Session() as sess:
result = sess.run([mul, intermed])
print(result)

# output:
# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]

๐Ÿฃ Feeds

import tensorflow as tf

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)

with tf.Session() as sess:
print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))

# output:
# [array([ 14.], dtype=float32)]

๐Ÿน Tensor Ranks, Shapes, and Types

Rank

Examples of Rank are as follows:

  • Rank 0 : Scalar (magnitude only) : s = 483
  • Rank 1 : Vector (magnitude and direction) : v = [1.1, 2.2, 3.3]
  • Rank 2 : Matrix (table of numbers) : m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  • Rank 3 : 3-Tensor (cube of numbers) : t = [[[2], [4], [6]], [[8], [10], [12]], [[14], [16], [18]]]
  • Rank n : n-Tensor (you get the idea) : โ€ฆ.

Shape

The following list shows how these relate to one another:

  • Rank 0 : Shape [] : Dimension number 0-D : A 0-D tensor. A scalar
  • Rank 1 : Shape [D0] : Dimension number 1-D : A 1-D tensor with shape [5]
  • Rank 2 : Shape [D0,D1] : Dimension number 2-D : A 2-D tensor with shape [3,4]
  • Rank 3 : Shape [D0,D1,D2] : Dimension number 3-D : A 3-D tensor with shape [1,4,3]
  • Rank n : Shape [D0,D1,โ€ฆ,D(n-1)] : Dimension number n-D : A tensor with shape [D0,D1,D(n-1)]

Shapes can be represented via Python lists/tuples of inits.

Data types

There are folloing data types to tensor:

  • DT_FLOAT / tf.float32 / 32 bits floating point.
  • DT_DOUBLE / tf.float64 / 64 bits floating point.
  • DT_INT8 / tf.int8 / 8 bits signed integer.
  • DT_INT16 / tf.int16 / 16 bits signed integer.
  • DT_INT32 / tf.int32 / 32 bits signed integer.
  • DT_INT64 / tf.int64 / 64 bits signed integer.
  • DT_UINT8 / tf.uint8 / 8 bits unsigned integer.
  • DT_STRING / tf.string / Variable length byte arrays. Each element of a Tensor is a byte array.
  • DT_BOOL / tf.bool / Boolean.
  • DT_COMPLEX64 / tf.complex64 / Complex number made of two 32 bits floating points: real and imaginary parts.
  • DT_COMPLEX128 / tf.complex128 / Complex number made of two 64 bits floating points: real and imaginary parts.
  • DT_QINT8 / tf.qint8 / 8 bits signed integer used in quantized Ops.
  • DT_QINT32 / tf.qint32 / 32 bits signed integer used in quantized Ops.
  • DT_QUINT8 / tf.quint8 / 8 bits unsigned integer used in quantized Ops.

๐Ÿˆ Introduction to Machine Learning Theory

Type

Supervised machine learning

The program is โ€œtrainedโ€ on a pre-defined set of โ€œtraining examplesโ€,
which then caficiltates its ability to reach an accurate conclusion when given new data.

Unsupervised machine learning

The program is vien a bunch of data and must find patterns and relationships therein.

๐Ÿ˜ผ Liner Regression

# A linear regression learning algorithm example using TensorFlow library.

import tensorflow as tf
import numpy
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.01
training_epochs = 1000
display_step = 50

# Training Data
train_X = numpy.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 = numpy.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]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

# Construct a linear model
pred = tf.add(tf.mul(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)

# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
with tf.Session() as sess:
sess.run(init)

# Fit all training data
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X: x, Y: y})

#Display logs per epoch step
if (epoch+1) % display_step == 0:
c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
"W=", sess.run(W), "b=", sess.run(b))

print("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

#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()

๐Ÿ‘ฝ tf.contrib.learn Quickstart

import tensorflow as tf
import numpy as np

# Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"

# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST, target_dtype=np.int)

# set variable
x_train, y_train = training_set.data, training_set.target
x_test, y_test = test_set.data, test_set.target

# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(hidden_units=[10, 40, 10], n_classes=3)

# Fit model.
classifier.fit(x=x_train, y=y_train, steps=200)

# Evaluate accuracy.
accuracy_score = classifier.evaluate(x=x_test, y=y_test)["accuracy"]
print('Accuracy: {0:f}'.format(accuracy_score))

# Classify two new flower samples.
new_samples = np.array(
[[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=float)
y = classifier.predict(new_samples)
print ('Predictions: {}'.format(str(y)))

๐Ÿ˜Ž Special Thanks


๐Ÿ  Sample Code

morizyun/tensorflow_tutorial

๐Ÿ–ฅ Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!