홈>
import tensorflow as tf
import numpy as np
x = tf.Variable(2, name='x', trainable=True, dtype=tf.float32)
with tf.GradientTape() as t:
t.watch(x)
log_x = tf.math.log(x)
y = tf.math.square(log_x)
opt = tf.optimizers.Adam(0.5)
# train = opt.minimize(lambda: y, var_list=[x]) # FAILS
@tf.function
def f(x):
log_x = tf.math.log(x)
y = tf.math.square(log_x)
return y
yy = f(x)
train = opt.minimize(lambda: yy, var_list=[x]) # ALSO FAILS
수율 ValueError :
No gradients provided for any variable: ['x:0'].
이것은 부분적으로 제시 한 예처럼 보입니다. 이것이 버그 또는 2.0 또는 내가 잘못하고있는 버그인지 확실하지 않습니다.
업데이트 :
일부 문제와 흥미로운 메모가 있었기 때문에 아래의 솔루션을 꾸미 셨습니다.
import numpy as np
import tensorflow as tf
x = tf.Variable(3, name='x', trainable=True, dtype=tf.float32)
with tf.GradientTape(persistent=True) as t:
# log_x = tf.math.log(x)
# y = tf.math.square(log_x)
y = (x - 1) ** 2
opt = tf.optimizers.Adam(learning_rate=0.001)
def get_gradient_wrong(x0):
# this does not work, it does not actually update the value of x
x.assign(x0)
return t.gradient(y, [x])
def get_gradient(x0):
# this works
x.assign(x0)
with tf.GradientTape(persistent=True) as t:
y = (x - 1) ** 2
return t.gradient(y, [x])
#### Option 1
def a(x0, tol=1e-8, max_iter=10000):
# does not appear to work properly
x.assign(x0)
err = np.Inf # step error (banach), not actual erro
i = 0
while err > tol:
x0 = x.numpy()
# IMPORTANT: WITHOUT THIS INSIDE THE LOOP THE GRADIENTS DO NOT UPDATE
with tf.GradientTape(persistent=True) as t:
y = (x - 1) ** 2
gradients = t.gradient(y, [x])
l = opt.apply_gradients(zip(gradients, [x]))
err = np.abs(x.numpy() - x0)
print(err, x.numpy(), gradients[0].numpy())
i += 1
if i > max_iter:
print(f'stopping at max_iter={max_iter}')
return x.numpy()
print(f'stopping at err={err}<{tol}')
return x.numpy()
#### Option 2
def b(x0, tol=1e-8, max_iter=10000):
x.assign(x0)
# To use minimize you have to define your loss computation as a funcction
def compute_loss():
log_x = tf.math.log(x)
y = tf.math.square(log_x)
return y
err = np.Inf # step error (banach), not actual erro
i = 0
while err > tol:
x0 = x.numpy()
train = opt.minimize(compute_loss, var_list=[x])
err = np.abs(x.numpy() - x0)
print(err, x.numpy())
i += 1
if i > max_iter:
print(f'stopping at max_iter={max_iter}')
return x.numpy()
print(f'stopping at err={err}<{tol}')
return x.numpy()
- 답변 # 1
- 답변 # 2
위에서 승인 된 솔루션을 상향 투표했지만 엔드 투 엔드 솔루션을 실행하는 데 시간이 여전히 필요했기 때문에 코드를 해결하는 것도 가능합니다. 간단한 수학 퍼즐 :
와이즈 비즈f(x)=x-(6/7)*x-1/7
g(x)=f(f(f(f(x))))
Find x such that g(x) == 0!pip install setuptools --upgrade !pip install -q tensorflow==2.0.0-beta1 import tensorflow as tf import numpy as np tf.__version__ #=> '2.0.0-beta1' @tf.function def f(x): return x-(6/7)*x-1/7 print(tf.autograph.to_code(step.python_function)) x = tf.Variable(0, trainable=True, dtype=tf.float64) y = tf.constant([0], dtype=tf.float64) @tf.function def g(x): return f(f(f(f(x)))) print(tf.autograph.to_code(compute.python_function)) # Create a list of variables which needs to be adjusted during the training process, in this simple case it is only x variables = [x] # Instantiate a Gradient Decent Optimizer variant, it this case learning rate and specific type of optimizer doesn't matter too much optimizer = tf.optimizers.Adam(0.5) # We need to somehow specify the error between the actual value of the evaluated function in contrast to the target (which is zero) loss_object = tf.keras.losses.MeanAbsoluteError() # Since we are not running inside a TensorFlow execution graph anymore we need some means of keeping state of the gradient during training # so a persistent GradientTape is your friend and the way to go in TensorFlow 2.0 with tf.GradientTape(persistent=True) as tape: #Let's train for some iterations for i in range(1000): # given the actual value of X (which we now continueously adjust in order to find the root of the equation) y_pred = g(x) # At this point we are actually setting the whole equation to zero. Since X is variable, the goal is to find an X which satisfies the condition # (that the whole equations becomes zero). We are doing this by defining a loss which becomes zero if y_pred approximates y. Or in other words, # since y is zero, the loss becomes zero if y_pred approximates zero. loss = loss_object(y,y_pred) # Now the magic happens. Loss basically represents the error surface and is only dependent on X. So now let's compute the first derivative and # see in which direction we need to adjust X in order to minimize the error and getting a value (output of the nested equations) closer to zero grads = tape.gradient(loss, variables) # Once we've found this magic number magically, let's update the value of X based on this magic number in order to perform better on the next # iteration optimizer.apply_gradients(zip(grads, variables)) # And now it's pretty cool, we can just print the current error (loss) and the actual value of X in each iteration. At the end of the training, # we've found the optima wich a loss / error close to zero and a value of X close to 400 where 400 is the correct solution. # Small deviations from the true solutions stem from numeric errors print('Loss: {}, X: {}'.format(loss.numpy(), x.numpy()))
관련 자료
- 모든 행을 표시하지 않고 배열의 결과를 에코하는 간단한 PHP 함수
- python - 간단한 GAN은 2 단계 후 Tensorflow에서 NaN을 예측합니다
- 계속이이 간단한 Python 함수에서 작동하지 않는 것 같습니다
- r - TIdyverse를 사용하여 누적 분포 함수를 그리는 간단한 방법은 무엇입니까?
- python 정규화 함수 - 증가하는 가치 최소화
- r - 간단한 부분 집합/요약 기능에 대한 dplyr'ish 접근
- 이 간단한 함수를 편집하여 목록의 문자와 단어를 알파벳순 (Python)으로 올바르게 정렬하는 방법은 무엇입니까?
- python - Scipyoptimize 이상하게 작동하는 기능 최소화
- python - 입력 된 값을 사용하여 함수를 호출 할 때 간단한 코드가 작동하지 않는 이유는 무엇입니까?
- javascript - 간단한 해시 함수에서 잘못된 인수 오류가 발생하는 이유는 무엇입니까?
- r - 정규식으로 추출한 숫자에 간단한 수학 함수 적용
트렌드
- OpenCv의 폴더에서 여러 이미지 읽기 (python)
- 파이썬 셀레늄 모든 "href"속성 가져 오기
- html - 자바 스크립트 - 클릭 후 변경 버튼 텍스트 변경
- git commit - 자식 - 로컬 커밋 된 파일에 대한 변경을 취소하는 방법
- JSP에 대한 클래스를 컴파일 할 수 없습니다
- javascript - 현재 URL에서 특정 div 만 새로 고침/새로 고침
- jquery - JavaScript로 현재 세션 값을 얻으시겠습니까?
- javascript - swiperjs에서 정지, 재생 버튼 추가
- JavaScript 변수를 HTML div에 '출력'하는 방법
- python - 문자열에서 특정 문자 제거
무슨 일이 있습니다. 두 가지 옵션이 있습니다 :
테이프를 사용하여 그라디언트 계산이 경우 업데이트 규칙을 적용 할 때만 최적화 프로그램을 사용해야합니다.
손실을 함수로 정의 이 경우 옵티 마이저.minimize
를 사용할 수 있습니다. 방법을 사용하면 그라디언트를 계산하고 매개 변수를 업데이트하는 테이프를 만듭니다