apps/train.py
def train_model(
        model,
        trainloader,
        validloader,
        learning_rate,
        epochs,
        device):
    '''train the deep neural network model on the data'''

    print_every = 5
    learning_rate = .001 if learning_rate is None else float(learning_rate)
    epochs = 5 if epochs is None else int(epochs)
    if device is None:
        device = torch.device('cpu')

    criterion = nn.NLLLoss()
    optimizer = optim.Adam(
        model.classifier.parameters(),
        lr=learning_rate
    )

    steps = 0
    running_loss = 0
    model.to(device)

    for epoch in range(epochs):
        model.train()

        for inputs, labels in trainloader:
            steps += 1
            # Move input and label tensors to the default device
            inputs, labels = inputs.to(device), labels.to(device)
            optimizer.zero_grad()
            logps = model.forward(inputs)
            loss = criterion(logps, labels)
            loss.backward()
            optimizer.step()

            running_loss += loss.item()

            if steps % print_every == 0:
                valid_loss = 0
                accuracy = 0

                model.eval()
                with torch.no_grad():
                    for inputs, labels in validloader:
                        inputs, labels = inputs.to(device), labels.to(device)
                        logps = model.forward(inputs)
                        batch_loss = criterion(logps, labels)
                        valid_loss += batch_loss.item()

                        # Calculate accuracy
                        ps = torch.exp(logps)
                        _, top_class = ps.topk(1, dim=1)
                        equals = top_class == labels.view(*top_class.shape)
                        accuracy += torch.mean(equals.type(torch.FloatTensor)).item()

                print(
                    f"[LOG] Epoch {epoch+1}/{epochs} -- "
                    f"Train loss: {running_loss/print_every:.3f}.. "
                    f"Val loss: {valid_loss/len(validloader):.3f}.. "
                    f"Val accuracy: {accuracy/len(validloader):.3f}"
                )

                running_loss = 0
                model.train()

    return model
train the deep neural network model on the data
train the deep neural network model on the data
train the deep neural network model on the data
def train_model(
        model,
        trainloader,
        validloader,
        learning_rate,
        epochs,
        device):
    print_every = 5
    learning_rate = .001 if learning_rate is None else float(learning_rate)
    epochs = 5 if epochs is None else int(epochs)
    if device is None:
        device = torch.device('cpu')
    criterion = nn.NLLLoss()
    optimizer = optim.Adam(
        model.classifier.parameters(),
        lr=learning_rate
    )
    steps = 0
    running_loss = 0
    model.to(device)
    for epoch in range(epochs):
        model.train()
        for inputs, labels in trainloader:
            steps += 1
            inputs, labels = inputs.to(device), labels.to(device)
            optimizer.zero_grad()
            logps = model.forward(inputs)
            loss = criterion(logps, labels)
            loss.backward()
            optimizer.step()
            running_loss += loss.item()
            if steps % print_every == 0:
                valid_loss = 0
                accuracy = 0
                model.eval()
                with torch.no_grad():
                    for inputs, labels in validloader:
                        inputs, labels = inputs.to(device), labels.to(device)
                        logps = model.forward(inputs)
                        batch_loss = criterion(logps, labels)
                        valid_loss += batch_loss.item()
                        ps = torch.exp(logps)
                        _, top_class = ps.topk(1, dim=1)
                        equals = top_class == labels.view(*top_class.shape)
                        accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
                print(
                    f"[LOG] Epoch {epoch+1}/{epochs} -- "
                    f"Train loss: {running_loss/print_every:.3f}.. "
                    f"Val loss: {valid_loss/len(validloader):.3f}.. "
                    f"Val accuracy: {accuracy/len(validloader):.3f}"
                )
                running_loss = 0
                model.train()
    return model
def train_model ( model , trainloader , validloader , learning_rate , epochs , device ) : print_every = 5 learning_rate = .001 if learning_rate is None else float ( learning_rate ) epochs = 5 if epochs is None else int ( epochs ) if device is None : device = torch . device ( 'cpu' ) criterion = nn . NLLLoss ( ) optimizer = optim . Adam ( model . classifier . parameters ( ) , lr = learning_rate ) steps = 0 running_loss = 0 model . to ( device ) for epoch in range ( epochs ) : model . train ( ) for inputs , labels in trainloader : steps += 1 inputs , labels = inputs . to ( device ) , labels . to ( device ) optimizer . zero_grad ( ) logps = model . forward ( inputs ) loss = criterion ( logps , labels ) loss . backward ( ) optimizer . step ( ) running_loss += loss . item ( ) if steps % print_every == 0 : valid_loss = 0 accuracy = 0 model . eval ( ) with torch . no_grad ( ) : for inputs , labels in validloader : inputs , labels = inputs . to ( device ) , labels . to ( device ) logps = model . forward ( inputs ) batch_loss = criterion ( logps , labels ) valid_loss += batch_loss . item ( ) ps = torch . exp ( logps ) _ , top_class = ps . topk ( 1 , dim = 1 ) equals = top_class == labels . view ( * top_class . shape ) accuracy += torch . mean ( equals . type ( torch . FloatTensor ) ) . item ( ) print ( f"[LOG] Epoch {epoch+1}/{epochs} -- " f"Train loss: {running_loss/print_every:.3f}.. " f"Val loss: {valid_loss/len(validloader):.3f}.. " f"Val accuracy: {accuracy/len(validloader):.3f}" ) running_loss = 0 model . train ( ) return model
train the deep neural network model on the data
train the deep neural network model on the data
'''train the deep neural network model on the data''' # Move input and label tensors to the default device # Calculate accuracy
model
trainloader
validloader
learning_rate
epochs
device