在PyTorch中,如何使用eval()函數(shù)將模型設(shè)置為評(píng)估模式? pytorch的variable
Americanas精選控跨境問(wèn)答2025-06-116510
在PyTorch中,可以使用eval()
函數(shù)將模型設(shè)置為評(píng)估模式。eval()
函數(shù)會(huì)返回一個(gè)張量,該張量表示模型的輸出。以下是如何使用eval()
函數(shù)將模型設(shè)置為評(píng)估模式的示例:
import torch
import torch.nn as nn
import torch.optim as optim
# 定義一個(gè)簡(jiǎn)單的線性模型
class SimpleModel(nn.Module):
def __init__(self, input_size, hidden_size):
super(SimpleModel, self).__init__()
self.linear = nn.Linear(input_size, hidden_size)
def forward(self, x):
return self.linear(x)
# 創(chuàng)建一個(gè)模型實(shí)例
model = SimpleModel(10, 5)
# 定義損失函數(shù)和優(yōu)化器
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 使用eval()函數(shù)將模型設(shè)置為評(píng)估模式
eval_output = eval(model)
# 打印評(píng)估輸出
print(eval_output)
在這個(gè)例子中,我們首先定義了一個(gè)簡(jiǎn)單的線性模型,然后創(chuàng)建了一個(gè)模型實(shí)例。接下來(lái),我們定義了損失函數(shù)和優(yōu)化器。最后,我們使用eval()
函數(shù)將模型設(shè)置為評(píng)估模式,并打印評(píng)估輸出。
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。