Exemplo n.º 1
0
def add_n_elements_delete_half_random(n):
    # Don't time initialization
    big_arr = array(n)
    small_arr = array(1)
    node = ListNode(1)
    dll = DoublyLinkedList(node)

    # Experiment with this.
    # How does higher or lower change things?
    divisor = 10

    # Array size N
    start = timer()
    for i in range(n):
        array_append(big_arr, random.randrange(n / divisor))

    for i in range(int(n / 2)):
        array_remove(big_arr, random.randrange(n / divisor))

    time = timer() - start
    print("Size N Array: Appended " + str(n) +
          " elements and removed half in " + str(time))

    # Array size 1 (To start)
    start = timer()
    for i in range(n):
        array_append(small_arr, random.randrange(int(n / divisor)))

    for i in range(int(n / 2)):
        array_remove(small_arr, random.randrange(int(n / divisor)))

    time = timer() - start
    print("Size 1 Array: Appended " + str(n) +
          " elements and removed half in " + str(time))

    # Linked List - Head
    start = timer()
    for i in range(n):
        dll.add_to_head(random.randrange(int(n / divisor)))

    for i in range(int(n / 2)):
        dll.find_and_delete(random.randrange(int(n / divisor)))

    time = timer() - start
    print("Linked Head: Added " + str(n) + " elements and removed half in " +
          str(time))

    # Linked List - Tail
    start = timer()
    for i in range(n):
        dll.add_to_tail(random.randrange(int(n / divisor)))

    for i in range(int(n / 2)):
        dll.find_and_delete(random.randrange(int(n / divisor)))

    time = timer() - start
    print("Linked Tail: Added " + str(n) + " elements and removed half in " +
          str(time))
Exemplo n.º 2
0
def add_n_elements(n):
    # Don't time initialization
    big_arr = array(n)
    small_arr = array(1)
    node = ListNode(1)
    dll = DoublyLinkedList(node)

    # Array size N
    start = timer()
    for i in range(n):
        array_append(big_arr, "value")

    time = timer() - start
    print("Size N Array: Appended " + str(n) + " elements in " + str(time))

    # Array size 1 (To start)
    start = timer()
    for i in range(n):
        array_append(small_arr, "value")

    time = timer() - start
    print("Size 1 Array: Appended " + str(n) + " elements in " + str(time))

    # Linked List - Head
    start = timer()
    for i in range(n):
        dll.add_to_head("value")

    time = timer() - start
    print("Linked Head: Added " + str(n) + " elements in " + str(time))

    # Linked List - Tail
    start = timer()
    for i in range(n):
        dll.add_to_tail("value")

    time = timer() - start
    print("Linked Tail: Added " + str(n) + " elements in " + str(time))
Exemplo n.º 3
0
import arrays as np

data = np.array([[1, 1, 0.3], [1, 0.4, 0.5], [0, 0.7, 0.8]])
print(data)

y = np.copy(data[:, 0])
print(y)

data[:, 0] = 1
X = data
print(X)

b = (np.linalg.inv(X.T.dot(X)).dot(X.T)).dot(y)
print(b)

c = map(str, b)  # применяет функцию str к каждому элементу array
print(
    " ".join(c)
)  # возвращает строку, состоящую из элементов array, разделённых символами "delim"

