當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Tensorflow reciprocal()用法及代碼示例


Tensorflow是Google開發的開源機器學習庫。它的應用之一是開發深度神經網絡。

模塊tensorflow.math為許多基本的數學運算提供支持。函數tf.reciprocal()[別名tf.math.reciprocal]支持在Tensorflow中計算輸入的倒數。它期望以複數形式輸入為 $a+bi$ ,浮點數和整數。輸入類型為張量,如果輸入包含多個元素,則將計算按元素的倒數, $y=1/x$

用法:tf.reciprocal(x, name=None) or tf.math.reciprocal(x, name=None)

參數
x:類型為bfloat16,half,float32,float64,int32,int64,complex64或complex128的張量。
name(可選):操作的名稱。

返回類型:與x具有相同大小和類型的張量。

代碼1:

# Importing the Tensorflow library 
import tensorflow as tf 
  
# A constant vector of size 6 
a = tf.constant([-0.5, -0.1, 0, 0.1, 0.5, 2], dtype = tf.float32) 
  
# Applying the reciprocal function and 
# storing the result in 'b' 
b = tf.reciprocal(a, name ='reciprocal') 
  
# Initiating a Tensorflow session 
with tf.Session() as sess:
    print('Input type:', a) 
    print('Input:', sess.run(a)) 
    print('Return type:', b) 
    print('Output:', sess.run(b))

輸出:

Input type:Tensor("Const:0", shape=(6, ), dtype=float32)
Input:[-0.5 -0.1  0.   0.1  0.5  2. ]
Return type:Tensor("reciprocal:0", shape=(6, ), dtype=float32)
Output:[ -2.  -10.    inf  10.    2.    0.5]

 $ inf $ 表示當輸入接近零時,倒數接近無窮大。

代碼2:可視化

# Importing the Tensorflow library 
import tensorflow as tf 
  
# Importing the NumPy library 
import numpy as np 
  
# Importing the matplotlib.pylot function 
import matplotlib.pyplot as plt 
  
# Two vector each of size 20 with values from 0 to 10 
a = np.linspace(0, 10, 20) 
  
# Applying the reciprocal function and 
# storing the result in 'b' 
b = tf.reciprocal(a, name ='reciprocal') 
  
# Initiating a Tensorflow session 
with tf.Session() as sess:
    print('Input:', a) 
    print('Output:', sess.run(b)) 
    plt.plot(a, sess.run(b), color = 'red', marker ='o') 
    plt.title("tensorflow.reciprocal")  
    plt.xlabel("X")  
    plt.ylabel("Y")  
    plt.grid() 
  
    plt.show()

輸出:

Input:[ 0.          0.52631579  1.05263158  1.57894737  2.10526316  2.63157895
  3.15789474  3.68421053  4.21052632  4.73684211  5.26315789  5.78947368
  6.31578947  6.84210526  7.36842105  7.89473684  8.42105263  8.94736842
  9.47368421 10.        ]
Output:[       inf 1.9        0.95       0.63333333 0.475      0.38
 0.31666667 0.27142857 0.2375     0.21111111 0.19       0.17272727
 0.15833333 0.14615385 0.13571429 0.12666667 0.11875    0.11176471
 0.10555556 0.1       ]



相關用法


注:本文由純淨天空篩選整理自sanskar27jain大神的英文原創作品 Python | Tensorflow reciprocal() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。