vlab-kaist / NN101_23S

MIT License
6 stars 7 forks source link

[LAB] Week 1_Problem 2_Yungeun Song #46

Closed Diiligent closed 1 year ago

Diiligent commented 1 year ago

Problem

Week 1_Problem 2

Source Code

import torch
from random import random 
from typing import Callable

##                        Problem 2                           ##
##                                                            ##
##           Arbitrary quartic function will be given.        ##
## Return the optimal point(global minimum) of given function ##
##          Condition: highest order term is positive         ##
##                  Made by @jangyoujin0917                   ##
##                                                            ##

def solution(func: Callable, start_point: float): # DO NOT MODIFY FUNCTION NAME    
    ### IMPLEMENT FROM HERE

    x = torch.tensor([start_point], dtype=torch.float, requires_grad=True)

    step_num = 10000
    lr = 1e-3

    velocity = torch.Tensor([0.5])
    beta = 0.98
    grad = torch.tensor([1.0] * 1)
    for i in range(step_num):
        z = func(x)
        z.backward(grad, retain_graph=True)
        velocity = beta * velocity - lr*x.grad.data 
        x.data += velocity
        #x.data -= lr*x.grad.data
        x.grad.data.zero_()
    return(float(x))

if __name__ == "__main__":
    def test_func(x): # function for testing;function for evaluation will be different.
        return x**4 - 5*x**3 + 6*x**2
    t = torch.tensor([0], requires_grad=True, dtype=torch.float32)
    print(solution(test_func, t))

Description

Beta = 0.98

Output (Optional)

No response

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 youngandtherich {'youngandtherich': 0.0}

github-actions[bot] commented 1 year ago

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