delta_w = (y - y_h) * x
Exemplo n.º 4
0
        """
        i = 0
        errors = 1
        while errors and i < max_steps:
            i += 1
            errors = 0
            for example, answer in zip(input_matrix, y):
                example = example.reshape((example.size, 1))
                error = self.train_on_single_example(example, answer)
                errors += int(error)  # int(True) = 1, int(False) = 0, так что можно не делать if


w = np.random.randint(1, 10, (2, 1))
b = random.randint(1, 10)
neuron1 = Perceptron(w, b)
examples = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
y = np.array([0, 1, 1, 1])[:, np.newaxis]
neuron1.train_until_convergence(examples, y)

w = np.random.randint(1, 10, (2, 1))
b = random.randint(1, 10)
neuron2 = Perceptron(w, b)
y = np.array([1, 1, 1, 0])[:, np.newaxis]
neuron2.train_until_convergence(examples, y)

w = np.random.randint(1, 10, (2, 1))
b = random.randint(1, 10)
examples = np.array([[0, 1], [1, 1], [1, 0]])
neuron3 = Perceptron (w, b)
y = np.array([0, 1, 0])[:, np.newaxis]
neuron3.train_until_convergence(examples, y)
Exemplo n.º 5
0
import arrays as np

X = np.array([[1, 60], [1, 50], [1, 75]])
print(X)

y = np.array([[10], [7], [12]])
print(y)

c = X.T.dot(X)
print(c)

d = np.linalg.inv(c)
print(d)

e = d.dot(X.T)
print(e)

f = e.dot(y)
print(f)
     def __iter__(self):
        return Iteradorarreglo()

class Iteradorarreglo:

    def __init__(self, arr):
        self.__arr=arr
        self.__indice=0

    def __iter__(self):
        return self

    def __next__(self):
        if self.__indice<len(self.__arr):
            dato=self.__arr[self.__indice]
            self.__indice +=1
            return dato
        else:
            raise StopIteration
from arrays import array
algo=array(10)
print(algo.get_item(6363))
algo.set_item(553,3)
print(algo.get_item(3))
print(f"el arreglo tiene {algo.get_lenght()} elementos")
algo.clear(777)
print(algo.get_item(3))
print("------------")
for x in range(algo.get_lenght()):
    print(f"{x}-->{algo.get_item(x)}")
import arrays as np

a = np.array([[1, 2, 3], [4, 5, 6]])  # создаём массив
print(a)  # смотрим на массив
print(a.shape)  # смотрим на форму массива

b = np.array([1, 2, 3])
print(b)
print(b.shape)

d = np.array([[1], [2], [3]])
print(d)
print(d.shape)

c = np.array(1)
print(c)
print(c.shape)
Exemplo n.º 8
0
    )  # производная сигмоидальной функции, работает и с числами, и с векторами (поэлементно)


def max(x):  # функция максимума
    if x > 0: return x
    else: return 0


def max_prime(x):  # производная функции максимума
    if x > 0: return 1
    else: return 0


# задаем данные
weights0_1 = np.array([[0.7, 0.2, 0.7],
                       [0.8, 0.3,
                        0.6]])  # задаем матрицу весво между слоями 0 и 1
weights1_2 = np.array([[0.2, 0.4]])  # задаем матрицу весво между слоями 1 и 2
print("weights0_1\n", weights0_1, "\nweights1_2\n", weights1_2)

b1 = np.zeros((2, 1))
b2 = np.zeros((1, 1))

input_a = np.array([[0], [1], [1]])  # задаем вектор входных активаций
print("input_activations\n", input_a, input_a.shape)

y = np.ones((1, 1))  # задаем вектор правильных ответов
print("answer y\n", y, y.shape)

# прямое распространение активаций
z1 = np.dot(weights0_1, input_a) + b1
Exemplo n.º 9
0
import arrays as np
import math


def J_quadratic(a, y):  #квадратичная целевая функция
    # a - вектор входных активаций (n, 1)
    # y - вектор правильных ответов (n, 1)
    return 0.5 * np.mean((a - y)**2)  # Возвращает значение J (число)


def J_cross_entopy(a, y):  # кросс энтропийная целевая функция
    J = 0
    for i in range(len(a - 1)):
        J += (y[i] * ln(a[i]) + (1 - y[i]) * ln(1 - a[i]))
    return -1 * J / len(a)


def ln(x):
    if x == 0:
        return 0
    else:
        return math.log(x)


a = np.array([1, 0.3, 0.1])
y = np.array([1, 0, 0])

print(J_quadratic(a, y), J_cross_entopy(a, y))
Exemplo n.º 10
0
import time
import arrays as np
input_matrix = np.random.sample((4, 3))
print(input_matrix)
w = np.random.random((3, 1))
print(w)
b = 3

y = input_matrix.dot(w) + b
print(y > 0)

#####################################
mat = np.append(input_matrix, np.array([[1]] * input_matrix.shape[0]), axis=1)
weights = np.append(w, np.array([[b]]), axis=0)

print(mat.dot(weights) > 0)

#####################################
print(time.time())


#####################################
def sigmoid(x):
    """сигмоидальная функция, работает и с числами, и с векторами (поэлементно)"""
    return 1 / (1 + np.exp(-x))


print(sigmoid(w))