<jupyter_start><jupyter_text>Correct answer:```python TODO: import WandBimport wandb```------    ```python TODO: import WandB Alert and timedeltafrom wandb import AlertLevelfrom datetime import timedelta```<jupyter_code># TODO: import WandB

import torch, torchvision, os

import numpy as np
import scikitplot as skplt
import matplotlib.pyplot as plt
import torch.nn.functional as F

# TODO: import WandB Alert and timedelta

from sklearn.metrics import f1_score
from sklearn import datasets
from tqdm import tqdm<jupyter_output><empty_output><jupyter_text>Correct answer:```python TODO: WandB loginwandb.login()```<jupyter_code># TODO: WandB login<jupyter_output><empty_output><jupyter_text>Dataset[torch.utils.data.Dataset](https://pytorch.org/docs/stable/data.htmltorch.utils.data.Dataset) - An abstract class representing a Dataset [torch.utils.data.DataLoader](https://pytorch.org/docs/stable/data.htmltorch.utils.data.DataLoader) - Data loader. Combines a dataset and a sampler, and provides an iterable over the given dataset.[sklearn.datasets.load_iris()](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.htmlsklearn.datasets.load_iris) - Iris Dataset.<jupyter_code>class IrisDataset(torch.utils.data.Dataset):
    def __init__(self, train=True):
        super(IrisDataset, self).__init__()
        iris = datasets.load_iris()
        self.inputs = torch.from_numpy(iris.data.astype(np.float32))
        self.targets = torch.from_numpy(iris.target.astype(np.long))

    def __len__(self):
        return len(self.targets)
    
    def __getitem__(self, item):
        return [self.inputs[item], self.targets[item]]
train_dataset = IrisDataset()
trainloader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True, )

print(len(train_dataset))
train_dataset[0][0].shape<jupyter_output><empty_output><jupyter_text>Model[torch.nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.htmltorch.nn.Module) - Base class for all neural network modules. [torch.nn.Conv2d](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.htmltorch.nn.Conv2d) - Applies a 2D convolution over an input signal composed of several input planes.[torch.nn.MaxPool2d](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.htmltorch.nn.MaxPool2d) - Applies a 2D max pooling over an input signal composed of several input planes.[torch.nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.htmltorch.nn.Linear) - Applies a linear transformation to the incoming data: $ y = xA^T + b $[torch.nn.functional.relu](https://pytorch.org/docs/stable/nn.functional.htmltorch.nn.functional.relu) - Applies the rectified linear unit function element-wise.<jupyter_code>class IrisNet(torch.nn.Module):
    def __init__(self):
        super(IrisNet, self).__init__()
        self.fc1 = torch.nn.Linear(4, 100)
        self.fc2 = torch.nn.Linear(100, 3)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x<jupyter_output><empty_output><jupyter_text>Define a Loss function and optimizer<jupyter_code>config = {"lr": 1e-2, "num_epoch": 15}
model = IrisNet()

criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=config["lr"])<jupyter_output><empty_output><jupyter_text>Correct answer:```python TODO: WandB initrun = wandb.init(project="mnist")     TODO: WandB configwandb.config.update(config)     TODO: WandB watchwandb.watch(model)```<jupyter_code># TODO: WandB init


# TODO: WandB config


