본문 바로가기

공부(Deep learning)/구현-기초

[tensorflow] numpy to tf.constant

목적 : numpy 형식을 tensor 형식으로


numpy를 tf.const로 바꾸기 :

tf.convert_to_tensor(X, np.float32)  #X: numpy 형식

또는

tf.constant(X)



numpy를 tf.Variable로 바꾸기

tf.Variable(X)



코드 :

#============================================================

import tensorflow as tf
import numpy as np
from sklearn import datasets

mnist = datasets.fetch_mldata('MNIST original', data_home='.')
X = mnist.data
t = mnist.target

sess = tf.Session()
print("original X:",len(X[0]))

X_tensor_const = tf.convert_to_tensor(X, np.float32)
print("after const:",X_tensor_const)
print("after const contents:",X_tensor_const.eval(session = sess)[0][300:320])

print("after const2:",tf.constant(X.astype(float)))
print("after const2 contents:",tf.constant(X.astype(float)).eval(session= sess)[0][300:320])

X_tensor_var = tf.Variable(X.astype(float))
init = tf.global_variables_initializer()
sess.run(init)
print("after var:",X_tensor_var)
print("after var contents:",X_tensor_var.eval(session = sess)[0][300:320])

#============================================================



결과 :

#============================================================

original X: 784
after const: Tensor("Const:0", shape=(70000, 784), dtype=float32)
after const contents: [253. 243.  50.   0.   0.   0.   0.   0.   0.   0.   0.   0.   0.   0.
   0.   0.  38. 165. 253. 233.]
after const2: Tensor("Const_1:0", shape=(70000, 784), dtype=float64)
after const2 contents: [253. 243.  50.   0.   0.   0.   0.   0.   0.   0.   0.   0.   0.   0.
   0.   0.  38. 165. 253. 233.]
after var: <tf.Variable 'Variable:0' shape=(70000, 784) dtype=float64_ref>
after var contents: [253. 243.  50.   0.   0.   0.   0.   0.   0.   0.   0.   0.   0.   0.
   0.   0.  38. 165. 253. 233.]

#============================================================