Пример #1
0
def train(x_origin, y, c, count):
    g = 0.8
    l = len(x_origin[0])
    x = [numpy.append(i, [1.]) for i in x_origin]
    ew1 = utils.random_array(l + 1, c)
    ew2 = utils.random_array(c + 1, 1)
    for times in range(count):
        dew1 = [numpy.zeros(c) for tmp in range(l + 1)]
        dew2 = [0 for tmp in range(c + 1)]
        for t in range(len(x)):
            active1 = activate(function(ew1, x[t]))
            active1 = numpy.append(active1, 1.0)
            active2 = activate(function(ew2, active1))
            d2 = -active2[0] * (1. - active2[0]) * (active2[0] -
                                                    (y[t] + 1.) / 2.)
            d1 = [
                active1[i] * (1. - active1[i]) * ew2[i][0] * d2
                for i in range(c)
            ]
            for i in range(c + 1):
                dew2[i] += g * active1[i] * d2
            for k in range(l + 1):
                for j in range(c):
                    dew1[k][j] += g * x[t][k] * d1[j]
        for i in range(c + 1):
            ew2[i][0] += dew2[i]
        for i in range(l + 1):
            for j in range(c):
                ew1[i][j] += dew1[i][j]
    return ew1, ew2
Пример #2
0
def train(x_origin, y, c, count):
    g = 0.8
    l = len(x_origin[0])
    x = [numpy.append(i, [1.]) for i in x_origin]
    ew1 = utils.random_array(l + 1, c)
    ew2 = utils.random_array(c + 1, 1)
    for times in range(count):
        dew1 = [numpy.zeros(c) for tmp in range(l + 1)]
        dew2 = [0 for tmp in range(c + 1)]
        for t in range(len(x)):
            active1 = activate(function(ew1, x[t]))
            active1 = numpy.append(active1, 1.0)
            active2 = activate(function(ew2, active1))
            d2 = -active2[0] * (1. - active2[0]) * (active2[0] - (y[t] + 1.) / 2.)
            d1 = [active1[i] * (1. - active1[i]) * ew2[i][0] * d2 for i in range(c)]
            for i in range(c + 1):
                dew2[i] += g * active1[i] * d2
            for k in range(l + 1):
                for j in range(c):
                    dew1[k][j] += g * x[t][k] * d1[j]
        for i in range(c + 1):
            ew2[i][0] += dew2[i]
        for i in range(l + 1):
            for j in range(c):
                ew1[i][j] += dew1[i][j]
    return ew1, ew2
Пример #3
0
def run(n_alternatives, n_criteria, output_file):

    # preference functions to be considered
    preference_functions = [
        'usual', 'quasi-criterion', 'linear', 'gaussian', 'level',
        'linear_with_indifference'
    ]

    input_mat = utils.random_matrix(n_criteria, n_alternatives)

    input_weight = utils.random_array(n_criteria)

    input_preference = [
        preference_functions[random.randint(0, 5)] for x in range(n_criteria)
    ]
    input_param = {
        'p': utils.random_number(),
        'q': utils.random_number(),
        'sigma': utils.random_number()
    }
    if input_param['p'] < input_param['q']:
        input_param['p'], input_param['q'] = input_param['q'], input_param['p']
    algorithmPromethee = Promethee(input_mat, input_weight, input_preference,
                                   input_param)

    utils.write_table_to_csv(algorithmPromethee.getPairwiseComparisonMatrix(),
                             output_file)
Пример #4
0
def dataGen(size: int = 100, theta: float = 0.):
    """
    Returns position, cost, vx[0], vxx[1]
    """

    x = random_array(size)
    y = []
    vx = []
    vxx = []

    for state in x:
        ddp = solve_crocoddyl(state)
        y.append([ddp.cost])

        vx_ = np.array(ddp.Vx)
        vx.append(vx_[0])

        vxx_ = np.array(ddp.Vxx)
        vxx.append(vxx_[0])

    start = torch.tensor(x, dtype=torch.float32)
    cost = torch.tensor(y, dtype=torch.float32)
    grad1 = torch.tensor(vx, dtype=torch.float32)
    grad2 = torch.tensor(vxx, dtype=torch.float32)
    del ddp, x, y, vx, vxx
    return start, cost, grad1, grad2
