可随意转载

将numpy对象转为tensor

v= paddle.to_tensor(v, dtype=dtype)

修改tensor形状

target[k][_slices] = paddle.reshape(v, target[k][_slices].shape)

判断变量中的tensor类型

import paddle

t = paddle.to_tensor([1])
print(type(t))

if isinstance(t, paddle.Tensor):
    print("是Tensor")
else:
    print("不是Tensor")

进度条神器tqdm

from tqdm import tqdm
import time

bar = tqdm(range(1000), desc='tqdm')
for i,(data) in enumerate(bar):
    time.sleep(0.01)

Cool~ 8行写出一个神经网络

import paddle
import paddle.nn as nn

class TestModel(nn.Layer):
    def __init__(self):
        super(TestModel, self).__init__()
        model = [nn.Linear(16,8), nn.Linear(8,4)]
        model += [nn.Linear(4,1)]
        self.model = nn.Sequential(*model)

    def forward(self, input):
        return self.model(input)

# 打印网络
shortNet = TestModel()
summary = paddle.summary(shortNet, (1,16))

迁移学习的利器init_weight

在上面的代码基础上加一点东西:

def weights(layer):
    if type(layer) == nn.Linear:
        print('before init weight:', layer.weight.numpy())
        new_weight = paddle.full(shape=layer.weight.shape, dtype=layer.weight.dtype, fill_value=0.9)
        layer.weight.set_value(new_weight)
        print('after init weight:', layer.weight.numpy())
shortNet.apply(weights)