示例#1
0
sys.path.append('src')
from dataframe import DataFrame
from polynomial_regressor import PolynomialRegressor

data = [(1, 3.1), (2, 10.17), (3, 20.93), (4, 38.71), (5, 60.91), (6, 98.87), (7, 113.92), (8, 146.95), (9, 190.09), (10, 232.65)]

columns = ['time', 'distance']
df = DataFrame.from_array(data, columns)

# Part A

print("\nquadratic_regressor")

quadratic_regressor = PolynomialRegressor(degree=2)
quadratic_regressor.fit(df, dependent_variable='distance')
quadratic_regressor.solve_coefficients()

n_list = [5, 10, 200]
for n in n_list:
    prediction = quadratic_regressor.predict({'time': n})
    print(n, "->", prediction)

# Part B

print("\ncubic_regressor")

cubic_regressor = PolynomialRegressor(degree=3)
cubic_regressor.fit(df, dependent_variable='distance')
cubic_regressor.solve_coefficients()

n_list = [5, 10, 200]
df = DataFrame.from_array([(0, 1), (1, 2), (2, 5), (3, 10), (4, 20), (5, 30)],
                          columns=['x', 'y'])


def round_dict(this_dict, amount):
    new_dict = {}
    for key, value in this_dict.items():
        new_value = round(value, amount)
        new_dict[key] = new_value
    return new_dict


constant_regressor = PolynomialRegressor(degree=0)
constant_regressor.fit(df, dependent_variable='y')
constant_regressor.solve_coefficients()
assert round_dict(constant_regressor.coefficients, 4) == {
    'constant': 11.3333
}, round_dict(constant_regressor.coefficients, 4)
assert round(constant_regressor.predict({'x': 2}), 4) == 11.3333

print("passed constant_regressor")

linear_regressor = PolynomialRegressor(degree=1)
linear_regressor.fit(df, dependent_variable='y')
linear_regressor.solve_coefficients()
assert round_dict(linear_regressor.coefficients, 4) == {
    'constant': -3.2381,
    'x': 5.8286
}
assert round(linear_regressor.predict({'x': 2}), 4) == 8.4190