Пример #5
0
def template(func, name, size):
    a = random_array(size)
    aback = list(a)
    expected = sorted(a)
    t1 = time.time()
    func(a)
    t2 = time.time()
    if str(expected) == str(a):
        t = t2 - t1
        return (True, t)
    else:
        s = 'failed: {}\nbefore: ({})\nafter : ({})'.format(name, aback, a)
        print(s)
        return (False, 0)
Пример #6
0
def template(func, name, size):
    a = random_array(size)
    aback = list(a)
    expected = sorted(a)
    t1 = time.time()
    func(a)
    t2 = time.time()
    if str(expected) == str(a):
        t = t2 - t1
        return (True, t)
    else:
        s = 'failed: {}\nbefore: ({})\nafter : ({})'.format(name, aback, a)
        print(s)
        return (False, 0)
Пример #7
0
def main():

    print('hello')

    size_tuple = (3, 2)

    print(utils.random_array(size_tuple))

    csv_path = 'MOCK_DATA.csv'

    csv_path = resource_path(csv_path)

    print("Reading data from %s" % csv_path)

    print(utils.read_csv_data(csv_path)[:5])
Пример #8
0
def dataGen(size: int = 100, theta: float = 0.):
    """
    Returns position and cost
    """

    x = random_array(size)
    y = []

    for state in x:
        ddp = solve_crocoddyl(state)
        y.append([ddp.cost])

    positions = torch.tensor(x, dtype=torch.float32)
    cost = torch.tensor(y, dtype=torch.float32)
    del ddp, x, y
    return positions, cost
Пример #9
0
def main():

    print('hello')

    size_tuple = (3, 2)

    print(utils.random_array(size_tuple))

    csv_files = ('MOCK_DATA.csv', 'MOCK_DATA2.csv')

    csv_paths = [os.path.join('data', X) for X in csv_files]

    csv_paths = [resource_path(X) for X in csv_paths]

    for csv_path in csv_paths:

        print("Reading data from %s" % csv_path)

        print(utils.read_csv_data(csv_path)[:5])
Пример #10
0
from utils import test, random_array, swap


def my_min(arr):
    mini = 0
    for x in xrange(1, len(arr)):
        if arr[x] < arr[mini]:
            mini = x
    return mini


#selection sort. finds the minimum and exchanges it with the current minimum
def selection_sort(arr):
    for x in xrange(0, len(arr)):
        mini = x
        for y in xrange(x, len(arr)):
            if arr[y] < arr[mini]:
                mini = y
        swap(arr, x, mini)

    return arr


if __name__ == "__main__":
    sortedarr = selection_sort(random_array(10))
    print(sortedarr)
    print(test(sortedarr))
Пример #11
0
from utils import test, random_array, swap


#divides array into subarrays until size 1, then merges until back to original array, sorted
def merge(a, b):
    arr = []
    while a and b:
        if a[0] < b[0]:
            arr.append(a.pop(0))
        else:
            arr.append(b.pop(0))

    #one of these arrays are empty now
    arr = arr + a + b
    return arr


def merge_sort(arr):
    if len(arr) == 1:
        return arr
    middle = len(arr) / 2
    left = merge_sort(arr[:middle])
    right = merge_sort(arr[middle:])
    return merge(left, right)


if __name__ == "__main__":
    sortedarr = merge_sort(random_array(10))
    print(sortedarr)
    print(test(sortedarr))
Пример #12
0
from utils import random_array


