예제 #1
0
def con_grad():
    eps = 0.001
    x = [0, 0, 0]
    x_prev = x.copy()
    k = 0
    d = [0, 0, 0]
    grad = gradient(x)

    table.add_row([k, x.copy(), function(x), norm(grad)])
    while norm(grad) >= eps:
        if k == 0:
            d[0] = -grad[0]
            d[1] = -grad[1]
            d[2] = -grad[2]
        else:
            b = norm(gradient(x))**2 / norm(gradient(x_prev))**2
            for i in range(3):
                d[i] = -grad[i] + b * d[i]
        t = mint(-10, 10, eps, x.copy())
        x_prev = x.copy()
        for i in range(3):
            x[i] = x[i] + t * d[i]
        grad = gradient(x)
        k = k + 1
        table.add_row([k, x.copy(), function(x), norm(grad)])
    print(table)
예제 #2
0
def method_newton():
    step = 0
    eps = 0.001
    grad = []        # значение градиента
    invert_h = [[0.174, 0.0449, -0.0112],        # обратная матрица гесса
         [0.0449, 0.27, -0.0674],
         [-0.0112, -0.0674, 0.517]]

    x0 = [0, 0, 0]          # начальное приближение
    x = [0, 0, 0]
    # ищем градиент от начального приближения
    grad = gradient(x0)
    table.add_row([step, x.copy(), function(x), norm(grad)])

    multi = matrix_multi(invert_h, grad)
    for i in range(3):
        x[i] = x0[i] - multi[i]
    step += 1
    grad = gradient(x)
    table.add_row([step, x, function(x), norm(grad)])
    while norm(gradient(x)) >= eps:
        x0 = x.copy()
        grad = gradient(x0)
        multi = matrix_multi(invert_h, grad)
        for i in range(3):
            x[i] = x0[i] - multi[i]
        step += 1
        table.add_row([step, x.copy(), function(x), norm(gradient(x))])
    print(table)
    return
예제 #3
0
파일: main_view.py 프로젝트: clopez26/PCS
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.shop_name_label.setText(_translate("MainWindow", "shop_name"))
        self.elements_grid.setSortingEnabled(True)
        __sortingEnabled = self.elements_grid.isSortingEnabled()
        self.elements_grid.setSortingEnabled(False)
        # item = self.elements_grid.item(0)
        # item.setText(_translate("MainWindow", "hola 3"))
        # item = self.elements_grid.item(1)
        # item.setText(_translate("MainWindow", "hola 4"))
        # item = self.elements_grid.item(2)
        # item.setText(_translate("MainWindow", "hola 5"))
        # item = self.elements_grid.item(3)
        # # item.setText(_translate("MainWindow", "hola1"))
        # item = self.elements_grid.item(4)
        # item.setText(_translate("MainWindow", "hola2"))
        self.elements_grid.setSortingEnabled(__sortingEnabled)
        item = self.cart_table.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.cart_table.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "item"))
        item = self.cart_table.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "cost"))
        self.check_out_button.setText(_translate("MainWindow", "Check out"))
        item = self.total_table.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.total_table.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "total_text"))
        item = self.total_table.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "total_value"))
        __sortingEnabled = self.total_table.isSortingEnabled()
        self.total_table.setSortingEnabled(False)
        item = self.total_table.item(0, 0)
        item.setText(_translate("MainWindow", "Total"))
        self.total_table.setSortingEnabled(__sortingEnabled)
        self.check_out_button_2.setText(_translate("MainWindow", "Report"))

        # ITEM EVENT ACTION
        self.elements_grid.itemClicked.connect(self.add_toCart)

        #USER CANT EDIT ITEM/COST HEADERS
        self.cart_table.setEditTriggers(
            QtWidgets.QAbstractItemView.NoEditTriggers)

        # BUTTON EVENTS
        self.check_out_button.clicked.connect(self.checkout)
        self.check_out_button_2.clicked.connect(self.report)

        # Give function an Instance of Main Window to have access to UI Elements
        FT.function().returnObj(self)
