pytorch和tensorflow函数对应关系(持续更新)

pytorch和tensorflow函数对应关系

方法名称大写一般为类,小写为函数,如A,a,使用方法为A()(),a()

作用 Pytorch tensorflow
平常系列
tensor常量 troch.tensor() tf.constant()
range torch.arange() tf.range()
求和 元素.sum() tf.reduce_sum()
随机变量 torch.normal() tf.random.normal()
矩阵相乘 torch.matmul() / @ tf.matmul() / @
log torch.log() tf.math.log()
最大下标 元素.argmax() tf.argmax()
转换类型 元素.type() tf.cast()
zeros torch.zeros() tf.zeros()
实现relu torch.max(x, 0) tf.math.maximum(X, 0)
激活函数系列
relu torch.relu() tf.nn.relu()
sigmoid torch.sigmoid() tf.nn.sigmoid()
tanh torch.tanh() tf.nn.tanh()
张量 reshape 元素.reshape( (,) ) tf.reshape(元素, (, ))
损失函数系列
Crossentropy torch.nn.CrossEntropyLoss(reduction=‘none’) tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
MSE torch.nn.MSELoss(reduction=‘none’) tf.keras.losses.MeanSquaredError()
优化器系列
SGD torch.optim.SGD() tf.keras.optimizers.SGD()
RMSprop torch.optim.RMSprop() tf.keras.optimizers.RMSprop()
Adam torch.optim.Adam() tf.keras.optimizers.Adam()
AdaGrad torch.optim.AdaGrad() tf.keras.optimizers.AdaGrad()
权重初始化系列
均匀分布 torch.nn.init.uniform_() tf.keras.initializers.RandomUniform( )
正态分布 torch.nn.init.normal_(() tf.keras.initializers.RandomNormal( )
常数 torch.nn.init.constant_() tf.keras.initializers.Constant( )
xavier均匀分布 torch.nn.init.xavier_uniform_() tf.keras.initializers.glorot_uniform()
xavier正态分布 torch.nn.init.xavier_uniform_() tf.keras.initializers.glorot_normal()
he 正太分布 torch.nn.init.kaiming_uniform_() tf.keras.initializers.he_normal()
he 均匀分布 torch.nn.init.kaiming_normal_() tf.keras.initializers.he_uniform()
网络层系列
全连接层 torch.nn.Linear() tf.keras.layers.Dense()
Flatten torch.nn.Flatten() tf.keras.layers.Flatten()
Sequential torch.nn.Sequential() tf.keras.models.Sequential()
Module继承 torch.nn.Module tf.keras.Model
记录参数 net.train() with tf.GradientTape() as tape:
可求导变量 torch.normal(…,requires_grad=True) / nn.Parameter() tf.variable()
计算梯度 loss.backward() grads = tape.gradient(l, params)
参数优化 updater.step() updater.apply_gradients(zip(grads, params))
权重衰减 初始化优化器时加上 ‘weight_decay’: wd 键值对 增加参数kernel_regularizer=tf.keras.regularizers.l2(wd)
参数访问 net[i].state_dict() net.layers[2].weights
某一个参数访问 net[i].bias net.layers[2].weights[1]

注意:
1、pytorch当中和tensorflow当中的Sequential使用的时候,有 [ ] 的区别:
如下:

# pytorch
net = nn.Sequential(nn.Flatten(),
                    nn.Linear(784, 256),
                    nn.ReLU(),
                    nn.Linear(256, 10))

def init_weights(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01)

net.apply(init_weights);
# tensorflow
net = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(256, activation='relu'),
    tf.keras.layers.Dense(10)])

2、手动进行反向传播的时候的也有很大的差别

# pytorch
for x, y in data:
	# 每次更新完成需要手动的将更新器当中的值清零
	optimizer.zero_grad()
	
	# 自定义的网络 - selfnet
	y = selfnet(x)
	
	# 自定义的损失函数,或者使用系统自带的
	loss = selfloss(y,y_true) 
	
	# 使用损失值计算梯度
	loss.backward()
	
	# 使用自定义的优化器或者系统自带的优化器,更新参数,
	# 优化器在定义的时候就已经将网络的参数加了进行,所以显得在这里没有输入参数 
	# optimizer= torch.optim.SGD(selfnet.parameters(), lr=lr)
	optimizer.step()
# tensorflow
for x, y in data:
	with tf.GradientTape() as tape:
		# 自定义的网络 - selfnet
		y = selfnet(x) 
		# 自定义的损失函数,或者使用系统自带的
		loss = selfloss(y,y_true)
		
	# 将损失值和网络的可更新权重都放入tape中求导
	grads = tape.gradient(loss , selfnet.trainable_variables)
	
	# 使用自定义的优化器或者系统自带的优化器,更新参数
	optimizer.apply_gradients(zip(grads, net.trainable_variables))

3、查看网络模型

# pytorch
1、 # 直接打印网络
print(net)

2、安装pip install torchsummary
from torchsummary import summary
summary(net,input_size=(,))
# tensorflow
net.summary()

4、是否要自加 relu 层,

# pytorch
dropout1, dropout2 = 0.2, 0.5

class Net(nn.Module):
    def __init__(self, num_inputs, num_outputs, num_hiddens1, num_hiddens2,
                 is_training = True):
        super(Net, self).__init__()
        self.num_inputs = num_inputs
        self.training = is_training
        self.lin1 = nn.Linear(num_inputs, num_hiddens1)
        self.lin2 = nn.Linear(num_hiddens1, num_hiddens2)
        self.lin3 = nn.Linear(num_hiddens2, num_outputs)
        # 不能通过使用关键字的形似来使用直接使用 relu 
        # 须添加 relu 层
        self.relu = nn.ReLU()

    def forward(self, X):
        H1 = self.relu(self.lin1(X.reshape((-1, self.num_inputs))))
        # 只有在训练模型时才使用dropout
        if self.training == True:
            # 在第一个全连接层之后添加一个dropout层
            H1 = dropout_layer(H1, dropout1)
        H2 = self.relu(self.lin2(H1))
        if self.training == True:
            # 在第二个全连接层之后添加一个dropout层
            H2 = dropout_layer(H2, dropout2)
        out = self.lin3(H2)
        return out


net = Net(num_inputs, num_outputs, num_hiddens1, num_hiddens2)
# tensorflow
dropout1, dropout2 = 0.2, 0.5

class Net(tf.keras.Model):
    def __init__(self, num_outputs, num_hiddens1, num_hiddens2):
        super().__init__()
        self.input_layer = tf.keras.layers.Flatten()
        # 我们可以在每一层中通过添加关键字 activation='relu' 来确定是否使用relu
        self.hidden1 = tf.keras.layers.Dense(num_hiddens1, activation='relu')
        self.hidden2 = tf.keras.layers.Dense(num_hiddens2, activation='relu')
        self.output_layer = tf.keras.layers.Dense(num_outputs)

    def call(self, inputs, training=None):
        x = self.input_layer(inputs)
        x = self.hidden1(x)
        # 只有在训练模型时才使用dropout
        if training:
            # 在第一个全连接层之后添加一个dropout层
            x = dropout_layer(x, dropout1)
        x = self.hidden2(x)
        if training:
            # 在第二个全连接层之后添加一个dropout层
            x = dropout_layer(x, dropout2)
        x = self.output_layer(x)
        return x

net = Net(num_outputs, num_hiddens1, num_hiddens2)

猜你喜欢

转载自blog.csdn.net/To_be_little/article/details/124382699
今日推荐