def partition(array, start, end):
    r = start - 1  # the last element that is smaller than key
    key = array[end]
    for i in range(start, end):  # find out all the elements that are smaller than key and swap them before key
        if array[i] < key:
            array[r + 1], array[i] = array[i], array[r + 1]  # swap the smaller element to r+1 position
            r += 1  # r+1 position is now smaller than key, update r
    array[r + 1], array[end] = array[end], array[r + 1]  # last swap
    return r + 1


def qsort(array, start, end):
    if start >= end:
        return
    p = partition(array, start, end)
    qsort(array, start, p - 1)
    qsort(array, p + 1, end)


if __name__ == "__main__":
    array = random_array(10)
    qsort(array, 0, len(array) - 1)
    print array
Пример #13
0

def get_digit(d, n, base=10):
    for i in range(n):
        d /= base
    return d % base


def radixSort(array, base=10):
    buckets = [[] for _ in range(base)]
    n = get_total_digit_num(max(array))
    for i in range(n):  # n times distribute and collect and then the array will be in order.
        # distribute data to buckets
        for item in array:
            index = get_digit(item, i)
            buckets[index].append(item)
        # collect data from buckets
        count = 0
        for bucket in buckets:
            for item in bucket:
                array[count] = item
                count += 1
        buckets = [[] for _ in range(base)]


if __name__ == "__main__":
    array = random_array(20)
    print "before:", array
    radixSort(array)
    print "after:", array
Пример #14
0
def partition(arr, low, high):
    pivotIndex = low
    low = low + 1

    for x in xrange(low, high + 1):
        if arr[x] < arr[pivotIndex]:
            swap(arr, x, low)
            low = low + 1

    swap(arr, pivotIndex, low - 1)

    return low - 1


def quick_sort(arr):
    quick_sort_helper(arr, 0, len(arr) - 1)
    return arr


def quick_sort_helper(arr, low, high):
    if low < high:
        pivotIndex = partition(arr, low, high)
        quick_sort_helper(arr, low, pivotIndex - 1)
        quick_sort_helper(arr, pivotIndex + 1, high)


if __name__ == "__main__":
    sortedarr = quick_sort(random_array(10))
    print(sortedarr)
    print(test(sortedarr))
Пример #15
0
from utils import test, random_array, swap


#bubble sort. runs through over and over until all is well
def bubble_sort(arr):
    in_order = False
    while not in_order:
        in_order = True
        for x in xrange(0, len(arr) - 1):
            if arr[x] > arr[x + 1]:
                swap(arr, x, x + 1)
                in_order = False

    return arr


if __name__ == "__main__":
    sortedarr = bubble_sort(random_array(10))
    print(sortedarr)
    print(test(sortedarr))
Пример #16
0
def get_digit(d, n, base=10):
    for i in range(n):
        d /= base
    return d % base


def radixSort(array, base=10):
    buckets = [[] for _ in range(base)]
    n = get_total_digit_num(max(array))
    for i in range(
            n
    ):  # n times distribute and collect and then the array will be in order.
        # distribute data to buckets
        for item in array:
            index = get_digit(item, i)
            buckets[index].append(item)
        # collect data from buckets
        count = 0
        for bucket in buckets:
            for item in bucket:
                array[count] = item
                count += 1
        buckets = [[] for _ in range(base)]


if __name__ == "__main__":
    array = random_array(20)
    print "before:", array
    radixSort(array)
    print "after:", array
Пример #17
0
import utils

#my implementation of insertion sort
#insertion sort works by iterating and inserting the values in their correct spots


def insertion_sort(arr):
    for n in xrange(1, len(arr)):
        for m in xrange(n, 0, -1):
            if arr[m] < arr[m - 1]:
                utils.swap(arr, m, m - 1)
            else:
                break
    return arr


if __name__ == "__main__":
    sortedarr = insertion_sort(utils.random_array(10))
    print(utils.test(sortedarr))