前言😫
- 最近应导师要求,需要把现有的
tensorflow
实现的代码改成pytorch
版本的,具体代码不在此处说明(是涉及深度学习这块,需要搭建网络) - 改完觉得真的是个体力活,数据预处理直接可以用,主要是任务这块的代码,照着
tensorflow
一行行改下来的。
大致步骤:
-
先明确tensorflow的网络结构,如何查看参考下方链接,在
pytroch
上搭建相同的网络结构,注意:网络搭建顺序也要一样。 -
改写主要代码,
tensoflow
函数和pytorch
函数之间的转换(经过实践检验)-
tensorflow pytroch tf.reshape(input, shape) input.view() tf.expand_dims(input, dim) input.unsqueeze(dim) / input.view() tf.squeeze(input, dim) torch.squeeze(dim)/ input.view() tf.gather(input1, input2) input1[input2] tf.tile(input, shape) input.repeat(shape) tf.boolean_mask(input, mask) input[mask] #注意,mask是bool值,不是0,1的数值 tf.concat(input1, input2) torch.cat(input1, input2) tf.matmul() torch.matmul() tf.minium(input, min) torch.clamp(input, max=min) tf.equal(input1, input2) torch.eq(input1, input2)/ input1 == input2 tf.logical_and(input1, input2) input1 & input2 tf.logical_not(input) ~ input tf.reduce_logsumexp(input, [dim]) torch.logsumexp(input, dim=dim) tf.reduce_any(input, dim) input.any(dim) tf.reduce_mean(input) torch.mean(input) tf.reduce_sum(input) input.sum() tf.transpose(input) input.t() tf.softmax_cross_entroy_with_logits(logits, labels) torch.nn.CrossEntropyLoss(logits, labels) -
获取词向量:
tensorflow
中: input_emb = tf.gather(tf.get_variable(“input_emb”, [num, embedding_size]), input)pytorch
中:1.embedding = nn.Embedding(num, embedding_size),2.input_emb = embedding (input)
-
只是初始化embedding矩阵
tensorflow
中: input_emb = tf.get_variable(“input_emb”, [num, embedding_size])pytorch
中:1.embedding = nn.Embedding(num, embedding_size), 2.input_emb = embedding .weight
-
-
基本重构完成代码之后,检查代码以下方面:
- 👌 初始化网络权重是否正确
- 👌 如果有预训练模型,检查是否加载正确
- 👌 检查优化器,整个任务是相同的学习率,还是说是不同层,设置了不同的学习率
- 👌 如果数据预处理也需要改动,最好也检查一下预处理是否正确
写在最后
- 重构的过程可能比较烦躁,特别是代码量较多,自己也不是特别清楚整个代码的细节,只是知道代码的具体流程,所以请沉住气,不确定的地方是问问身边懂得朋友。期待你的重构成功,加油