Пример #1
0
def simplex_step(A, b, c, R_square, show_bases=False):
    if show_bases: print("basis: ", R_square)
    R = A.D[0]
    # Extract the subsystem
    A_square = Mat((R_square, A.D[1]), {(r, c): A[r, c]
                                        for r, c in A.f if r in R_square})
    b_square = Vec(R_square, {k: b[k] for k in R_square})
    # Compute the current vertex
    x = solve(A_square, b_square)
    print("(value: ", c * x, ") ", end="")
    # Compute a possibly feasible dual solution
    y_square = solve(A_square.transpose(),
                     c)  #compute entries with labels in R_square
    y = Vec(R, y_square.f)  #Put in zero for the other entries
    if min(y.values()) >= -1e-10: return ('OPTIMUM', x)  #found optimum!
    R_leave = {i for i in R if y[i] < -1e-10}  #labels at which y is negative
    r_leave = min(R_leave,
                  key=hash)  #choose first label at which y is negative
    # Compute the direction to move
    d = Vec(R_square, {r_leave: 1})
    w = solve(A_square, d)
    # Compute how far to move
    Aw = A * w  # compute once because we use it many times
    R_enter = {r for r in R if Aw[r] < -1e-10}
    if len(R_enter) == 0: return ('UNBOUNDED', None)
    Ax = A * x  # compute once because we use it many times
    delta_dict = {r: (b[r] - Ax[r]) / (Aw[r]) for r in R_enter}
    delta = min(delta_dict.values())
    # Compute the new tight constraint
    r_enter = min({r for r in R_enter if delta_dict[r] == delta}, key=hash)[0]
    # Update the set representing the basis
    R_square.discard(r_leave)
    R_square.add(r_enter)
    return ('STEP', None)
Пример #2
0
def create_matrix_A_B():

	# Creating matrices A and B
	filename = "train_dataset.csv"
	file = open(filename,'r')

	labels = file.readline().split(',')

	labels = [label.strip() for label in labels]

	A = Mat((set(),set()) , {})

	row_labels_A = set();
	col_labels_A = set();

	f = {};

	for line in file:
		row = line.split(',')
		row = [row.strip() for row in row]
		user_id = row[0];
		song_id = row[1];
		target = row[5];
		if user_id not in row_labels_A:
			row_labels_A.add(user_id)
		if song_id not in col_labels_A:
			col_labels_A.add(song_id)

		f.update({(user_id,song_id):int(target)})

	A = Mat((row_labels_A,col_labels_A) , f)

	B = A.transpose()

	return (A,B)
Пример #3
0
def simplex_step(A, b, c, R_square, show_bases=False):
    if show_bases: print("basis: ", R_square)
    R = A.D[0]
    # Extract the subsystem
    A_square = Mat((R_square, A.D[1]), {(r,c):A[r,c] for r,c in A.f if r in R_square})
    b_square = Vec(R_square, {k:b[k] for k in R_square})
    # Compute the current vertex
    x = solve(A_square, b_square)
    print("(value: ",c*x,") ",end="")
    # Compute a possibly feasible dual solution
    y_square = solve(A_square.transpose(), c) #compute entries with labels in R_square
    y = Vec(R, y_square.f) #Put in zero for the other entries
    if min(y.values()) >= -1e-10: return ('OPTIMUM', x) #found optimum!
    R_leave = {i for i in R if y[i]< -1e-10} #labels at which y is negative
    r_leave = min(R_leave, key=hash) #choose first label at which y is negative
    # Compute the direction to move
    d = Vec(R_square, {r_leave:1})
    w = solve(A_square, d)
    # Compute how far to move
    Aw = A*w # compute once because we use it many times
    R_enter = {r for r in R if Aw[r] < -1e-10}
    if len(R_enter)==0: return ('UNBOUNDED', None)
    Ax = A*x # compute once because we use it many times
    delta_dict = {r:(b[r] - Ax[r])/(Aw[r]) for r in R_enter}
    delta = min(delta_dict.values())
    # Compute the new tight constraint
    r_enter = min({r for r in R_enter if delta_dict[r] == delta}, key=hash)[0]
    # Update the set representing the basis
    R_square.discard(r_leave)
    R_square.add(r_enter)
    return ('STEP', None)