# TODO: WandB watch<jupyter_output><empty_output><jupyter_text>Train the network    Correct answer:```python TODO: Change to wandb.logwandb.log({"loss": loss}, commit=False)wandb.log({"f1_macro": f1_macro}, commit=False)wandb.log(f1_none, commit=False)wandb.log({"cf_matrix": wandb.Image(plt)})plt.close()```--------```python TODO: WandB Alertsif f1_macro > 0.7:    wandb.alert(        title='Good accuracy',         text=f'F1-score {f1_macro} is above 0.7',        level=AlertLevel.INFO,  INFO, WARN, or ERROR         wait_duration=timedelta(minutes=5)    )```<jupyter_code>for e in range(config["num_epoch"]):
    for i, data in tqdm(enumerate(trainloader)):
        # get the inputs; data is a list of [inputs, labels]
        inputs, targets = data

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = model(inputs)
        loss = criterion(outputs, targets)
        loss.backward()
        optimizer.step()

    # print progress
    loss = loss.item()
    # TODO: Change to wandb.log
    print('[%5d] loss: %.3f' % (i + 1, loss))
    with torch.no_grad():
        predicted = []
        targeted = []
        for data in trainloader:
            inputs, targets = data
            outputs = torch.argmax(model(inputs), -1)
            targeted += targets.tolist()
            predicted += outputs.tolist()

        f1_none = f1_score(targeted, predicted, average=None)
        f1_macro = f1_score(targeted, predicted, average='macro')

    # TODO: Change to wandb.log
    print('[%5d] f1_macro: %.3f' % (i + 1, f1_macro))
    f1_none = {"f1_none/"+str(e): v for e,v in enumerate(f1_none)}
    print('[%5d]', f1_none)

    skplt.metrics.plot_confusion_matrix(targeted, predicted, normalize=True)
    plt.show()
    
    # TODO: WandB Alerts<jupyter_output><empty_output><jupyter_text>Correct answer:  ```python     TODO: WandB Save Filewandb.save("path/to/file")```<jupyter_code>torch.save(model.state_dict(), "model.pth")

# TODO: WandB Save File<jupyter_output><empty_output><jupyter_text>Correct answer:```python TODO: WandB Finish    run.finish()```<jupyter_code># TODO: WandB Finish<jupyter_output><empty_output><jupyter_text>Correct answer:   ```python TODO: WandB reinitrun = wandb.init(project="project_name", id="project_id", resume=True)model_pth = wandb.restore("model.pth")```<jupyter_code># TODO: WandB reinit


model = IrisNet()

model.load_state_dict(torch.load(model_pth.name))
run.finish()
run = wandb.init(project="another-logs")
mnist = torchvision.datasets.MNIST(root='.', train=True, download=True)
print(np.array(mnist[0][0]).shape)<jupyter_output><empty_output><jupyter_text>Correct answer:```python     TODO: WandB Imagewandb.log({"sample_" + str(idx): [wandb.Image(sample, caption=str(target))]})```<jupyter_code>idx = 15
sample = np.array(mnist[0][0])
target = np.array(mnist[0][1])
plt.imshow(sample)
plt.show()

# TODO: WandB Image<jupyter_output><empty_output><jupyter_text>Correct answer:  ```python TODO: WandB Segmentation Maskmask_img = wandb.Image(sample[0], masks={  "predictions": {    "mask_data": prediction,    "class_labels": class_labels,  },  "ground_truth": {    "mask_data": ground_truth,    "class_labels": class_labels  },})```<jupyter_code>idx = 20
sample = np.array(mnist[idx][0])

class_labels = {
  0: "background",
  1: "number",
}

prediction = np.array(sample>200, dtype=np.int)
ground_truth = np.array(sample>100, dtype=np.int)

# TODO: WandB Segmentation Mask
mask_img = None

wandb.log({"name": mask_img})<jupyter_output><empty_output><jupyter_text>Correct answer:  ```python TODO: WandB Text Table 1wandb.log({"examples": wandb.Table(data=data, columns=["Text", "Predicted Label", "True Label"])}) TODO: WandB Text Table 2table = wandb.Table(columns=["Text", "Predicted Label", "True Label"])table.add_data("I love my phone", "1", "1")table.add_data("My phone is terrible", "0", "-1")wandb.log({"examples": table})```<jupyter_code>data = [["I love my phone", "1", "1"],["My phone is terrible", "+ášľť0", "-1"]]
# TODO: WandB Text Table #1


# TODO: WandB Text Table #2<jupyter_output><empty_output><jupyter_text>wandb.log() - https://docs.wandb.ai/library/log<jupyter_code>run.finish()<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup