標籤:

TensorFlow 基本變數定義,基本操作,矩陣基本操作

使用 TensorFlow 進行基本操作的實例,這個實例主要是使用 TensorFlow 進行了加法運算。包括使用 constant 常量進行加法運算和使用 placeholder 進行變數加法運算,以及擴展到矩陣的加法運算。TensorFlow 變數定義,加法運算。

查看更多 TensorFlow 教程:TensorFlow 安裝,TensorFlow 教程,TensorFlow 資源,TensorFlow 導航。

# -*- coding:utf-8 -*-from __future__ import print_function使用 TensorFlow 進行基本操作的實例,這個實例主要是使用 TensorFlow 進行了加法運算。包括使用 constant 常量進行加法運算和使用 placeholder 進行變數加法運算,以及擴展到矩陣的加法運算。TensorFlow 變數定義,加法運算。Basic Operations example using TensorFlow library.Author: Aymeric DamienProject: https://github.com/aymericdamien/TensorFlow-Examples/import tensorflow as tf# Basic constant operations# The value returned by the constructor represents the output# of the Constant op.a = tf.constant(2)b = tf.constant(3)# Launch the default graph.with tf.Session() as sess: print("a=2, b=3") print("Addition with constants: %i" % sess.run(a+b)) print("Multiplication with constants: %i" % sess.run(a*b))# Basic Operations with variable as graph input# The value returned by the constructor represents the output# of the Variable op. (define as input when running session)# tf Graph inputa = tf.placeholder(tf.int16)b = tf.placeholder(tf.int16)# Define some operationsadd = tf.add(a, b)mul = tf.multiply(a, b)# Launch the default graph.with tf.Session() as sess: # Run every operation with variable input print("Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3})) print("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))# ----------------# More in details:# Matrix Multiplication from TensorFlow official tutorial# 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)# 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 threes ops in the# graph: the two constants and matmul.## The output of the op is returned in result as a numpy `ndarray` object.with tf.Session() as sess: result = sess.run(product) print(result) # ==> [[ 12.]]

推薦閱讀:

學習筆記TF058:人臉識別
TensorFlow 101
深度學習框架TensorFlow學習筆記(1)
調試TensorFlow的過程中用到的一些PyCharm技巧——將2空格縮進改成4空格縮進,
My solutions for `Google TensorFlow Speech Recognition Challenge`

TAG:TensorFlow |