y = x^2 求导 x = 2
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-4, 4.01, 0.1)
y = x ** 2
plt.plot(x, y)
plt.plot(2, 4, 'ro')
plt.show()
x = Variable(torch.FloatTensor([2]), requires_grad = True)
y = x ** 2
y.backward()
print(x.grad)
动态图比较 tensorflow
import tensorflow as tf
first_counter = tf.constant(0)
second_counter = tf.constant(10)
def cond(first_counter, second_counter, *args):
return first_counter < second_counter
def body(first_counter, second_counter):
first_counter = tf.add(first_counter, 2)
second_counter = tf.add(second_counter, 1)
return first_counter, second_counter
c1, c2 = tf.while_loop(cond, body, [first_counter, second_counter])
with tf.Session() as sess:
counter_1_res, counter_2_res = sess.run([c1, c2])
print(counter_1_res)
动态图比较pytorch
import torch
first_counter = torch.Tensor([0])
second_counter = torch.Tensor([10])
while(first_counter < second_counter)[0]:
first_counter += 2
second_counter += 1
print(first_counter)
print(second_counter)