# Worked Algo For Linear Regression (Python 2.7.x and 3.4.x)

Oct 7th, 2015
344
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. # coding=utf-8
2. # Linear Regression Realization (http://dataaspirant.com/2014/12/20/linear-regression-implementation-in-python/)
3.
4. # input_data.csv:
5. # square_feet;price
6. # 150;6450
7. # 200;7450
8. # 250;8450
9. # 300;9450
10. # 350;11450
11. # 400;15450
12. # 600;18450
13.
14. # Required Packages
15. import matplotlib.pyplot as plt
16. import pandas as pd
17. from sklearn import linear_model
18.
19.
20. # Function to get data
21. def get_data(file_name):
22.     data = pd.read_csv(file_name, sep=";")
23.     x_parameter = []
24.     y_parameter = []
25.     # TODO: Replace the names of the fields 'square foot', 'price' for your own values
26.     for single_square_feet in data['square_feet']:
27.         x_parameter.append([float(single_square_feet)])
28.
29.     for single_price_value in data['price']:
30.         y_parameter.append(float(single_price_value))
31.     return x_parameter, y_parameter
32.
33.
34. # Function for Fitting our data to Linear model
35. # noinspection PyPep8Naming
36. def linear_model_main(x_parameters, y_parameters, predict_value):
37.     # Create linear regression object
38.     regr = linear_model.LinearRegression()
39.     regr.fit(x_parameters, y_parameters)
40.     # noinspection PyArgumentList
41.     predict_outcome = regr.predict(predict_value)
42.     predictions = {'intercept': regr.intercept_, 'coefficient': regr.coef_, 'predicted_value': predict_outcome}
43.     return predictions
44.
45.
46. # Function to show the resutls of linear fit model
47. def show_linear_line(x_parameters, y_parameters):
48.     # Create linear regression object
49.     regr = linear_model.LinearRegression()
50.     regr.fit(x_parameters, y_parameters)
51.     plt.scatter(x_parameters, y_parameters, color='blue')
52.     # noinspection PyArgumentList
53.     plt.plot(x_parameters, regr.predict(x_parameters), color='red', linewidth=4)
54.     # Supress axis value
55.     plt.xticks(())
56.     plt.yticks(())
57.     plt.show()
58.
59.
60. X, Y = get_data('input_data.csv')
61. predicted_value = 700
62. result = linear_model_main(X, Y, predicted_value)
63. print('Constant Value: {0}'.format(result['intercept']))
64. print('Coefficient: {0}'.format(result['coefficient']))
65. print('Predicted Value: {0}'.format(result['predicted_value']))
66. show_linear_line(X, Y)
RAW Paste Data