コード例 #1
0
def find_a_b(fname):
    data = read_vectors(fname)

    a_row_d = set(range(2))
    a_rows, b = [], Vec(set(range(len(data))), {})
    for i, v in enumerate(data):
        a_rows.append(Vec(a_row_d, {0: v['age'], 1:1}))
        b[i] = v['height']

    coeffs = QR_solve(rowdict2mat(a_rows), b)
    return (coeffs[0], coeffs[1])
コード例 #2
0
ファイル: HW.py プロジェクト: vasuharish/Coding_the_matrix
def linear_regression(data):
    datalist = read_vectors(data)
    x = list(datalist[0].D)[1]
    y = list(datalist[0].D)[0]
    x_domain = {1, x}
    x_rowlist = []
    y_list = []
    for v in datalist:
        x_rowlist.append(Vec(x_domain, {1: 1, x: v[x]}))
        y_list.append(v[y])
    y_vec = list2vec(y_list)
    minimize = QR_solve(rowdict2mat(x_rowlist), y_vec)
    return minimize[1], minimize[x]  # return b,a
コード例 #3
0
ファイル: solver_for_p6.py プロジェクト: vvw/CodingMatrix
def problem9():
    vlist = read_vectors('age-height.txt')
    agelist = []
    heightlist = []
    for v in vlist:
        agelist.append(v['age'])
        heightlist.append(v['height'])
    oneslist = [1] * len(agelist)
    print(agelist)
    print(heightlist)
    colsA = [[a, o] for a, o in zip(agelist, oneslist)]
    A = listlist2mat(colsA)
    print(A)
    b = list2vec(heightlist)
    print(b)
    x = QR_solve(A, b)
    print(x)
    result = A.transpose()*(b-A*x)
    print(result.is_almost_zero())
コード例 #4
0
x_hat_2 = Vec({0, 1}, {0: 2.5, 1: 2.67})

## 8: (Problem 9.11.14) Small examples of least squares
#Find the vector minimizing (Ax-b)^2

#Please represent your solution as a list

least_squares_A3 = listlist2mat([[3, 1], [4, 1]])
least_squares_b3 = list2vec([10, 13])

your_answer_1 = [1.08, 0.984]
your_answer_2 = [3, 1]

#your_answer_1 = QR_solve(least_squares_A1, least_squares_b1)
#your_answer_2 = QR_solve(least_squares_A3, least_squares_b3)

## 9: (Problem 9.11.15) Linear regression example
#Find a and b for the y=ax+b line of best fit

data_vecs = read_vectors("age-height.txt")
age_vecs_row_dict = {}
height_vec = Vec(set(range(len(data_vecs))), {})
for i, data_vec in enumerate(data_vecs):
    age_vecs_row_dict[i] = list2vec([data_vec['age'], 1])
    height_vec[i] = data_vec['height']
A = rowdict2mat(age_vecs_row_dict)
x_hat = QR_solve(A, height_vec)
a = 0.6349650349650302
b = 64.9283216783218