#### Copyright 2017 Google LLC.
# Licensed under the Apache License, Version 2.0 (the “License”);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at以下でライセンスのコピーが得られる
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an “AS IS” BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# TensorFlow Programming Concepts Tensorflow プログラミングコンセプト
**Learning Objectives:** 学習オブジェクト
* Learn the basics of the TensorFlow programming model, focusing on the following concepts:TensorFlowのプログラミング・モデルの基本をまなぶ。以下の概念にフォーカスする。
* tensors テンソル
* operations オペレーション* graphs
* sessions グラフ
* Build a simple TensorFlow program that creates a default graph, and a session that runs the graph 簡単なプログラムをつくる。それは 規定のグラフを創りグラフを実行するセッションを創る
**Note:** Please read through this tutorial carefully. このチュートリアルを注意深くお読みください。The TensorFlow programming model is probably different from others that you have encountered, and thus may not be as intuitive as you’d expect.Tensorflowプログラミングモデルは、で、またあなたがきたいするものと直感的なものではないのでおそらくあなたがみられた他のものとことなるの
## Overview of Concepts 概念のオーバービュー
TensorFlow gets its name from **tensors**, which are arrays of arbitrary dimensionality.
TensorFlowはテンソルカラキテイル。コレハニンイノジゲンの配列
Using TensorFlow, you can manipulate tensors with a very high number of dimensions.
TensorFlowを使って非常に高次元のテンソルを扱うことができる。
That said, most of the time you will work with one or more of the following low-dimensional tensors:多くの時間は、一つ或はそれ以上の以下の低い次元のテンソルを処理することになる。
* A **scalar** is a 0-d array (a 0th-order tensor). For example, `”Howdy”` or `5`
* A **vector** is a 1-d array (a 1st-order tensor). For example, `[2, 3, 5, 7, 11]` or `[5]`
* A **matrix** is a 2-d array (a 2nd-order tensor). For example, `[[3.1, 8.2, 5.9][4.3, -2.7, 6.5]]`
TensorFlow **operations** create, destroy, and manipulate tensors.TensorFlowオペレーションはテンソルを作り、消し、捜査する。 Most of the lines of code in a typical TensorFlow program are operations.典型的TensorFlowプログラムのコードのほとんどの行はオペレーションです。
A TensorFlow **graph** (also known as a **computational graph** or a **dataflow graph**) is, yes, a graph data structure.TensorFlow グラフ(コンピュテーショナル・グラフあるいはデータフロー・グラフとしても知られている)はグラフ・データ構造
A graph’s nodes are operations (in TensorFlow, every operation is associated with a graph).グラフのノード(点サーフロー内ですべてのオペレーションはグラフと関連しています。 Many TensorFlow programs consist of a single graph, but TensorFlow programs may optionally create multiple graphs. 多くのTensorFlowプログラムは一つのグラフからなるが、TensorFlowプログラムはオプションとして多重のグラフを作成する
A graph’s nodes are operations; a graph’s edges are tensors. グラフノードはオペレーションでグラフ・エッジはテンソルです、TensorFlowors flow through the graph, manipulated at each node by an operation. グラフの中のTensorFlowは各ノードでオペレーションで操作される。The output tensor of one operation often becomes the input tensor to a subsequent operation. 一つのオペレーションの出力テンソルは次のオペレーションに対する入力となる。TensorFlow implements a **lazy execution model,** meaning that nodes are only computed when needed, based on the needs of associated nodes. TensorFlowはレイジー実行モデルインプリメントし、関連するノードの必要性に基づき、ノードは必要な時に計算されることを意味する。、
Tensors can be stored in the graph as **constants** or **variables**. テンソルはconstantsあるいはvariableとしてグラフの中に保存される。
As you might guess, constants hold tensors whose values can’t change, while variables hold tensors whose values can change.あなたが予想するとおり定数はテンソルを保持しそn値は変更できないが変数保持でき値は変更できる。
However, what you may not have guessed is that constants and variables are just more operations in the graph. しかしながら、予想しなかったかもしれませんことは定数と変数はグラフのなかにさらなるオペレーションです。
A constant is an operation that always returns the same tensor value. 定数は常に同じテンソル値を返す。
A variable is an operation that will return whichever tensor has been assigned to it.変数は、代入されたどのようなテンソルでも返す。
To define a constant, use the `tf.constant` operator and pass in its value. For example:
定数を定義するために、tf.constantオペレータを使い値をpass inする。例えば
“`
x = tf.constant(5.2)
“`
Similarly, you can create a variable like this:同様に変数を次のように作る。
“`
y = tf.Variable([5])
“`
Or you can create the variable first and then subsequently assign a value like this (note that you always have to specify a default value):あるいは最初に変数を作り、続いて値を次のように割り当てる)代入)。
“`
y = tf.Variable([0])
y = y.assign([5])
“`
Once you’ve defined some constants or variables, you can combine them with other operations like `tf.add`. いったんいくつかの定数あるいは変数を定義したら、それらをtf.addなどの他のオペレータで結合させることができる。
When you evaluate the `tf.add` operation, it will call your `tf.constant` or `tf.Variable` operations to get their values and then return a new tensor with the sum of those values.tf.addのオペレータを評価するとき、tf.constant tf.valueオペレーションなどその値を呼び、他の値との和などで新しいテンソルをリターンできる
Graphs must run within a TensorFlow **session**, which holds the state for the (s) it runs:グラフはTensorFlowセッションの中で実行しなければいけない。(s)に対する状態を保持し実行する。
“`
with tf.Session() as sess:
initialization = tf.global_variables_initializer()
print(y.eval())
“`
When working with `tf.Variable`s, you must explicitly initialize them by calling `tf.global_variables_initializer` at the start of your session, as shown above.tf.variableで操作するとき、上で示した通りセッションのスタート時に`tf.global_variables_initializer`を呼ぶことにより明示的に初期化しなければならない。
**Note:**注意 A session can distribute graph execution across multiple machines (assuming the program is run on some distributed computation framework).(プログラムが分散された計算フレームワーク上で実行されるとき、)セッションはグラフの実行を複数の機械に分配することができる。 For more information, see [Distributed TensorFlow](https://www.tensorflow.org/deploy/distributed).さらなる情報については、[Distributed TensorFlow](https://www.tensorflow.org/deploy/distributed)を参照ください。
### Summary サマリー
TensorFlow programming is essentially a two-step process:TensorFlowのプログラミングは本質的に2ステップの過程です。
1. Assemble constants, variables, and operations into a graph.定数、変数そしてオペレーションのグラフへの組み込み
2. Evaluate those constants, variables and operations within a session.セッション内のこれらの定数m変数、オペレーションを評価します。
## Creating a Simple TensorFlow Program単純なTensorFlowプログラムを創造する。
Let’s look at how to code a simple TensorFlow program that adds two constants.二つの定数を追加する簡単なTensorFlowプログラムのコードをどうつくるかをみてみましょう。
### Provide import statements輸入文を与える
As with nearly all Python programs, you’ll begin by specifying some `import` statements.ほとんどすべてのpythonプログラムとのように、いくつかのimport文を指定することから始めよう。
The set of `import` statements required to run a TensorFlow program depends, of course, on the features your program will access. import文の集合はTensorFlowのプログラム依存を実行する必要がある。At a minimum, you must provide the `import tensorflow` statement in all TensorFlow programs:最小、すべてのTensorFlowプログラム内の`import tensorflow`文を指定する必要がある。
import tensorflow as tf
**Don’t forget to execute the preceding code block (the `import` statements).**いままでのコードのかたまり(import文)を実行することをわすれないでください。
Other common import statements include the following:その他の共通な重要な文は次のものである。
“`
import matplotlib.pyplot as plt # Dataset visualization.
import numpy as np # Low-level numerical Python library.
import pandas as pd # Higher-level numerical Python library.
“`
TensorFlow provides a **default graph**. TensorFlowは既定のグラフを提供する。However, we recommend explicitly creating your own `Graph` instead to facilitate tracking stateしかしながら、問題のある状態をファッシリテートしないであなた自身のグラフを明示的に創られることをお奨めします。 (e.g., you may wish to work with a different `Graph` in each cell).(例えば各セルで異なるグラフを扱いたいかもしれない)
from __future__ import print_function
import tensorflow as tf
# Create a graph. グラフを創る
g = tf.Graph()
# Establish the graph as the “default” graph.グラフを既定のグラフとして確立
with g.as_default():
# Assemble a graph consisting of the following three operations:以下の三つのオペレーシからなるグラフで組み立て
# * Two tf.constant operations to create the operands.オペランドを創るために二つのtf.constantオペレーション
# * One tf.add operation to add the two operands.二つのオペランドを追加するための一つのtf.addオペレーション
x = tf.constant(8, name=”x_const”)
y = tf.constant(5, name=”y_const”)
my_sum = tf.add(x, y, name=”x_y_sum”)
# Now create a session.セッションを創る
# The session will run the default graph.セッションは既定のグラフを実行する
with tf.Session() as sess:
print(my_sum.eval())
## Exercise: Introduce a Third Operand 練習:第三被演算子の紹介
Revise the above code listing to add three integers, instead of two:上のコードもリスティングの二つの数に変わり3つの整数を加える。
1. Define a third scalar integer constant, `z`, and assign it a value of `4`.三番目のスカラー整数 zを定義しそれに値4を代入する。
2. Add `z` to `my_sum` to yield a new sum.新しい和を譲るためにzをmy_sumに加える。
**Hintヒント:** See the API docs for [tf.add()] APIどみゅ面とを参照(https://www.tensorflow.org/api_docs/python/tf/add) for more details on its function signature.その関数のより詳細についてはこれを参照
3. Re-run the modified code block. 修正したコードのブロック再実行Did the program generate the correct grand total?プログラムは正しいグランド トータルを生成しましたか?
### Solution 解
Click below for the solution. 解を得るために以下をクリック
# Create a graph. グラフを生成
g = tf.Graph()
# Establish our graph as the “default” graph.グラフを既定のグラフとして確立する
with g.as_default():
# Assemble a graph consisting of three operations.3つのオペレーションからなるグラフを組み合わせる
# (Creating a tensor is an operation.)テンソル作成づうるのはオペレーション
x = tf.constant(8, name=”x_const”)
y = tf.constant(5, name=”y_const”)
my_sum = tf.add(x, y, name=”x_y_sum”)
# Task 1: Define a third scalar integer constant z.タスク1:三番目のスカラー整数zを定義
z = tf.constant(4, name=”z_const”)
# Task 2: Add z to `my_sum` to yield a new sum.タスク2:新しい和を譲るためにmy_sumに zを足す
new_sum = tf.add(my_sum, z, name=”x_y_z_sum”)
# Now create a session.セッションを作成
# The session will run the default graph.セッションは既定のグラフを実行
with tf.Session() as sess:
# Task 3: Ensure the program yields the correct grand total.タスク3:プログラムが正しいグランドトータルが得られたか確認してくたさい
print(new_sum.eval())
## Further Information さらなる情報
To explore basic TensorFlow graphs further, experiment with the following tutorial:
基本的なTensorFlow グラフをさらに探査するために以下のチュートリアルを経験してみてください
* [Mandelbrot set](https://www.tensorflow.org/tutorials/non-ml/mandelbrot)