1、Session模式
import numpy as np
import tensorflow as tf
x = np.random.uniform(size=(5, 5))
print(x)
dataset = tf.data.Dataset.from_tensor_slices(x)
iterator = dataset.make_one_shot_iterator()
one_element = iterator.get_next()
with tf.Session() as sess:
for i in range(5):
print(sess.run(one_element))
output:
[[0.48407081 0.03628483 0.85685243 0.9885185 0.6602042 ]
[0.7674624 0.8888297 0.48057987 0.72229103 0.26369241]
[0.08343725 0.12699605 0.31953763 0.63731339 0.73616979]
[0.59368905 0.18187225 0.67860501 0.41622567 0.07726847]
[0.02645211 0.20432138 0.18880295 0.44921278 0.95174813]]
2018-11-23 13:46:09.531113: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 AVX512F FMA
[0.48407081 0.03628483 0.85685243 0.9885185 0.6602042 ]
[0.7674624 0.8888297 0.48057987 0.72229103 0.26369241]
[0.08343725 0.12699605 0.31953763 0.63731339 0.73616979]
[0.59368905 0.18187225 0.67860501 0.41622567 0.07726847]
[0.02645211 0.20432138 0.18880295 0.44921278 0.95174813]
2、Eager模式
import numpy as np
import tensorflow as tf
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
x = np.random.uniform(size=(5, 5))
print(x)
dataset = tf.data.Dataset.from_tensor_slices(x)
for one_element in tfe.Iterator(dataset):
print(one_element)
# 等价
# import numpy as np
# import tensorflow as tf
# import tensorflow.contrib.eager as tfe
#
# tfe.enable_eager_execution()
# x = np.random.uniform(size=(5, 5))
# print(x)
# dataset = tf.data.Dataset.from_tensor_slices(x)
# dataset_iter = tfe.Iterator(dataset)
#
# for one_element in range(5):
# print(dataset_iter.next())
output:
[[0.29101795 0.09259019 0.17660338 0.52656286 0.3001233 ]
[0.46576027 0.44113183 0.27082472 0.11122776 0.18648526]
[0.6122186 0.70970741 0.56580514 0.81276644 0.41534348]
[0.65401505 0.1209128 0.53892136 0.63635556 0.61327768]
[0.70670191 0.82295929 0.22628438 0.28126593 0.14501256]]
2018-11-23 13:53:23.297254: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 AVX512F FMA
tf.Tensor([0.29101795 0.09259019 0.17660338 0.52656286 0.3001233 ], shape=(5,), dtype=float64)
tf.Tensor([0.46576027 0.44113183 0.27082472 0.11122776 0.18648526], shape=(5,), dtype=float64)
tf.Tensor([0.6122186 0.70970741 0.56580514 0.81276644 0.41534348], shape=(5,), dtype=float64)
tf.Tensor([0.65401505 0.1209128 0.53892136 0.63635556 0.61327768], shape=(5,), dtype=float64)
tf.Tensor([0.70670191 0.82295929 0.22628438 0.28126593 0.14501256], shape=(5,), dtype=float64)
参考链接:https://blog.youkuaiyun.com/kwame211/article/details/78579035