23
loading...
This website collects cookies to deliver better user experience
# Sequential model in both Pytorch and Tensorflow
model = keras.Sequential(
[
layers.conv2d(20,5, activation="relu"),
layers.conv2d(64,5, activation="relu"),
]
)
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
import tensorflow as tf
# Tensorflow 1.x
x = tf.constant([1., 2., 3.]) # Define a tensor x
y = tf.constant([4., 5., 6.]) # Define a tensor y
add_op = tf.add(x,y) # Add operation
with tf.Session() as sess: #create a session
result = sess.run(add_op) # run the session
print(result) # [ 5.,7., 9.,]
#Tensorflow 2.x
x = tf.constant([1., 2., 3.]) # Define a tensor x
y = tf.constant([4., 5., 6.]) # Define a tensor y
result = tf.add(x,y) # Add operation
print(result) # [5,7,9]
import torch
x = torch.tensor([1,2,3]) # Define a tensor x
y = torch.tensor([4,5,6]) # Define a tensor y
result = torch.add(x,y) # Add operation
print(result) # [5,7,9]
import torch
import numpy as np
torch.tensor([1,2,3])
np.array([1,2,3])
tf.constant([1,2,3])
# OUTPUT: [1,2,3]
torch.ones(5)
np.ones(5)
tf.ones(5)
# OUTPUT: [1, 1, 1, 1, 1]
torch.zeros(5)
np.zeros(5)
# OUTPUT:[0, 0, 0, 0, 0]
t = torch.tensor([[1,2,3],[4,5,6]])
n = np.array([[1,2,3], [4,5,6]])
t.flatten()
n.flatten()
# OUTPUT:[1, 2, 3, 4, 5, 6]
# No TF equivalent
np.arange(4)
torch.arange(4)
tf.range(4) # slightly different from numpy
# OUTPUT: [0,1,2,3]
n = np.array([1,2,3,4])
p = torch.tensor([1,2,3,4])
t = tf.constant([1,2,3,.4])
print(n[0]) # output: 1
print(p[0]) # output: 1
print(t[0]) # output: 1
n[0] = 2 # n = [2,2,3,4]
p[0] = 2 # p = [2,2,3,4]
t[0] = 2 # TypeError
tf.variable
instead of tf.constant
but still it is not very straightforward like PyTorch, NumPy, or regular python list. This is just one of the ways that set TensorFlow apart from the others.