
如何快速實(shí)現(xiàn)REST API集成以優(yōu)化業(yè)務(wù)流程
那如何改進(jìn)呢?
其實(shí)思路比較簡單,就是按照預(yù)測的方向多迭代幾次就可以,比如我們從完全的隨機(jī)數(shù)開始按照上述思路進(jìn)行擴(kuò)散,下面是實(shí)現(xiàn)的代碼:
# 采樣策略:把采樣過程拆解為5步,每次只前進(jìn)一步
n_steps = 5
x = torch.rand(8, 1, 28, 28).to(device) # 從完全隨機(jī)的值開始
step_history = [x.detach().cpu()]
pred_output_history = []
for i in range(n_steps):
with torch.no_grad(): # 在推理時(shí)不需要考慮張量的導(dǎo)數(shù)
pred = net(x) # 預(yù)測“去噪”后的圖像
pred_output_history.append(pred.detach().cpu())
# 將模型的輸出保存下來,以便后續(xù)繪圖時(shí)使用
mix_factor = 1/(n_steps - i) # 設(shè)置朝著預(yù)測方向移動多少
x = x*(1-mix_factor) + pred*mix_factor # 移動過程
step_history.append(x.detach().cpu()) # 記錄每一次移動,以便后續(xù)
# 繪圖時(shí)使用
fig, axs = plt.subplots(n_steps, 2, figsize=(9, 4), sharex=True)
axs[0,0].set_title('x (model input)')
axs[0,1].set_title('model prediction')
for i in range(n_steps):
axs[i, 0].imshow(torchvision.utils.make_grid(step_history[i])
[0].clip(0, 1), cmap='Greys')
axs[i, 1].imshow(torchvision.utils.make_grid(pred_output_
history[i])[0].clip(0, 1), cmap='Greys')
我們執(zhí)行5次迭代,觀察一下模型預(yù)測的變化,輸出結(jié)果如下圖所示:
從上圖可以看出,模型在第一步就已經(jīng)輸出了去噪的圖片,只是往最終的目標(biāo)前進(jìn)了一小步,效果不佳,但是迭代5次以后,發(fā)現(xiàn)效果越來越好。如果迭代更多次數(shù),效果如何呢?
# 將采樣過程拆解成40步
n_steps = 40
x = torch.rand(64, 1, 28, 28).to(device)
for i in range(n_steps):
noise_amount = torch.ones((x.shape[0],)).to(device) * (1-(i/n_
steps))# 將噪聲量從高到低移動
with torch.no_grad():
pred = net(x)
mix_factor = 1/(n_steps - i)
x = x*(1-mix_factor) + pred*mix_factor
fig, ax = plt.subplots(1, 1, figsize=(12, 12))
ax.imshow(torchvision.utils.make_grid(x.detach().cpu(), nrow=8)
[0].clip(0, 1), cmap='Greys')
從上圖可以看出,雖然在迭代多次以后,生成的圖像越來越清晰,但是最終的效果仍然不是很好,我們可以嘗試訓(xùn)練更長時(shí)間的擴(kuò)散模型,并調(diào)整模型參數(shù)、學(xué)習(xí)率、優(yōu)化器等。
文章轉(zhuǎn)自微信公眾號@ArronAI