vlab-kaist / NN101_23S

MIT License
6 stars 7 forks source link

[LAB] Week 2_Problem 2_이찬솔 #81

Closed Nucobi closed 1 year ago

Nucobi commented 1 year ago

Problem

Week 2_Problem 2

Source Code

import torch
from random import random
from typing import Callable, List, Tuple

##                         Problem 2                          ##
##                                                            ##
##            Arbitary x_train, y_train are given.            ##
##     In this problem, x_train is List of List of float.     ##
##   Suppose that x and y have linear correlation, y=wx+b.    ##
##           (In this problem, w will be a vector.)           ##
##     In function training(), you should return [w, b].      ##
##          In function predict(), you should return          ##
##            List y_test corresponding to x_test.            ##
##                  Made by @jangyoujin0917                   ##
##                                                            ##

# NOTE : Feel free to use torch.optim and tensor.

def training(x_train: List[List[float]], y_train: List[float]) -> Tuple[
    List[float], float]:  # DO NOT MODIFY FUNCTION NAME
    # data normalization
    # 1. Prevents overflow when calculating MSE
    # 2. Prevents underfitting
    # Note that you need to convert [w, b] to the original scale.
    # w = w * (y_max - y_min)
    # b = b * (y_max - y_min) + y_min
    y_min = min(y_train)
    y_max = max(y_train)
    normalize = lambda y: (y - y_min) / (y_max - y_min)

    ### IMPLEMENT FROM HERE
    def tensors(x):
        return
    def returnTensor(train: List[float]):
        return torch.FloatTensor([[n] for n in train])

    y_train = [normalize(_) for _ in y_train] # normalize

    x_tensor = torch.FloatTensor(x_train)
    y_tensor = torch.FloatTensor(y_train)

    w = torch.tensor([[0. for _ in range(len(x_train[0]))] for _ in range(len(x_train))],requires_grad=True)
    b = torch.zeros(1, requires_grad=True)

    optimizer = torch.optim.Adam([w, b], lr=0.0065)

    epoch = 1000
    for _ in range(epoch):
        h = w @ torch.transpose(x_tensor,0,1) + b
        loss = torch.mean((h - y_tensor) ** 2)

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

        # if ((_+1)%100==0): print(f"Epoch: {_+1}/{epoch} - w:{w},b:{b} , loss: {loss}")
    W = [_.item()*(y_max - y_min) for _ in list(w)[0]]
    B = b.item() * (y_max - y_min) + y_min
    return [W,B]

def predict(x_train: List[List[float]], y_train: List[float], x_test: List[List[float]]) -> List[
    float]:  # DO NOT MODIFY FUNCTION NAME
    ### IMPLEMENT FROM HERE
    W, B = training(x_train, y_train)
    result = []
    for element in x_test:
        val = 0
        for i in range(len(element)):
            val += W[i]*element[i]
        val += B
        result.append(val)
    return result

if __name__ == "__main__":
    x_train = [[0., 1.], [1., 0.], [2., 2.], [3., 1.], [4., 3.]]
    y_train = [3., 2., 7., 6., 11.]  # y = x_0 + 2*x_1 + 1 # Note that not all test cases give clear line.
    x_test = [[5., 3.], [10., 6.], [8., 9.]]

    w, b = training(x_train, y_train)
    y_test = predict(x_train, y_train, x_test)

    print(w, b)
    print(y_test)

Description

asdf

Output (Optional)

[1.0000237450003624, 1.9999630004167557] 1.0000030770897865 [12.000010803341866, 23.000018529593945, 26.999860040843487]

github-actions[bot] commented 1 year ago

This is an auto-generated grading output. Your code failed to run. Please check again.

github-actions[bot] commented 1 year ago

This is an auto-generated grading output. Your code failed to run. Please check again.

github-actions[bot] commented 1 year ago

This is an auto-generated grading output. Your code failed to run. Please check again.

github-actions[bot] commented 1 year ago

This is an auto-generated grading output. Checking code of Nucobi Timeout reached for Nucobi {'Nucobi': 'timed_out'}

github-actions[bot] commented 1 year ago

This is an auto-generated grading output. Checking code of Nucobi Timeout reached for Nucobi {'Nucobi': 'timed_out'}

github-actions[bot] commented 1 year ago

This is an auto-generated grading output. Checking code of Nucobi {'Nucobi': nan}

github-actions[bot] commented 1 year ago

This is an auto-generated grading output. Checking code of Nucobi {'Nucobi': 40.9}

github-actions[bot] commented 1 year ago

This is an auto-generated grading output. Checking code of Nucobi {'Nucobi': 71.3}