Пример #4
0
def problem8_2():
    domain = ({'a','b'},{'A','B'})
    A = Mat(domain,{('a','A'):3, ('a','B'):1,('b','A'):4, ('b','B'):1})
    print(A)
    b = Vec(domain[0], {'a': 10, 'b': 13})
    print(b)
    x = QR_solve(A, b)
    print(x)
    print([x])
    result = A.transpose()*(b-A*x)
    print(result.is_almost_zero())
    print((b-A*x)*(b-A*x))
Пример #5
0
def problem7_1():
    domain = ({'a','b','c'},{'A','B'})
    A = Mat(domain,{('a','A'):8, ('a','B'):1,('b','A'):6, ('b','B'):2,('c','A'):0,('c','B'):6})
    print(A)
    b = Vec(domain[0], {'a': 10, 'b': 8, 'c': 6})
    print(b)
    x = QR_solve(A, b)
    print(x)
    print([x])
    result = A.transpose()*(b-A*x)
    print(result.is_almost_zero())
    print((b-A*x)*(b-A*x))
Пример #6
0
def problem6():
    domain = ({'a','b','c'},{'A','B'})
    A = Mat(domain,{('a','A'):-1, ('a','B'):2,('b','A'):5, ('b','B'):3,('c','A'):1,('c','B'):-2})
    print(A)
    Q, R = QR_factor(A)
    print(Q)
    print(R)
    b = Vec(domain[0], {'a': 1, 'b': -1})
    x = QR_solve(A, b)
    print(x)
    print([x])
    result = A.transpose()*(b-A*x)
    print(result.is_almost_zero())
Пример #7
0
for line in file:
	row = line.split(',')
	row = [row.strip() for row in row]
	user_id = row[0];
	song_id = row[1];
	target = row[5];
	if user_id not in row_labels_A and user_id in row_labels_inliers:
		row_labels_A.add(user_id)
		if song_id not in col_labels_A:
			col_labels_A.add(song_id)
		f.update({(user_id,song_id):int(target)})

A = Mat((row_labels_A,col_labels_A) , f)

# Creating the age song listening profile
age_listening_profile = O.transpose() * A

age_song_list = []

# Computing most popular song for every age
for row_label in age_listening_profile.D[0]:
	row_values = []
	for col_label in age_listening_profile.D[1]:
		row_values.append(age_listening_profile.f.get((row_label,col_label)))
	max_row_value = max(row_values)
	age_song = "";

	for col_label in age_listening_profile.D[1]:
		if age_listening_profile.f.get((row_label,col_label)) == max_row_value:
			age_song = col_label
			break;
Пример #8
0
# Scalar Mult Test
M = Mat(({1, 3, 5}, {2, 4}), {(1, 2): 4, (5, 4): 2, (3, 4): 3})
print(M)
print(0 * M == Mat(({1, 3, 5}, {2, 4}), {}))

print(1 * M == M)
N = Mat(({1, 3, 5}, {2, 4}), {(1, 2): 1.0, (5, 4): 0.5, (3, 4): 0.75})
print(N)
print(0.25 * M == N)
print("\n")

# Transpose Test
M = Mat(({0, 1}, {0, 1}), {(0, 1): 3, (1, 0): 2, (1, 1): 4})
print(M)
print(M.transpose())
print(M.transpose() == Mat(({0, 1}, {0, 1}), {
    (0, 1): 2,
    (1, 0): 3,
    (1, 1): 4
}))

