1. 程式人生 > >命令式和符號式混合編程

命令式和符號式混合編程

hybrid 保存 ali 符號 spl ont code pla ids

# 命令式和符號式編程

def add_str():
    return ‘‘‘
def add(a,b):
    return a + b
‘‘‘



def fancy_func_str():
    return ‘‘‘
def fancy_func(a, b, c, d):
    e = add(a,b)
    f = add(c,d)
    g = add(e,f)
    return g
‘‘‘

def evoke_str():
    return add_str() + fancy_func_str() + ‘‘‘
print(fancy_func(1,2,3,4))
‘‘‘ prog = evoke_str() # print(prog) y = compile(prog,‘‘,exec) # exec(y) from mxnet import nd,autograd,sym from mxnet.gluon import nn,loss as gloss def get_net(): net = nn.HybridSequential() net.add(nn.Dense(256,activation=relu), nn.Dense(128,activation=relu
), nn.Dense(2)) net.initialize() return net net = get_net() X = nd.random.normal(shape=(1,512)) print(net(X)) # 通過net.hybridize()來編譯和優化HybridSequential實例中的串聯層的計算 net.hybridize() print(net(X)) # 對比 import time def benchmark(net, x): start = time.time()
for i in range(1000): _ = net(x) nd.waitall() return time.time() - start net = get_net() print(before hybridizing: %.4f sec % benchmark(net,X)) net.hybridize() print(after hybridizing: %.4f sec % benchmark(net,X)) # 保存參數 net.export(my_mlp) x = sym.var(data) print(net(x))

命令式和符號式混合編程