Tuesday, December 27, 2016

Hello TensorFlow

In November, 2015, Google open-sourced its numerical computation library called TensorFlow using data flow graphs. Its flexible implementation and architecture enables you to focus on building the computation graph and deploy the model with little efforts on heterogeous platforms such as mobile devices, hundreds of machines, or thousands of computational devices.


#########################################################
## Installations of TensorFlow
#########################################################
Anaconda is a Python distribution that includes a large number of standard numeric and scientific computing packages. Anaconda uses a package manager called 'condo' hat has its own environment system similar to Virtualenv.

- Install Anaconda

- Create a condo environment

conda create -n tensorflow python=3.6

conda install -c conda-forge tensorflow

conda install ipython

conda install jupyter

which python

which ipython

which jupyter


- Activate the condo environment and install TensorFlow in it.

source activate tensor flow

- After the install you will activate the condo environment each time you want to use TensorFlow.

export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.0rc0-cp27-none-linux_x86_64.whl

- Optionally install iPython and other packages into the condo environment.

source activate tensor flow

source deactivate

Install Python


### Python commands
快速安装python命令行工具
``` 
python3 -m pip install --user pipx
python3 -m pipx ensurepath
```

Pipenv自动为您的项目创建和管理virtualenv,以及在安装/卸载软件包时从Pipfile添加/删除软件包。它还生成了非常重要的Pipfile.lock文件,用于生成确定性构建。
``` 
pipx install pipenv
```

Black是代码格式化工具, 产生的代码差异最小,可以加速代码审查.
isort是可以按字母顺序对 import 进行排序,并自动分成多个部分。
```
pipenv install black isort --dev
```
setup.cfg config
```
[isort]
multi_line_output=3
include_trailing_comma=True
force_grid_wrap=0
use_parentheses=True
line_length=88
```
use black and isort
```
pipenv run black
pipenv run isort
```

cookiecutter生成项目
```
pipx run cookiecutter gh:sourceryai/python-best-practices-cookiecutter
```



#############################
# Test the TensorFlow installation
#############################
python
...
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
>>> print(sess.run(hello))
Hello, TensorFlow!
>>> a = tf.constant(10)
>>> b = tf.constant(32)
>>> print(sess.run(a + b))
42

###################################
# Run TensorFlow from the Command Line
###################################
>>> import os;
>>> import inspect;
>>> import tensorflow;
>>> print(os.path.dirname(inspect.getfile(tensorflow)));
/Users/tkmaemd/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow

(tensorflow) NY-C02MW0YGFD58:~ tkmaemd$ python -c 'import os; import inspect; import tensorflow; print(os.path.dirname(inspect.getfile(tensorflow)))'
/Users/tkmaemd/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow

###################################
# Basic Usage
###################################
TensorFlow programs are usually structured into a construction phase, that assembles a graph, and an execution phase that uses a session to execute ops in the graph.

For example, it is common to create a graph to represent and train a neural network in the construction phase, and then repeatedly execute a set of training ops in the graph in the execution phase.

# Building the graph

import tensorflow as tf
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

# Launch the default graph

sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()

# Interactive Usage

import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])
x.initializer.run()
sub = tf.sub(x, a)
print(sub.eval())
# ==> [-2. -1.]
sess.close()


# Variables

state = tf.Variable(0, name="counter")
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(state))

for _ in range(3):
sess.run(update)
print(sess.run(state))

# Fetches

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)

# Feeds

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.]}))

###################################
# Hello World
###################################
import tensorflow as tf
h = tf.constant("Hello")
w = tf.constant(" World!")
hw = h + w

with tf.Session() as less: 
 ans = sess.run(hw)

print ans

###################################
# Run a TensorFlow demo model
###################################
cd /Users/tkmaemd/anaconda/envs/tensorflow/lib/python2.7/site-
packages/tensorflow/models/image/mnist


###################################
# Introduction
###################################
source activate py35
source activate tensor flow
ipython
source deactivate tensor flow
source deactivate py35

import tensorflow as tf
import numpy as np

# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3

# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 0.1 and b 0.3, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b

# Minimize the mean squared errors.
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

# Before starting, initialize the variables.  We will 'run' this first.
init = tf.global_variables_initializer()

# Launch the graph.
sess = tf.Session()
sess.run(init)

# Fit the line.
for step in range(201):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(w), sess.run(b))

# Learns best fit is W: [0.1], b: [0.3]

No comments:

Post a Comment