TensorFlow 操作簡介

2021-10-01 03:45:26 字數 2497 閱讀 9814

在tensorflow中定義常數

import tensorflow as tf

a = tf.constant(1)

b = tf.constant(2)

sess = tf.session(

)sess.run(a)

sess.run(b)

進行算數運算:

with tf.session(

)as sess:

print

("addition matrix: %i"

% sess.run(a + b)

)print

("multiplication matrix: %i"

% sess.run(a * b)

)

定義函式

a = tf.placeholder(tf.int16)

b = tf.placeholder(tf.int16)

add = tf.add(a, b)

mul = tf.multiply(a, b)

with tf.session(

)as sess:

print

("addition with variables: %i"

% sess.run(add, feed_dict=))

print

("multiplication with variables: %i"

% sess.run(mul, feed_dict =

))

矩陣乘法

matrix1 = tf.constant([[

3.,3

.]])

matrix2 = tf.constant([[

2.],

[2.]

])mul = tf.matmul(matrix1, matrix2)

sess = tf.session(

)print

(sess.run(mul)

)

可以看到上面的操作大多都需要 tf.session(),顯得有些累贅,此時可以利用eager api簡化操作

from __feature__ import absolute_import, division, print_function

import tensorflow as tf

import numpy as np

print

("setting edge model..."

)tf.enable_edger_execution(

)tf.contrib.eager

print

("define constant eager"

)a = tf.constant(2)

print

("a = %i"

% a)

b = tf.constant(3)

print

("b = %i"

% b)

print

("running operations, without tf.session"

)c = a + b

print

("a + b = % i"

% c)

d = a * b

print

("a * b = % i"

% d)

print

("mixing operations with tensors and numpy arrays"

)a = tf.constant([[

2.,1

.],[

1.,0

.]], dtype = tf.float32)

print

("tensor: \n a = %s"

% a)

b = np.array([[

3.,0

.],[

5.,1

.]], dtype = np.float32)

print

("numpyarray: \b b = %s"

% b)

print

("running operations, without tf.session"

)c = a + b

print

("a + b = %s"

% c)

d = a * b

print

("a * b = %s"

% d)

print

("iterate through tensor 'a' :"

)for i in

range

(a.shape[0]

):for j in

range

(a.shape[1]

):print

(a[i]

[j])

參考資料

安裝tensorflow 的過程簡介

ubuntu 16.04 x64 desktop pip環境為9.0.1 如果pip不是9.0.1 請執行下面的命令 pip install upgrade pip 因為tensorflow 0.12.0rc0 cp27 none linux x86 64.whl,需要的庫為libcudart.so...

Tensorflow 深度學習簡介(自用)

一些廢話,也可能不是廢話。可能對,也可能不對。機器學習的定義 如果乙個程式可以在任務t上,隨著經驗e的增加,效果p也可以隨之增加,則稱這個程式可以在經驗中學習。程式 指的是需要用到的機器學習演算法,演算法的效果除了依賴於訓練資料,也依賴於從資料種提取的特徵。也可以說機器學習的是特徵和任務之間的關聯。...

Tensorflow基本操作

tensorflow常量變數定義 import cv2 import tensorflow as tf data1 tf.constant 2,dtype tf.int32 data2 tf.variable 10,name var sess tf.session print sess.run da...