예제 #4
0
def fastest():
    eps = 0.001
    x = [0, 0, 0]
    step = 0
    grad = gradient(x)
    table.add_row([step, x, function(x), norm(grad)])

    while norm(grad) >= eps:
        t = mint(-10, 10, 0.01, x)
        for i in range(3):
            x[i] = x[i] - t * grad[i]
        step += 1
        grad = gradient(x)
        table.add_row([step, x, function(x), norm(grad)])
    print(table)
    return
예제 #5
0
 def __init__(self, n1, n2, f='RELU'):
     self.n1 = n1
     self.n2 = n2
     self.function = functions.function(f)
     self.step_size = 0.5
     self.decay_rate = 0.5
     self.strength = 0.5
예제 #6
0
def Nesterov_3_qv(x, epoch=100, epoch_N_G=100, h_N_G=0.001):

    L = func(x)

    f_line = []
    for i in range(epoch):

        f = func(x)
        F = function(x)
        jac = jacobian(function, x)[:, 0]
        #         print('x : {}'.format(x))
        #         print('f : {}'.format(f))
        #         print('jac : {}'.format(jac))
        #         print('hes : {}'.format(hes))

        x_k = torch.zeros_like(x)
        x_k.copy_(x)
        x_k = x_k.view(3, 1)

        func_Nes = lambda y: 1 / (2 * f) * (f**2 + (
            (F + jac.mm(y - x_k))**2).sum()) + L / 2 * ((y - x_k)**2).sum()

        #         print('1 : {} {}'.format(x_k, func_Nes(x_k)))
        #         print('2 : {} {}'.format(x, func_Nes(x)))
        x, _ = Newton_for_Nesterov(x, func_Nes, epoch=epoch_N_G, h=h_N_G)
        #         print('3 : {} {}'.format(x_k, func_Nes(x_k)))
        #         print('4 : {} {}'.format(x, func_Nes(x)))
        print(x, end='\r')
        f_line.append(f)

    return x, f_line
예제 #7
0
파일: main_view.py 프로젝트: clopez26/PCS
    def guiMain(self):
        import sys
        global app
        global ui
        global MainWindow
        global headerText
        global bodyText
        global footerText

        headerText = ""
        bodyText = ""
        footerText = ""
        # global FT
        app = QtWidgets.QApplication(sys.argv)
        MainWindow = QtWidgets.QMainWindow()
        # ui = Ui_MainWindow()
        self.setupUi(MainWindow)

        # Adding items
        item = store_item.makeItem("jamonilla.jpg", "jamonilla", "food", 2.15)
        self.addElement(item)
        item = store_item.makeItem("rice.jpg", "rice", "food", 5.14)
        self.addElement(item)
        item = store_item.makeItem("coke.jpg", "coke", "food", 1.00)
        self.addElement(item)
        # item = store_item.makeItem("papa.png", "papa", "food", 1.15)
        # ui.addElement(item)

        # MainWindow.show()
        # app.exec_()
        # sys.exit(app.exec_())
        return FT.function()
예제 #8
0
def mod_Newton(x, epoch=1000, epoch_N_G=100, h_N_G=0.001):

    L = func(x)
    n = x.shape[0]
    E = torch.eye(n, n, dtype=torch.float32)

    f_line = [func(x)]
    for i in range(epoch):

        F = function(x)
        F_T = F.transpose(0, 1)
        jac = jacobian(function, x)[:, 0]
        jac_T = jac.transpose(0, 1)

        #         print(F)
        #         print()
        #         print(F_T)
        #         print()
        #         print(jac)
        #         print()
        #         print(jac_T)
        #         print()

        l = torch.tensor(1, dtype=torch.float32)

        def func_Nes(l):

            A = (E * l + jac.mm(jac_T) / L).inverse()

            return l / 2 + (A.mm(F) * F).sum() / 2

        l, line = Newton_for_Newton(l, func_Nes, epoch=epoch_N_G, h=h_N_G)
        #         return line
        #print(l, end='\r') # lambda для двойственной задачи

        B = (E * l + jac.mm(jac_T) / L).inverse()
        h = -1 / L * jac_T.mm(B).mm(F)[:, 0]

        #         print(B)
        #         print()
        #         print(jac_T)
        #         print()
        #         print(F)
        #         print()
        #         print(h, end='\r')
        #         print()

        print(x, end='\r')

        x += h

        f_line.append(func(x))

    return x, f_line
