Commit 1c00fcc1 authored by Zhangkai Wu's avatar Zhangkai Wu
Browse files

上传新文件

parent 7ab4e8fc
Loading
Loading
Loading
Loading
+99 −0
Original line number Diff line number Diff line
%% Cell type:code id:0353a0f2-0e5d-42a5-90b5-a262f5d5092a tags:

``` python
# NOTE:
# You may choose to use ChatGPT (or any AI-based tool) to assist with your assignment,
# but you must ensure that you fully understand the entire code.
# You are solely responsible for the work you submit.
# Please keep in mind: ChatGPT will not be available during the exam.
```

%% Cell type:code id:5a35312f tags:

``` python
import pandas
import torch
import torch.nn as nn
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from torch.autograd import Variable
```

%% Cell type:code id:0476b663 tags:

``` python
class Model(nn.Module):
    def __init__(self, input_features, hidden_layer1, hidden_layer2, output_features):
        super().__init__()
        self.fc1 = nn.Sequential(
            nn.Linear(input_features, hidden_layer1),
            nn.ReLU(inplace=True))
        self.fc2 = nn.Sequential(
            nn.Linear(hidden_layer1, hidden_layer2),
            nn.ReLU(inplace=True))
        self.out = nn.Sequential(
            nn.Linear(hidden_layer2, output_features),
            nn.ReLU(inplace=True))

    def forward(self, x):
        x = self.fc1(x)
        x = self.fc2(x)
        x = self.out(x)
        return x
```

%% Cell type:code id:9d320459 tags:

``` python
if __name__ == "__main__":
    # Main function of script
    dataset = pandas.read_csv("./iris.data.csv", header=None)
    # NOTE: Replace with the correct path to the iris.data.csv file on your system

    dataset.iloc[:, 4] = dataset.iloc[:, 4].astype('category')
    cat_columns = dataset.select_dtypes(['category']).columns
    dataset[cat_columns] = dataset[cat_columns].apply(lambda x: x.cat.codes)

    X = dataset.iloc[:, :4]
    y = dataset.iloc[:, 4]

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    X_train = Variable(torch.from_numpy(X_train.to_numpy())).float()
    y_train = Variable(torch.from_numpy(y_train.to_numpy())).long()
    X_test = Variable(torch.from_numpy(X_test.to_numpy())).float()
    y_test = Variable(torch.from_numpy(y_test.to_numpy())).long()

    model = Model(input_features=X_train.shape[1], hidden_layer1=10, hidden_layer2=20, output_features=3)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
    loss_fn = nn.CrossEntropyLoss()

    # Training
    epochs = 1000
    losses = []

    for i in range(epochs):
        y_pred = model.forward(X_train)
        loss = loss_fn(y_pred, y_train)
        losses.append(loss)
        print(f'epoch: {i:2}  loss: {loss.item():10.8f}')

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    # Testing
    preds = []
    with torch.no_grad():
        for val in X_test:
            y_hat = model.forward(val)
            preds.append(y_hat.argmax().item())

    acc_test = accuracy_score(y_test, preds)
    print("Test set accuracy: {:.2f}".format(acc_test))
```

%% Cell type:code id:e597c1b8-2db9-4147-acf3-868a934b169f tags:

``` python
```