2017-11-28 1 views
0

나는 tensorflow에 익숙하지 않으며 깊은 학습 네트워크에서 놀고있었습니다. 각 반복 후에 모든 가중치에 대해 반올림하는 사용자 정의를 수행하려고했습니다. tensorflow 라이브러리의 round 함수는 값을 특정 소수점 이하로 반올림하는 옵션을 제공하지 않습니다. 그래서 나는이tf.py_func, 사용자 정의 tensorflow 함수가 텐서의 첫 번째 요소에만 적용됨

import numpy as np 
import tensorflow as tf 
from tensorflow.python.framework import ops 

np_prec = lambda x: np.round(x,3).astype(np.float32) 
def tf_prec(x,name=None): 
    with ops.name_scope("d_spiky", name,[x]) as name: 
      y = tf.py_func(np_prec, 
         [x], 
         [tf.float32], 
         name=name, 
         stateful=False) 
      return y[0] 
with tf.Session() as sess: 

    x = tf.constant([0.234567,0.712,1.2,1.7]) 
    y = tf_prec(x) 
    y = tf_prec(x) 
    tf.global_variables_initializer 

    print(x.eval(), y.eval()) 

내가 가진 출력이

[ 0.234567 0.71200001 1.20000005 1.70000005] [ 0.235  0.71200001 1.20000005 1.70000005] 

그래서 반올림 정의가 텐서의 첫 번째 항목에서만 근무하고 있었고, 난 내가 뭘 잘못에 대해 확실하지 않다 썼다 . 미리 감사드립니다.

답변

1

여기에 있기 때문에 다음 줄의 오류,

np_prec = lambda x: np.round(x,3).astype(np.float32) 

당신은 np.float32 출력을 캐스팅. 당신은

print(np.round([0.234567,0.712,1.2,1.7], 3).astype(np.float32)) #prints [ 0.235  0.71200001 1.20000005 1.70000005] 

np.round의 기본 출력은 float64이며, 다음과 같은 코드로 오류를 확인할 수 있습니다. 또한 Tout 인수를 으로 변경해야합니다. tf.py_func to float64.

위의 수정 코드와 함께 다음 코드를 제공하고 필요한 경우 주석 처리했습니다.

import numpy as np 
import tensorflow as tf 
from tensorflow.python.framework import ops 

np_prec = lambda x: np.round(x,3) 
def tf_prec(x,name=None): 
    with ops.name_scope("d_spiky", name,[x]) as name: 
      y = tf.py_func(np_prec, 
         [x], 
         [tf.float64], #changed this line to tf.float64 
         name=name, 
         stateful=False) 
      return y[0] 
with tf.Session() as sess: 

    x = tf.constant([0.234567,0.712,1.2,1.7],dtype=np.float64) #specify the input data type np.float64 
    y = tf_prec(x) 
    y = tf_prec(x) 
    tf.global_variables_initializer 

    print(x.eval(), y.eval()) 

희망이 있습니다.

+0

감사합니다. 그것은 작동합니다 :) – George

관련 문제