예제 #9
0
def gauss_seidel():
    n = 3
    eps = 0.001
    e = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    x = [0, 0, 0]
    j = 0
    table.add_row([j, x.copy(), function(x), norm(gradient(x))])
    while True:
        k = 0
        print(x)
        while k <= n - 1:
            grad = gradient(x)
            if norm(grad) < eps:
                print(table)
                return
            else:
                t = mint(-10, 10, eps, x.copy())
                for i in range(3):
                    x[i] = x[i] - t * derivatives(x,k)*e[k][i]
                k = k + 1 
        j = j + 1
        table.add_row([j, x.copy(), function(x), norm(gradient(x))])
예제 #10
0
파일: main_view.py 프로젝트: clopez26/PCS
    def delete_fromCart(self):
        global cart_list
        try:
            index = self.cart_table.currentRow()
            item_to_delete = self.cart_table.item(index, 0).text()
            # print(("item to del %s",item_to_delete))
            # cart_list.remove((item_to_delete))
            for i in range(0,
                           self.cart_table.rowCount() -
                           1):  # DELETE FROM LIST TOO
                # print(i)
                # print(self.cart_table.rowCount())
                # print(cart_list[i].name)
                if (cart_list[i].name == item_to_delete):
                    #   print("popping %s", cart_list[i].name)
                    cart_list.pop(i)
                    break

            FT.function().deleteItem(index + 1)

        except:
            # print("Oops! Selected Wrong Item")
            pass
예제 #11
0
def droblenie():
    eps = 0.001
    c = 0.25
    x = [0, 0, 0]
    x_new = x.copy()
    step = 0
    t = 2
    grad = gradient(x)
    table.add_row([step, x.copy(), function(x), norm(grad)])

    while norm(grad) >= eps:
        for i in range(3):
            x_new[i] = x[i] - t * grad[i]
        while function(x_new) >= function(x):
            t = c * t
            for i in range(3):
                x_new[i] = x[i] - t * grad[i]
        step += 1
        grad = gradient(x_new)
        x = x_new.copy()
        table.add_row([step, x.copy(), function(x), norm(grad)])
    print(table)
    return
예제 #12
0
    def create_function(self, parent, cur):
        """
Create function (not main)

| Structure:
|   Func
|   | Declares
|   | Returns
|   | Params
|   | <code block>

Args:
    parent (Funcs): Reference to parent node
    cur (int): position where function is identified

Returns:
    int: position where function ends

See also:
    :py:func:`matlab2cpp.tree.functions.function`
    """
        assert isinstance(parent, mc.collection.Funcs)
        return functions.function(self, parent, cur)
예제 #13
0
    def create_function(self, parent, cur):
        """
Create function (not main)

| Structure:
|   Func
|   | Declares
|   | Returns
|   | Params
|   | <code block>

Args:
    parent (Funcs): Reference to parent node
    cur (int): position where function is identified

Returns:
    int: position where function ends

See also:
    :py:func:`matlab2cpp.tree.functions.function`
    """
        assert isinstance(parent, mc.collection.Funcs)
        return functions.function(self, parent, cur)
예제 #14
0
def run_simple():
    functionl = list()
    sum_ = functions.function('sum',
                              'int',
                              parameters=[('int', 'x'), ('int', 'y')],
                              line=1)
    functionl.append(sum_)
    env = environment.environment(-1)

    env.dec_variable('a', 'int')
    env.dec_variable('b', 'int')
    env.set_variable('a', 7)
    env.set_variable('b', 15)
    env.dec_variable('c', 'int')

    # function call
    env = env.new_env()
    param1, _ = env.find_name('a')
    param2, _ = env.find_name('b')
    env.dec_variable('a', 'int')
    env.dec_variable('b', 'int')
    env.set_variable('a', param1.value)
    env.set_variable('b', param2.value)
    env.set_return_to_name('c')
    print(env)
    # return here
    env = env.return_func(
        env.find_name('a')[0].value + env.find_name('b')[0].value)

    print(env.find_name('c')[0].value)
    env.set_variable('c', 8)
    env.set_variable('c', 9)
    env.trace_name('c')
    env.return_func(0)

    print('\n' + str(env))
