
###隱函數lanbda及map函數的應用實例 ''' lambda 參數1,參數2,參數3,...:表達式 ''' f = lambda x,y :x+y print(f(1,2)) ###輸出3 ''' map()接收一個函數f 和 一個Iterator(可迭代對象),並通過把函數f依次作用在Iterator的每一個元素上,並把結果做為新的Iterator返回 ''' a = [1,2,3] b = map(lambda x:x*x ,a) print(list(b)) ###輸出[1,4,9] ##map 函數處理字典 c = { 'x':np.array([1,2,3]), 'y':[4,5,6] } ##調用字典的key d = map(lambda data:data*2,c) print(list(d)) ##['xx', 'yy'] ##調用字典的values e = map(lambda data:data*2,c.values()) print(list(e)) ##[array([2, 4, 6]), [4, 5, 6, 4, 5, 6]] ##注意:列表*2重復一次,數組*2元素數字*2 def double(x): return x*2 print(list(map(double,c))) ## ['xx', 'yy'] print(list(map(double,c.values()))) ##[array([2, 4, 6]), [4, 5, 6, 4, 5, 6]]

import tensorflow as tf import numpy as np ##定義兩個數組 x = np.arange(6) y = np.arange(3,9) ##創建dataset數據集 dataset = tf.data.Dataset.from_tensor_slices({ 'x':x, 'y':y }) c = tf.data.Dataset.range(1,7) def getone(dataset): iterator = dataset.make_one_shot_iterator() #生成一個迭代器 one_element = iterator.get_next() #迭代器取值 return one_element one_element1 = getone(dataset) one_element2 = getone(c) #定義一個會話內調用的函數 def sess_get_one(one_element): for i in range(6): datav = sess.run(one_element) print(datav) #開啟會話,調取數據 with tf.Session() as sess: sess_get_one(one_element1) sess_get_one(one_element2) ''' {'x': 0, 'y': 3} {'x': 1, 'y': 4} {'x': 2, 'y': 5} {'x': 3, 'y': 6} {'x': 4, 'y': 7} {'x': 5, 'y': 8} 1 2 3 4 5 6 '''
import tensorflow as tf import numpy as np ##定義兩個數組 x = np.arange(6) y = np.arange(3,9) ##創建dataset數據集 dataset = tf.data.Dataset.from_tensor_slices({ 'x':x, 'y':y }) dataset1 = dataset.map(lambda data:(data['x']*2,tf.cast(data['y'],tf.float32))) c = tf.data.Dataset.range(1,7) def getone(dataset): iterator = dataset.make_one_shot_iterator() #生成一個迭代器 one_element = iterator.get_next() #迭代器取值 return one_element one_element1 = getone(dataset) one_element2 = getone(c) one_element3 = getone(dataset1) #定義一個會話內調用的函數 def sess_get_one(one_element): for i in range(6): datav = sess.run(one_element) print(datav) #開啟會話,調取數據 with tf.Session() as sess: sess_get_one(one_element1) sess_get_one(one_element2) sess_get_one(one_element3) ''' {'x': 0, 'y': 3} {'x': 1, 'y': 4} {'x': 2, 'y': 5} {'x': 3, 'y': 6} {'x': 4, 'y': 7} {'x': 5, 'y': 8} 字典類型的dataset數據集,每取一個值都帶着key 1 2 3 4 5 6 (0, 3.0) (2, 4.0) (4, 5.0) (6, 6.0) (8, 7.0) (10, 8.0) 相當於數據變成了:{(0, 3.0),(2, 4.0),(4, 5.0),(6, 6.0),(8, 7.0),(10, 8.0)} '''