def MultiLinearRegression(X, Y, alpha, n_cycle): X_train = np.array(data[X]) Y_train = np.array(data[['Sell_price']]) my_lreg = MyLR([[1.0], [1.0], [1.0], [1.0]]) my_lreg.fit_(X_train,Y_train, alpha, n_cycle) Y_pred = my_lreg.predict_(X_train) print(my_lreg.cost_(X_train, Y_train)) linear_model(X_train, Y_train, Y_pred)
def SingleLinearRegression(X, Y, alpha, n_cycle): X_train = np.array(data[X]).reshape(-1,1) Y_train = np.array(data[Y]).reshape(-1,1) myLR_age = MyLR([[1000.0], [-1.0]]) myLR_age.fit_(X_train, Y_train, alpha, n_cycle) Y_pred = myLR_age.predict_(X_train) print(myLR_age.cost_(X_train, Y_train)) linear_model(X_train, Y_train, Y_pred)
def main(): data = pd.read_csv("are_blue_pills_magics.csv") Xpill = np.array(data["Micrograms"]).reshape(-1, 1) Yscore = np.array(data["Score"]).reshape(-1, 1) mlr = MyLinearRegression([[1.0], [1.0]]) mlr.fit_(Xpill, Yscore, alpha=0.005, n_cycle=2000) best_theta = mlr.theta print(best_theta) better_y_score = mlr.predict_(Xpill) print(better_y_score) plt.title( "Evolution of the space driving score in function of the quantity of blue pill (in micrograms). \nIn blue the real values and in green the predicted values.", fontsize=8) plt.xlabel("micrograms") plt.ylabel("Score") plt.plot(Xpill, Yscore, 'bo', Xpill, better_y_score, 'g-.', Xpill, better_y_score, "go") plt.show() plt.close() linear_model1 = MyLinearRegression(np.array([[89.0], [-6]])) linear_model2 = MyLinearRegression(np.array([[89.0], [-6]])) Y_model1 = linear_model1.predict_(Xpill) Y_model2 = linear_model2.predict_(Xpill) print(linear_model1.mse_(Y_model1, Yscore)) # 57.60304285714282 print(mean_squared_error(Y_model1, Yscore)) # 57.603042857142825 print(linear_model2.mse_(Y_model2, Yscore)) print("cost = ", linear_model2.cost_(Xpill, Yscore)) # 232.16344285714285 print(mean_squared_error(Y_model2, Yscore)) # # 232.16344285714285 x = [] y = [ ] # On a créé deux listes vides pour contenir les abscisses et les ordonnées move_theta = -14.0 for i in range(1000): # On veut les points de 0 à 100 linear_model1 = MyLinearRegression(np.array([[88.0], [move_theta]])) # for i in range(5): Y_model1 = linear_model1.predict_(Xpill) y.append(float(linear_model1.cost_(Xpill, Yscore))) x.append(float(linear_model1.theta[1])) move_theta += 0.01 # linear_model1.fit_(Xpill, Yscore, alpha = 0.00005, n_cycle=10) plt.plot(x, y) plt.show() plt.close()
def get_poly_cost(x, y, poly, alpha=0.001, n_cycle=1000, thetas=None): if thetas is None: thetas = [1] * (poly + 1) lr = MyLR(thetas, alpha=alpha, n_cycle=n_cycle) poly_x = add_polynomial_features(x, poly) lr.fit_(poly_x, y) cost = lr.cost_(poly_x, y) print(f"Poly {poly}: {cost} | {repr(lr.thetas)}") return cost
def compare_polynomials(x: np.ndarray, y: np.ndarray, i: int) -> None: theta = [2.5] * (x.shape[1] + 1) alpha = 1e-8 max_iter = int(1e+6) linear_model = MyLR(theta, alpha, max_iter) x_train, x_test, y_train, y_test = data_spliter(x, y, 0.6) linear_model.fit_(x_train, y_train) y_hat = linear_model.predict_(x_test) this_cost = linear_model.cost_(y_test, y_hat) print(i, this_cost) print(linear_model.thetas) plt.bar(i, this_cost, label="$%d_{th} cost: %.3f$" % (i, this_cost))
def main(): data = pd.read_csv("./data/data.csv") x = np.array(data["km"]).reshape(-1, 1) y = np.array(data["price"]).reshape(-1, 1) lr = MyLR(np.zeros(x.shape[1] + 1), alpha=1e-3, max_iter=10000) # Standardisation lr.setup_zscore(x) # Before training print("Starting cost:", lr.cost_(x, y), end="\n\n") plot_all(x, y, lr) # Training model cost_history = lr.fit_(x, y, get_cost=True) # Plotting cost evolution plt.plot(cost_history, "m-") plt.show() # After training print("Ending cost:", lr.cost_(x, y)) print("Thetas: ", lr.thetas, end="\n\n") plot_all(x, y, lr) # Save config in a file params = lr.get_params_() with open("config.mlr", "w") as f: f.write(repr(params)) print("-> config.mlr created")
def plot_model(x, y, data, theta, alpha=0.001, max_iter=100000): X = np.array(data[["{}".format(x)]]) Y = np.array(data[["{}".format(y)]]) myLR_obj = MyLR(theta, alpha, max_iter) print(myLR_obj.cost_(Y, myLR_obj.predict_(X))) myLR_obj.fit_(X[:, 0].reshape(-1, 1), Y) Y_model = myLR_obj.predict_(X) print(myLR_obj.cost_(Y, Y_model)) plt.plot(X, Y_model, 'gs') plt.plot(X, Y_model, 'g--', label="Spredict(pills)") plt.plot(X, Y, 'bo', label="Strue") plt.grid(True) plt.legend(loc='upper right', bbox_to_anchor=(0.33, 1.15)) plt.ylabel("Space driving score") plt.xlabel("Quantity of blue pill (in micrograms)") plt.show()
def univariate_lr(df, feature_name, alpha=5e-5, n_cycle=500000, colors=("g", "lime")): y = np.array(df["Sell_price"]) x_feature = np.array(df[feature_name]) lr = MyLR([1, 1], alpha=alpha, n_cycle=n_cycle) lr.fit_(x_feature, y) print(f"thetas: {lr.thetas}, cost: {lr.cost_(x_feature, y)}") y_hat = lr.predict_(x_feature) # Plot plt.plot(x_feature, y, "o", color=colors[0], label="Sell price") plt.plot(x_feature, y_hat, "o", color=colors[1], label="Predicted sell price") plt.legend(loc="best") plt.xlabel(feature_name) plt.ylabel("Sell price") plt.show()
def multivariate_lr(df): x = np.array(df[["Age", "Thrust_power", "Terameters"]]) y = np.array(df["Sell_price"]) # lr = MyLR([1, 1, 1, 1], 9e-5, 1000000) lr = MyLR([380, -24, 5, -2], 9e-5, 100000) lr.fit_(x, y) print(f"thetas: {lr.thetas}, cost: {lr.cost_(x, y)}") y_hat = lr.predict_(x) # Plot ax1 = plt.subplot(131) x_age = np.array(df["Age"]) ax1.plot(x_age, y, "o", color="b", label="Sell price") ax1.plot(x_age, y_hat, "o", color="dodgerblue", label="Predicted sell price") ax1.set_xlabel("Age") ax1.set_ylabel("Sell price") ax1.legend(loc="best") ax2 = plt.subplot(132) x_thrust = np.array(df["Thrust_power"]) ax2.plot(x_thrust, y, "o", color="g", label="Sell price") ax2.plot(x_thrust, y_hat, "o", color="lime", label="Predicted sell price") ax2.set_xlabel("Thrust_power") ax2.set_ylabel("Sell price") ax2.legend(loc="best") ax3 = plt.subplot(133) x_dist = np.array(df["Terameters"]) ax3.plot(x_dist, y, "o", color="darkviolet", label="Sell price") ax3.plot(x_dist, y_hat, "o", color="violet", label="Predicted sell price") ax3.set_xlabel("Terameters") ax3.set_ylabel("Sell price") ax3.legend(loc="best") # plt.tight_layout() plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1) plt.show()
def test_MyLinearRegressing(): X = np.array([[1., 1., 2., 3.], [5., 8., 13., 21.], [34., 55., 89., 144.]]) Y = np.array([[23.], [48.], [218.]]) mylr = MyLR([[1.], [1.], [1.], [1.], [1]], 5e-5, 320000) # Example 0: print(mylr.predict_(X), end="\n\n") # Output: # array([[8.], [48.], [323.]]) # Example 1: print(mylr.cost_elem_(X, Y), end="\n\n") # Output: # array([[37.5], [0.], [1837.5]]) # Example 2: print(mylr.cost_(X, Y), end="\n\n") # Output: # 1875.0 # Example 3: mylr.fit_(X, Y) print(mylr.thetas, end="\n\n") # Output: # array([[18.023..], [3.323..], [-0.711..], [1.605..], [-0.1113..]]) # Example 4: print(mylr.predict_(X), end="\n\n") # Output: # array([[23.499..], [47.385..], [218.079...]]) # Example 5: print(mylr.cost_elem_(X, Y), end="\n\n") # Output: # array([[0.041..], [0.062..], [0.001..]]) # Example 6: print(mylr.cost_(X, Y), end="\n\n")
axs[2].set(xlabel = ("Terameters"), ylabel = ("Sell_price")) """ #plt.show() #myLR_age #print(myLR_age.mse_(X, Y_price)) fig, axs = plt.subplots(3) # 2 part X = np.array(data[['Age', 'Thrust_power', 'Terameters']]) #, 'Thrust_power', 'Terameters']) Y = np.array(data['Sell_price']).reshape(-1, 1) X.reshape(X.shape[0], -1) l_reg = MyLR([[1.0], [1.0], [1.0], [1.0]]) #print(l_reg.mse_(X, Y)) print(X.shape, Y.shape) y_hat = l_reg.fit_(X, Y, alpha=2.5e-10, n_cycle=5000) print(l_reg.theta) axs[0].scatter(X[:, 0:1], Y, color="purple") axs[0].scatter(X[:, 0:1], y_hat, color="blue") axs[0].set_title("Sell_price with age") axs[0].set(xlabel=("Age"), ylabel=("Sell_price")) axs[1].scatter(X[:, 1:2], Y, color="purple") axs[1].scatter(X[:, 1:2], y_hat, color="blue") axs[1].set_title("Sell_price with thrust") axs[1].set(xlabel=("Thrust_power"), ylabel=("Sell_price")) axs[2].scatter(X[:, 2:], Y, color="purple") axs[2].scatter(X[:, 2:], y_hat, color="blue") axs[2].set_title("Sell_price with meters")
sys.path.insert(1, '../ex03') from mylinearregression import MyLinearRegression from csvreader import CsvReader # 1: import data with CsvReader("spacecraft_data.csv", header = True, skip_top = 0, skip_bottom = 0) as csv_file: data = np.array(csv_file.getdata(), float) #Xage = data[:, 0:1] Xage = data[:, 0:3] Yprice = data[:, 3:4] # 2: perform fit #tr = MyLinearRegression([516, -1]) tr = MyLinearRegression([8., -10., 7., -2.]) print(tr.mse_(Xage, Yprice)) print(tr.fit_(Xage, Yprice, 1e-4, 1000)) #print(tr.cost_(Xage, Yprice)) print(tr.mse_(Xage, Yprice)) # 3: print plot plt.plot(Xage[:, 0:1], Yprice, 'bo', label = "Strue") #plt.plot(Xage, tr.predict_(Xage), 'g') plt.plot(Xage[:, 0:1], tr.predict_(Xage), 'go', label ="Spredict") plt.ylabel('sell price') plt.xlabel('age') plt.grid() plt.legend() plt.show()
from mylinearregression import MyLinearRegression as MyLR import numpy as np X = np.array([[1., 1., 2., 3.], [5., 8., 13., 21.], [34., 55., 89., 144.]]) Y = np.array([[23.], [48.], [218.]]) mylr = MyLR([[1.], [1.], [1.], [1.], [1]]) print(mylr.predict_(X)) print(mylr.cost_elem_(X,Y)) print(mylr.cost_(X,Y)) mylr.theta = mylr.fit_(X, Y, alpha = 1.6e-4, n_cycle=100000) print(mylr.predict_(X)) print(mylr.cost_elem_(X,Y)) print(mylr.cost_(X,Y))
def prepare(data, column_data, x_banner, leg_loc): dataX = data[column_data][1:] dataY = data['Sell_price'][1:] myLR_age = MyLR(np.array([[1.], [1.]]), alpha=2.5e-5) myLR_age.fit_(dataX, dataY) plot_(myLR_age, dataX, dataY, x_banner, leg_loc)
print(myLR_obj.cost_(Y, Y_model)) plt.plot(X, Y_model, 'gs') plt.plot(X, Y_model, 'g--', label="Spredict(pills)") plt.plot(X, Y, 'bo', label="Strue") plt.grid(True) plt.legend(loc='upper right', bbox_to_anchor=(0.33, 1.15)) plt.ylabel("Space driving score") plt.xlabel("Quantity of blue pill (in micrograms)") plt.show() data = pd.read_csv("spacecraft_data.csv") #plot_model("Age", "Sell_price", data, [[1000.0], [-1.0]], alpha = 2.5e-5, max_iter = 10000) #plot_model("Thrust_power", "Sell_price", data, [[0], [10.0]], alpha = 1e-4, max_iter = 10000) #plot_model("Terameters", "Sell_price", data, [[1000.0], [-1.0]], alpha = 1e-4, max_iter = 50000) X = np.array(data[['Age', 'Thrust_power', 'Terameters']]) Y = np.array(data[["Sell_price"]]) myLR_obj = MyLR([1.0, 1.0, 1.0, 1.0], alpha=5e-10, max_iter=10000) print(myLR_obj.cost_(Y, myLR_obj.predict_(X))) myLR_obj.fit_(X, Y) Y_model = myLR_obj.predict_(X) print(myLR_obj.cost_(Y, Y_model)) plt.plot(X[:, 2], Y_model, 'go', label="Spredict(pills)") plt.plot(X[:, 2], Y, 'bo', label="Strue") plt.grid(True) plt.legend(loc='upper right', bbox_to_anchor=(0.33, 1.15)) plt.ylabel("Space driving score") plt.xlabel("Quantity of blue pill (in micrograms)") plt.show()
import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../ex07") from mylinearregression import MyLinearRegression as MyLR sys.path.append("../ex10") from polinomial_model import add_polynomial_features data = pd.read_csv("are_blue_pills_magics.csv") X = np.array(data["Micrograms"]).reshape(-1, 1) Y = np.array(data["Score"]).reshape(-1, 1) myLR_obj = MyLR([90.0, -1.0, 1.0, 2.0], alpha=5e-6, max_iter=20000) print(myLR_obj.cost_(Y, add_polynomial_features(X, 3))) myLR_obj.fit_(add_polynomial_features(X, 3), Y) Y_model = myLR_obj.predict_(add_polynomial_features(X, 3)) print(myLR_obj.cost_(Y, Y_model)) plt.plot(X, Y_model, 'go', label="Spredict(pills)") plt.plot(X, Y, 'bo', label="Strue") plt.grid(True) plt.legend(loc='upper right', bbox_to_anchor=(0.33, 1.15)) plt.ylabel("Space driving score") plt.xlabel("Quantity of blue pill (in micrograms)") plt.show()
# print(cost_elems) # Output: # array([ [77.72116511], # [49.33699664], # [72.38621816], # [37.29223426], # [78.28360514]]) # Example 0.2: # print(lr1.cost_(lr1.predict_(x),y)) # Output: # 315.0202193084312 lr2 = MyLR([0, 0]) # Example 1.0: lr2.fit_(x, y, alpha=5e-8, n_cycle=1500000) print(lr2.thetas) # Output: # array([ [1.40709365], # [1.1150909 ]]) # Example 1.1: # print(lr2.predict_(x)) # Output: # array([ [15.3408728 ], # [25.38243697], # [36.59126492], # [55.95130097], # [65.53471499]]) # Example 1.2:
Xage = np.array(data[['Age']]) Xtp = np.array(data[['Thrust_power']]) Xtm = np.array(data[['Terameters']]) X = np.array(data[['Age', 'Thrust_power', 'Terameters']]) Y = np.array(data[['Sell_price']]) # exemple 2.a print('exemple 2.a') my_lreg = MyLR([1.0, 1.0, 1.0, 1.0]) print(my_lreg.mse_(X, Y)) # Output : # 144044.877... my_lreg.fit_(X, Y, alpha=9.5e-5, n_cycle=900000) # best predict print(my_lreg.thetas) # Output : # array([[334.994...],[-22.535...],[5.857...],[-2.586...]]) print(my_lreg.mse_(X, Y)) # Output : # 586.896999... # plots print('plots') plot_model(Xage, Y, my_lreg.predict_(X)) plot_model(Xtp, Y, my_lreg.predict_(X)) plot_model(Xtm, Y, my_lreg.predict_(X))
import numpy as np from mylinearregression import MyLinearRegression as MyLR import matplotlib.pyplot as plt import matplotlib.lines as mlines import matplotlib.cm as cm fig, axs = plt.subplots(3) data = pd.read_csv("spacecraft_data.csv") X = np.array(data['Age']).reshape(-1, 1) print(X.shape) Y_price = np.array(data['Sell_price']).reshape(-1, 1) X_thrust = np.array(data['Thrust_power']).reshape(-1, 1) X_meters = np.array(data['Terameters']).reshape(-1, 1) myLR_age = MyLR([[1000.0], [-1.0]]) myLR_age.fit_(X, Y_price, alpha = 2.5e-5, n_cycle = 5000) y_hat = myLR_age.predict_(X) axs[0].scatter(X, Y_price, color = "purple") axs[0].plot(X, y_hat, color = "pink") axs[0].set_title("Sell_price with age") axs[0].set(xlabel = ("Age"), ylabel = ("Sell_price")) myLR_thrust = MyLR([[1000.0], [-1.0]]) y_hat_t = myLR_thrust.fit_(X_thrust, Y_price, alpha = 2.5e-5, n_cycle = 5000) axs[1].scatter(X_thrust, Y_price, color = "purple") axs[1].plot(X_thrust, y_hat_t, color = "pink") axs[1].set_title("Sell_price with thrustpower") axs[1].set(xlabel = ("Thrust_power"), ylabel = ("Sell_price")) #plt.subplot(132) myLR_meters = MyLR([[1000.0], [-1.0]])
def main(): data = pd.read_csv("spacecraft_data.csv") X = np.array(data[['Age','Thrust_power','Terameters']]) Y = np.array(data[['Sell_price']]) # myLR_age = MyLR([[700.0], [-30.0]]) # # print(myLR_age.theta) # myLR_age.fit_(X[:,0].reshape(-1,1), Y, alpha = 2.5e-5, n_cycle = 100) # RMSE_age = myLR_age.mse_(myLR_age.predict_(X[:,0].reshape(-1,1)),Y) # # print(myLR_age.theta) # # print(RMSE_age) # plt.title("Evolution of the sell price of spacecrafts with respect to the age of the spacecraft\nand representation of the predicted values of our first model.", fontsize = 8) # plt.ylabel("sell price") # plt.xlabel("age") # # print(X[:,0].reshape(-1,1)) # # print("predict : ",myLR_age.predict_(X[:,0].reshape(-1,1))) # # plt.plot(X[:,0].reshape(-1,1), Y, 'bo', X[:,0].reshape(-1,1),myLR_age.predict_(X[:,0].reshape(-1,1)), 'go') # # plt.show() # # print(X[:,1].reshape(-1,1)) # myLR_thrust = MyLR([[15.3],[4.4]]) # myLR_thrust.fit_(X[:,1].reshape(-1,1), Y, alpha = 2.5e-5, n_cycle = 200) # # print(myLR_thrust.mse_(myLR_thrust.predict_(X[:,0].reshape(-1,1)),Y)) # # print(myLR_thrust.theta) # plt.title("Evolution of the sell price of spacecrafts with respect to the thrust power\nof the spacecraft engines and representation of the predicted values of our second model.", fontsize = 8) # plt.ylabel("sell price") # plt.xlabel("thrust") # # plt.plot(X[:,1].reshape(-1,1), Y, 'bo', X[:,1].reshape(-1,1),myLR_thrust.predict_(X[:,1].reshape(-1,1)), 'go') # # plt.show() # # print(X[:,1].reshape(-1,1)) # myLR_dist = MyLR([[0.0],[1.5]]) # myLR_dist.fit_(X[:,2].reshape(-1,1), Y, alpha = 0.0005, n_cycle = 5) # # print(myLR_thrust.mse_(myLR_thrust.predict_(X[:,0].reshape(-1,1)),Y)) # # print(myLR_thrust.theta) # plt.title("Evolution of the sell price of spacecrafts\nwith respect to the terameters driven and the predicted values of our third model.", fontsize = 8) # plt.ylabel("sell price") # plt.xlabel("distance") # # plt.plot(X[:,2].reshape(-1,1), Y, 'bo',myLR_dist.predict_(X[:,2].reshape(-1,1)),Y ,'go') # # plt.show() my_lreg = MyLR([360.3584, -23.438, 5.7636, -2.6267]) # print(my_lreg.predict_(X)) # print(my_lreg.mse_(Y,my_lreg.predict_(X))) my_lreg.fit_(X,Y, alpha = 1e-4, n_cycle = 60) print(my_lreg.theta) print(my_lreg.mse_(Y,my_lreg.predict_(X))) plt.title("Evolution of the sell prices of spacecrafts and evolution of predicted sell prices\nof spacecrafts with the multi-variables hypothesis, with respect to the age.", fontsize = 8) plt.ylabel("sell price") plt.xlabel("age") plt.plot(X[:,0], Y, 'bo', X[:,0], my_lreg.predict_(X), 'go') plt.show() plt.plot(X[:,1], Y, 'bo', X[:,1], my_lreg.predict_(X), 'go') plt.show() plt.plot(X[:,2], Y, 'bo', X[:,2], my_lreg.predict_(X), 'go') plt.show()
import pandas as pd import numpy as np from normal_equation_model import graph_model from mylinearregression import MyLinearRegression as MyLR data = pd.read_csv("../resources/spacecraft_data.csv") X_train = np.array(data[['Age', 'Thrust_power', 'Terameters']]) Y_train = np.array(data['Sell_price']).reshape(-1, 1) myLR_ne = MyLR([[1.0], [1.0], [1.0], [1.0]]) myLR_lgd = MyLR([[1.0], [1.0], [1.0], [1.0]]) #Linear Gradient Descent myLR_lgd.fit_(X_train, Y_train, alpha=5e-5, n_cycle=10000) Y_pred_lgd = myLR_lgd.predict_(X_train) print('COST Linear gradient descent:', myLR_lgd.cost_(X_train, Y_train)) #Normal Equation myLR_ne.normalequation_(X_train, Y_train) Y_pred_ne = myLR_ne.predict_(X_train) print('COST Normal equation:', myLR_ne.cost_(X_train, Y_train)) graph_model(X_train, Y_train, Y_pred_lgd, Y_pred_ne)
""" Computes the normalized version of a non-empty numpy.ndarray using the min-max standardization. Args: x: has to be an numpy.ndarray, a vector. Returns: x' as a numpy.ndarray. None if x is a non-empty numpy.ndarray. Raises: This function shouldn't raise any Exception. """ return (x - np.min(x)) / (np.max(x) - np.min(x)) X = np.array([[1., 1., 2., 3.], [5., 8., 13., 21.], [34., 55., 89., 144.]]) X = minmax(X) Y = np.array([[23.], [48.], [218.]]) Y = minmax(Y) mylr = MyLR(np.array([[1.], [1.], [1.], [1.], [1.]])) plot_(mylr, X, Y) mylr.fit_(X, Y) plot_(mylr, X, Y) plt.show() #plot_cost_(mylr) #mylr.fit_(X, Y) print(mylr.thetas) #plot_cost_(mylr) #plot_(mylr, X, Y)
import pandas as pd import numpy as np #from sklearn.metrics import mean_squared_error from mylinearregression import MyLinearRegression as MyLR from linear_model import linear_model, cost_model data = pd.read_csv('../resources/are_blue_pills_magics.csv') Xpill = np.array(data['Micrograms']).reshape(-1, 1) Yscore = np.array(data['Score']).reshape(-1, 1) linear_model1 = MyLR(np.array([[0.0], [0.0]])) linear_model1.theta = linear_model1.fit_(Xpill, Yscore, alpha=0.05, n_cycle=1000) Y_model1 = linear_model1.predict_(Xpill) cost_elem = linear_model1.cost_(Xpill, Yscore) #cost_model(linear_model1.theta, cost_elem) linear_model(Xpill, Y_model1, Yscore) print(linear_model1.theta) #print(linear_model1.mse_(Yscore, Y_model1)) #print(mean_squared_error(Yscore, Y_model1)) #print(linear_model2.mse_(Yscore, Y_model2))
plt.legend(loc=leg_loc) plt.show() def prepare(data, column_data, x_banner, leg_loc): dataX = data[column_data][1:] dataY = data['Sell_price'][1:] myLR_age = MyLR(np.array([[1.], [1.]]), alpha=2.5e-5) myLR_age.fit_(dataX, dataY) plot_(myLR_age, dataX, dataY, x_banner, leg_loc) data = pd.read_csv("../resources/spacecraft_data.csv") #prepare(data, 'Age', 'x1: age(in years)', 'lower left') #prepare(data, 'Thrust_power', 'x2: thrust power(in 10Km/s)', 'upper left') #prepare(data, 'Terameters', 'x3: distance totalizer value of spacecraft (in Tmeters)', 'upper right') X = np.array(data[['Age','Thrust_power','Terameters']]) Y = np.array(data[['Sell_price']]).reshape((-1, 1)) my_lreg = MyLR(np.array([[300.0], [-10.0], [3.0], [-2.0]]), alpha=2.5e-5, n_cycle=600000) my_lreg.fit_(X, Y) prediction = my_lreg.predict_(X) #real_age = X[:, 0] real_dist = X[:, 2] plt.grid(True) plt.scatter(real_dist, Y, color='b', s=40, label='Sell price') plt.scatter(real_dist, prediction, color='c', s=10, label='Predicted sell price') #plt.xlabel('x1: age(in years)') plt.xlabel('x2: thrust power(in 10Km/s)') plt.ylabel('y: sell price (in keuros)') plt.legend(loc='lower left') plt.show()
import numpy as np from mylinearregression import MyLinearRegression as MyLR X = np.array([[1., 1., 2., 3.], [5., 8., 13., 21.], [34., 55., 89., 144.]]) Y = np.array([[23.], [48.], [218.]]) theta = np.array([[1.], [1.], [1.], [1.], [1]]) print("X", X.shape) print("Y", Y.shape) print("theta", theta.shape) # MyLR(). mylr = MyLR(theta) mylr.predict_(X) mylr.cost_elem_(X, Y) mylr.cost_(X, Y) mylr.fit_(X, Y, alpha=1.6e-4, n_cycle=200000) mylr.theta mylr.predict_(X) mylr.cost_elem_(X, Y) mylr.cost_(X, Y)
# [42.25621131]]) # Example 0.1: print(lr1.cost_elem_(lr1.predict_(x), y)) # Output: # array([[77.72116511], # [49.33699664], # [72.38621816], # [37.29223426], # [78.28360514]]) # Example 0.2: print(lr1.cost_(lr1.predict_(x), y)) # Output: # 315.0202193084312 # Example 1.0: lr2 = MyLR([0, 0]) lr2.fit_(x, y) print(lr2.thetas) # Output: # array([[1.40709365], # [1.1150909 ]]) # Example 1.1: print(lr2.predict_(x)) # Output: # array([[15.3408728 ], # [25.38243697], # [36.59126492], # [55.95130097], # [65.53471499]]) # Example 1.2: print(lr2.cost_elem_(lr1.predict_(x), y)) # Output:
def add_polynomial_features(x, power): temp = x.copy() for i in range(2, power + 1): temp = np.append(temp, np.power(x, i), axis=1) return temp x = np.arange(1, 11).reshape(-1, 1) y = np.array([[1.39270298], [3.88237651], [4.37726357], [4.63389049], [7.79814439], [6.41717461], [8.63429886], [8.19939795], [10.37567392], [10.68238222]]) plt.scatter(x, y) plt.show() from polynomial_model import add_polynomial_features from mylinearregression import MyLinearRegression as MyLR # Build the model: x_ = add_polynomial_features(x, 3) my_lr = MyLR(np.ones(4).reshape(-1, 1)) my_lr.fit_(x_, y) ## To get a smooth curve, we need a lot of data points continuous_x = np.arange(1, 10.01, 0.01).reshape(-1, 1) x_ = add_polynomial_features(continuous_x, 3) y_hat = my_lr.predict_(x_) plt.scatter(x, y) # print(my_lr.thetas) plt.plot(continuous_x, y_hat, color='orange') plt.show()
import pandas as pd import numpy as np from mylinearregression import MyLinearRegression as MyLR import matplotlib.pyplot as plt data = pd.read_csv("../resources/spacecraft_data.csv") X = np.array(data[['Age', 'Thrust_power', 'Terameters']]) X1 = np.array(data[['Age', 'Thrust_power', 'Terameters']]) Y = np.array(data['Sell_price']).reshape(-1, 1) theta1 = np.array([[1.], [1.], [1.], [1.]]) theta2 = np.array([[1.], [1.], [1.], [1.]]) myLR_ne = MyLR(theta1) myLR_lgd = MyLR(theta2) myLR_lgd.fit_(X, Y, alpha=5e-5, n_cycle=2000) Y_new1 = myLR_lgd.predict_(X) myLR_ne.normalequation_(X, Y) print(myLR_ne.theta) Y_new2 = myLR_ne.predict_(X) ''' print("MSE = ") print(myLR_lgd.theta) print(myLR_lgd.mse_(Y, Y_new1)) print("MSE = ") print(myLR_ne.theta) print(myLR_ne.mse_(Y, Y_new2)) ''' plt.scatter(data.Age, Y_new1, color='green') plt.scatter(data.Age, Y_new2, color='red')
data.plot.scatter("Thrust_power", "Sell_price") x = np.linspace(0, 200, 100) y = my_lreg.theta[0] + (my_lreg.theta[2] * X[2]) # plt.plot(X[2], y, '-r', label='Linear model 1', color = "green") plt.plot(x, my_lreg.theta[0] + (my_lreg.theta[2] * x), '-r', label='Linear model 1', color="red") plt.legend(loc='upper left') plt.grid() plt.show(block=False) # 144044.877... my_lreg.fit_(X, Y, alpha=5e-5, n_cycle=60000) print(my_lreg.theta) # array([[334.994...],[-22.535...],[5.857...],[-2.586...]]) print(my_lreg.mse_(X, Y)) # 586.896999... # plt.show() x = np.linspace(0, 200, 100) y = my_lreg.theta[0] + (my_lreg.theta[2] * X[2]) # plt.plot(X[2], y, '-r', label='Linear model 1', color = "yellow") plt.plot(x, my_lreg.theta[0] + (my_lreg.theta[2] * x), '-r', label='Linear model 1', color="yellow")
x = np.column_stack((x, copy_x ** nb)) return x data = pd.read_csv("../resources/spacecraft_data.csv") X = np.array(data[['Age','Thrust_power','Terameters']]) Y = np.array(data[['Sell_price']]) reg = MLR([1.0, 1.0, 1.0, 1.0]) # power = 1 # reg.fit_(X,Y, alpha = 6.5e-5, n_cycle = 1000000) # print("cost ", power, " : ", reg.cost_(X, Y), "\n") power = 2 reg.thetas = np.full(3 ** power + 1, 1.0) P = add_polynomial_features(X, power) reg.fit_(P, Y, alpha = 1e-9, n_cycle = 5000) print("cost ", power, " : ", reg.cost_(P, Y), "\n") # power = 3 # reg.thetas = np.full(4 * power + 1, 1.0) # P = add_polynomial_features(X, power) # reg.fit_(P, Y, alpha = 3e-13, n_cycle = 100000) # print("cost ", power, " : ", reg.cost_(reg.predict_(P), Y), "\n") # power = 4 # reg.thetas = np.full(4 * power, 1) # P = add_polynomial_features(X, power) # reg.fit_(P, Y, alpha = 1e-17, n_cycle = 1000000) # print("cost ", power, " : ", reg.cost_(reg.predict_(P), Y), "\n") # power = 5