def getNextState(state):
    nextstate = function(state)
    return nextstate
예제 #16
0
    '하는', '뭐', '약', '곳', '층', '해', '날', '맛', '존', '앞', '핫', '때', '내', '넌', '것',
    '요', '거', '린', '위', '저', '탑', '또', '된', '잘'
]

steps = [True, True]  #0 : 수집, 1 : 워드클라우드

if steps[0]:
    options = webdriver.ChromeOptions()
    # options.add_argument('headless')
    options.add_argument('window-size=1920x1080')
    # options.add_argument('disable-gpu')

    driver = webdriver.Chrome('./chromedriver', chrome_options=options)
    action = webdriver.common.action_chains.ActionChains(driver)

    f = functions.function(driver)
    blog_search_address = 'https://search.naver.com/search.naver?where=post&sm=tab_jum&query='

    file = open(keyword + ".txt", 'w', encoding='utf-8-sig')
    cnt = 0

    #시작!!
    driver.get(blog_search_address + keyword)
    for page in range(30):
        for i in range(1, 11):
            title = driver.find_element_by_xpath(
                "//ul[@id='elThumbnailResultArea']/li[@id='sp_blog_" + str(i) +
                "']/dl/dt/a").get_attribute('title')
            ispass = f.pass_auction_article(title)
            if ispass:
                continue
예제 #17
0
파일: main_view.py 프로젝트: clopez26/PCS
 def add_toCart(self, item):
     item_to_send = item.data(QtCore.Qt.UserRole)
     print(str(item.data(QtCore.Qt.UserRole)))
     FT.function().addtoCart(self, item_to_send)
예제 #18
0
파일: main_view.py 프로젝트: clopez26/PCS
 def report(self):
     FT.function().report()
예제 #19
0
L = 1.
h = 1e-1
optimizer = NTS([x],
                function,
                lr=1e-2,
                L=1,
                epoch=100,
                adaptive_L=True,
                adaptive_lr=True)
while eps > 1e-6:

    #print(i)
    #print('' * 100, end='\r')
    print(' ' * 30,
          x,
          eps,
          optimizer.defaults['L'],
          optimizer.defaults['lr'],
          end='\r')

    with t.no_grad():
        x_last.copy_(x)

    optimizer.zero_grad()
    optimizer.step()

    eps = ((x - x_last)**2).sqrt().mean()

print(x)
print((function(x)**2).sum())
예제 #20
0
# Import all the contents of the classes file
import classes as classfile

# Import the listed contents from functions file
from functions import function, number

# Only run if the file is being run directly
if __name__ == "__main__":
    print("Function only run if file is run directly from this file.")
    print("E.g. python main.py")

    print(function())

    print(number(1))
예제 #21
0
 def __init__(self, f='LINEAR'):
     self.activation = 0
     self.inputs = []
     self.function = functions.function(f)
예제 #22
0
 def __init__(self, f='LINEAR'):
     self.activation = 0
     self.update = 0
     self.inputs = 0
     self.activation_function = functions.function(f)
예제 #23
0
precedence = (
    ('left', 'PLUS', 'MINUS'),
    ('left', 'TIMES', 'DIVIDE'),
    ('right', 'UMINUS'),
)

# dictionary of functions
funcs = {}
# test function
functionl = {}
sum_ = functions.function('sum',
                          'int',
                          parameters=[{
                              'type': 'int',
                              'name': 'x'
                          }, {
                              'type': 'int',
                              'name': 'y'
                          }],
                          line=17)
functionl['sum'] = sum_

next_line = 0
increments = {}
env = environment.environment(-1, name='main')


def function_call(func, params=None, ret=-1):
    global env
    if params is None:
        if func.num == 0:
예제 #24
0
 def __init__(self, f='LINEAR'):
     self.activation = 0
     self.activation_function = functions.function(f)
예제 #25
0
파일: main.py 프로젝트: cnrooofx/CS1117
def main():
    functions.function()