Python 如何将 numpy 数组转换为标准的 TensorFlow 格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36926140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert numpy arrays to standard TensorFlow format?
提问by Keshav Choudhary
I have two numpy arrays:
我有两个 numpy 数组:
- One that contains captcha images
- Another that contains the corresponding labels (in one-hot vector format)
- 一个包含验证码图像
- 另一个包含相应标签(单热矢量格式)
I want to load these into TensorFlow so I can classify them using a neural network. How can this be done?
我想将这些加载到 TensorFlow 中,以便我可以使用神经网络对它们进行分类。如何才能做到这一点?
What shape do the numpy arrays need to have?
numpy 数组需要什么形状?
Additional Info - My images are 60 (height) by 160 (width) pixels each and each of them have 5 alphanumeric characters. Here is a sample image:
附加信息 - 我的图像是 60(高)乘 160(宽)像素,每个都有 5 个字母数字字符。这是一个示例图像:
Each label is a 5 by 62 array.
每个标签都是一个 5 x 62 的数组。
回答by Jason
You can use tf.convert_to_tensor()
:
您可以使用tf.convert_to_tensor()
:
import tensorflow as tf
import numpy as np
data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)
data_tf = tf.convert_to_tensor(data_np, np.float32)
sess = tf.InteractiveSession()
print(data_tf.eval())
sess.close()
Here's a link to the documentation for this method:
这是此方法文档的链接:
https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor
https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor
回答by Ali
You can use tf.pack(tf.stackin TensorFlow 1.0.0) method for this purpose. Here is how to pack a random image of type numpy.ndarray
into a Tensor
:
为此,您可以使用tf.pack(TensorFlow 1.0.0 中的tf.stack)方法。以下是如何将类型的随机图像打包numpy.ndarray
到 a 中Tensor
:
import numpy as np
import tensorflow as tf
random_image = np.random.randint(0,256, (300,400,3))
random_image_tensor = tf.pack(random_image)
tf.InteractiveSession()
evaluated_tensor = random_image_tensor.eval()
UPDATE: to convert a Python object to a Tensor you can use tf.convert_to_tensorfunction.
更新:要将 Python 对象转换为张量,您可以使用tf.convert_to_tensor函数。
回答by Sung Kim
You can use placeholders and feed_dict.
您可以使用占位符和 feed_dict。
Suppose we have numpy arrays like these:
假设我们有这样的 numpy 数组:
trX = np.linspace(-1, 1, 101)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33
You can declare two placeholders:
您可以声明两个占位符:
X = tf.placeholder("float")
Y = tf.placeholder("float")
Then, use these placeholders (X, and Y) in your model, cost, etc.: model = tf.mul(X, w) ... Y ... ...
然后,在您的模型、成本等中使用这些占位符(X 和 Y):model = tf.mul(X, w) ... Y ... ...
Finally, when you run the model/cost, feed the numpy arrays using feed_dict:
最后,当您运行模型/成本时,使用 feed_dict 提供 numpy 数组:
with tf.Session() as sess:
....
sess.run(model, feed_dict={X: trY, Y: trY})