人工智能AI编程基础(九)
生活随笔
收集整理的這篇文章主要介紹了
人工智能AI编程基础(九)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
tensor切片的方法在實踐中大量運用,其中涉及到多維度的切片操作,有時還是挺讓人頭暈的。
tf.gather()的下標取值和切片的方法: import tensorflow as tf from datetime import datetime import numpy as npdef pprint(*args, **kwargs):print(datetime.now(), *args, **kwargs, end='\n' + '*' * 50 + '\n')params = tf.constant(['p0', 'p1', 'p2', 'p3', 'p4', 'p5']) pprint(params[3].numpy()) # 獲取第4個 pprint(tf.gather(params, 3).numpy()) # 獲取第4個 pprint(tf.gather(params, indices=[2, 0, 2, 5]).numpy()) # 分別獲取第3個,第1個,第3個,第6個 pprint(tf.gather(params, [[2, 0], [2, 5]]).numpy()) # 分別取下標的值,然后生成一個2 * 2的數組params = tf.constant([[0, 1.0, 2.0],[10.0, 11.0, 12.0],[20.0, 21.0, 22.0],[30.0, 31.0, 32.0]]) pprint(tf.gather(params, indices=[3, 1])) # 第4個下標和第1個 # 如果axis=0,則沿著縱軸進行操作; # 如果axis=1,則沿著橫軸進行操作 pprint(tf.gather(params, indices=[2, 1], axis=1).numpy()) # 多維度下標取值 params = tf.constant([[0, 0, 1, 0, 2],[3, 0, 0, 0, 4],[0, 5, 0, 6, 0]]) indices = tf.constant([[2, 4],[0, 4],[1, 3]]) pprint(tf.gather(params, indices, axis=1, batch_dims=1).numpy()) ################################################################# a = tf.random.normal([4, 35, 8]) pprint(tf.gather(a, axis=1, indices=[2, 3, 7, 9, 16]).shape) # axis=1就是第2個維度的變化 pprint(tf.gather(a, axis=2, indices=[2, 3, 7]).shape) # axis=2就是最里面的維度,所以是[4,35,3] ################################################################# # array([[b'c0', b'd0'], # [b'a1', b'b1']], dtype=object) result = tf.gather_nd(indices=[[0, 1], [1, 0]],params=[[['a0', 'b0'], ['c0', 'd0']],[['a1', 'b1'], ['c1', 'd1']]]).numpy() pprint(result) # array([b'b0', b'b1'], dtype=object),由外向內 pprint(tf.gather_nd(indices=[[0, 0, 1], [1, 0, 1]],params=[[['a0', 'b0'], ['c0', 'd0']],[['a1', 'b1'], ['c1', 'd1']]]).numpy()) # array([[[[b'a1', b'b1'], # [b'c1', b'd1']]], # [[[b'a0', b'b0'], # [b'c0', b'd0']]]], dtype=object) pprint(tf.gather_nd(indices=[[[1]], [[0]]],params=[[['a0', 'b0'], ['c0', 'd0']],[['a1', 'b1'], ['c1', 'd1']]]).numpy()) tf.boolean_mask()數據過濾的方法: # 根據布爾值篩選值 tensor = [0, 1, 2, 3] mask = np.array([True, False, True, False]) # 位置對應 pprint(tf.boolean_mask(tensor, mask)) ################################# tensor = [[1, 2], [3, 4], [5, 6]] mask = np.array([True, False, True]) pprint(tf.boolean_mask(tensor, mask)) # [[1,2],[5,6]]tensor = tf.random.normal([3, 4]) mask = np.array([True, False, True]) pprint('-----1', tf.boolean_mask(tensor, mask).shape) # shape=(2,4)tensor = tf.random.normal([4, 28, 28, 3]) mask = np.array([True, True, False, False]) # 4維中取前組數據,所以輸同是(2,28,28,3) pprint('-----2', tf.boolean_mask(tensor, mask).shape) # 在axis=3這個軸進行取值,[4,28,28,2] pprint('-----3', tf.boolean_mask(tensor, mask=[True, True, False], axis=3).shape) # 生成的數據是(3,4) pprint('-----4', tf.boolean_mask(tf.ones([2, 3, 4]), mask=[[True, False, False], [False, True, True]]).shape)總結
以上是生活随笔為你收集整理的人工智能AI编程基础(九)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于随机数的抽奖器
- 下一篇: 漫画翻译、嵌字 AI,东京大学论文被 A