M = Mat(({'x', 'y', 'z'}, {2, 4}), {
    ('x', 4): 3,
    ('x', 2): 2,
    ('y', 4): 4,
    ('z', 4): 5
})
print(M)
Mt = Mat(({2, 4}, {'x', 'y', 'z'}), {
    (4, 'x'): 3,
Пример #9
0
# Part 2
vT_x_2 = [[2],[0]]
Sigma_vT_x_2 = [[4],[0]]
U_Sigma_vT_x_2 = [[0],[4],[0]]



## 4: (Problem 11.8.4) The SVD of a small simple matrix
# A.D = ({'r1','r2'},{'c1','c2'})
# Row and column labels of SA should be {0,1, ...}
UA = Mat(({'r1','r2'},{0,1}),{('r1',0):1,('r2',1):1})
SA = Mat(({0,1},{0,1}),{(0,0):3,(1,1):-1})
VA = Mat(({'c1','c2'},{0,1}),{('c1',0):1,('c2',1):1})

print(UA*(SA*VA.transpose()))

# B.D = ({'r1','r2'},{'c1','c2'})
# Row- and column-labels of SB should be {0,1, ...}
UB = Mat(({'r1','r2'},{0,1}),{('r1',0):1,('r2',1):1})
SB = Mat(({0,1},{0,1}),{(0,0):3,(1,1):4})
VB = Mat(({'c1','c2'},{0,1}),{('c1',0):1,('c2',1):1})

print(UB*(SB*VB.transpose()))


# C.D = ({'r1','r2','r3'},{'c1','c2'})
# Row- and column-labels of SC should be {0,1, ...}
UC = Mat(({'r1','r2','r3'},{0,1}),{('r1',0):-1,('r2',1):1})
SC = Mat(({0,1},{0,1}),{(0,0):4,(1,1):0})
VC = Mat(({'c1','c2'},{0,1}),{('c1',1):1,('c2',0):-1})
Пример #10
0
    song_id = row[1]
    target = row[5]
    if user_id not in row_labels:
        row_labels.add(user_id)
    if song_id not in col_labels:
        col_labels.add(song_id)

    f.update({(user_id, song_id): int(target)})
    output_line = user_id + "\t" + song_id + "\t" + target + "\n"
    output_file.writelines(output_line)
    # if index == 100:
    # 	break;

A = Mat((row_labels, col_labels), f)

similarity_mat = A * A.transpose()

similarity_values = [
    val for (row_label, col_label), val in similarity_mat.f.items()
    if row_label != col_label
]

#print(similarity_values)

print(len(similarity_values))

max_sim = max(similarity_values)
print(max_sim)
min_sim = min(similarity_values)
print(min_sim)
Пример #11
0
        - b: a Vec
    Output:
        - vector x that minimizes norm(b - A*x)
    Example:
        >>> domain = ({'a','b','c'},{'A','B'})
        >>> A = Mat(domain,{('a','A'):-1, ('a','B'):2,('b','A'):5, ('b','B'):3,('c','A'):1,('c','B'):-2})
        >>> Q, R = QR.factor(A)
        >>> b = Vec(domain[0], {'a': 1, 'b': -1})
        >>> x = QR_solve(A, b)
        >>> result = A.transpose()*(b-A*x)
        >>> result * result < 1E-10
        True
    '''
    labels = sorted(A.D[1], key=repr)
    Q, R = QR.factor(A)
    R_list = list(mat2rowdict(R).values())
    c = Q.transpose()*b
    x = triangular_solve(R_list,labels,c)
    return x

domain = ({'a','b','c'},{'A','B'})
A = Mat(domain,{('a','A'):-1, ('a','B'):2,('b','A'):5, ('b','B'):3,('c','A'):1,('c','B'):-2})
Q, R = QR.factor(A)
b = Vec(domain[0], {'a': 1, 'b': -1})
x = QR_solve(A, b)
result = A.transpose()*(b-A*x)

    


# True
A = Mat(({'a','b'}, {0,1}), {('a',1):2, ('b',0):1})
B = Mat(({'a','b'}, {0,1}), {('a',1):2, ('b',0):1, ('b',1):0})
C = Mat(({'a','b'}, {0,1}), {('a',1):2, ('b',0):1, ('b',1):5}) 
print(A == B)
# True
print(A == C, " (False expected)")
# False
print(A == Mat(({'a','b'}, {0,1}), {('a',1):2, ('b',0):1}))
# True


print('For transpose(M):')

M = Mat(({0,1}, {0,1}), {(0,1):3, (1,0):2, (1,1):4})
print(M.transpose() == Mat(({0,1}, {0,1}), {(0,1):2, (1,0):3, (1,1):4}))
# True
M = Mat(({'x','y','z'}, {2,4}), {('x',4):3, ('x',2):2, ('y',4):4, ('z',4):5})
Mt = Mat(({2,4}, {'x','y','z'}), {(4,'x'):3, (2,'x'):2, (4,'y'):4, (4,'z'):5})
print(M.transpose() == Mt)
# True


print('For vector_matrix_mul(v, M):')

v1 = Vec({1, 2, 3}, {1: 1, 2: 8})
M1 = Mat(({1, 2, 3}, {1, 2, 3}), {(1, 2): 2, (2, 1):-1, (3, 1): 1, (3, 3): 7})
print(v1*M1 == Vec({1, 2, 3},{1: -8, 2: 2, 3: 0}))
# True
print(v1 == Vec({1, 2, 3}, {1: 1, 2: 8}))
# True
Пример #13
0
from mat import Mat
from vec import Vec

A = Mat(({0, 1, 2}, {0, 1, 2}), {(0,0):1, (1,1):1})
print(A)
B = A.transpose()
print(B)

print(A*B)
print(B*A)
print(2*A)
Пример #14
0
# I = identity({1,2,3})
# print(I)


def mat2coldict(A):
    """Given a matrix, return a dictionary mapping column labels of A to columns of A
           e.g.:
           >>> M = Mat(({0, 1, 2}, {0, 1}), {(0, 1): 1, (2, 0): 8, (1, 0): 4, (0, 0): 3, (2, 1): -2})
           >>> mat2coldict(M)
           {0: Vec({0, 1, 2},{0: 3, 1: 4, 2: 8}), 1: Vec({0, 1, 2},{0: 1, 1: 0, 2: -2})}
           >>> mat2coldict(Mat(({0,1},{0,1}),{}))
           {0: Vec({0, 1},{0: 0, 1: 0}), 1: Vec({0, 1},{0: 0, 1: 0})}
    """
    return {c: Vec(A.D[0], {r: A[(r, c)] for r in A.D[0]}) for c in A.D[1]}


#
# M = Mat(({0, 1, 2}, {0, 1}), {(0, 1): 1, (2, 0): 8, (1, 0): 4, (0, 0): 3, (2, 1): -2})
# d = mat2coldict(M)
# print(d)

# Comprehension quizzes
# R = [[0 for j in range(4)] for i in range(3)]
# print(R)
#
# C = [[i-j for i in range(3)] for j in range(4)]
# print(C)

M = Mat(({'a', 'b'}, {0}), {('a', 0): 10, ('b', 0): 20})
Mt = M.transpose()
print(Mt)
Пример #15
0
from hw7 import QR_solve
from mat import coldict2mat
from mat import Mat
from orthonormalization import aug_orthonormalize
from QR import factor
from vec import Vec
from vecutil import list2vec

print('Augmented Orthonormalize')
L = [list2vec(v) for v in [[4,3,1,2],[8,9,-5,-5],[10,1,-1,5]]]
print(coldict2mat(L))
Qlist, Rlist = aug_orthonormalize(L)
print(coldict2mat(Qlist))
print(coldict2mat(Rlist))
print((coldict2mat(Qlist)*coldict2mat(Rlist)))

print('QR Solve')

A=Mat(({'a','b','c'},{'A','B'}), {('a','A'):-1, ('a','B'):2, ('b','A'):5, ('b','B'):3,('c','A'):1, ('c','B'):-2})
print(A)
Q, R = factor(A)
print(Q)
print(R)
b = Vec({'a','b','c'}, {'a':1,'b':-1})
x = QR_solve(A,b)
print(x)
residual = A.transpose()*(b-A*x)
print(residual)