`
daojin
  • 浏览: 677366 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

初学tensorflow之 如何操作tensor

阅读更多
#定义一个函数,进行变换
import numpy as np
x = np.array([1, 2, 3, 4, 5])
f = lambda x: x ** 2
squares = f(x)

#用vectorize 进行变换
import numpy as np
x = np.array([1, 2, 3, 4, 5])
squarer = lambda t: t ** 2
vfunc = np.vectorize(squarer)
vfunc(x)

#用tensorflow的map函数
elems = np.array([1, 2, 3, 4, 5, 6])
squares = map_fn(lambda x: x * x, elems)
# squares == [1, 4, 9, 16, 25, 36]

elems = (np.array([1, 2, 3]), np.array([-1, 1, -1]))
alternate = map_fn(lambda x: x[0] * x[1], elems, dtype=tf.int64)
# alternate == [-1, 2, -3]

//rgb 转gray
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
img = mpimg.imread('image.png')     
gray = rgb2gray(img)    
plt.imshow(gray, cmap = plt.get_cmap('gray'))
plt.show()

import numpy as np
def rgb2gray(rgb):

    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
    return gray



维度操作:
假设a的shape为[1000,128,128]

b=np.expand_dims(a,axis=0)

b的shape为[1,1000,128,128]

c=np.squeeze(b)

c的数据维度为[1000,128,128]

expand_dims为增加内容为空的维度

squeeze为删除内容为空的维度
————————————————
版权声明:本文为CSDN博主「lihanlun」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lihanlun/article/details/79891676


elems = np.array([1, 2, 3])
alternates = map_fn(lambda x: (x, -x), elems, dtype=(tf.int64, tf.int64))
# alternates[0] == [1, 2, 3]
# alternates[1] == [-1, -2, -3]

#clip by value
tf.clip_by_value(
    t, clip_value_min, clip_value_max, name=None
)
A = tf.constant([[1, 20, 13], [3, 21, 13]])
B = tf.clip_by_value(A, clip_value_min=0, clip_value_max=3) # [[1, 3, 3],[3, 3, 3]]
C = tf.clip_by_value(A, clip_value_min=0., clip_value_max=3.) # throws `TypeError`
as input and clip_values are of different dtype


#np.where
import numpy as np
a=np.array([2,4,6,8,10])
np.where(a>6, 1, 0)

#array([0, 0, 0, 1, 1])

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics