def test_MyLinearRegressing(): x = np.array([[12.4956442], [21.5007972], [ 31.5527382], [48.9145838], [57.5088733]]) y = np.array([[37.4013816], [36.1473236], [ 45.7655287], [46.6793434], [59.5585554]]) lr1 = MyLR([2, 0.7]) # Example 0.0: print(lr1.predict_(x), end="\n\n") # Output: # array([[10.74695094], # [17.05055804], # [24.08691674], # [36.24020866], # [42.25621131]]) # Example 0.1: print(lr1.cost_elem_(lr1.predict_(x), y), end="\n\n") # Output: # array([[77.72116511], # [49.33699664], # [72.38621816], # [37.29223426], # [78.28360514]]) # Example 0.2: print(lr1.cost_(lr1.predict_(x), y), end="\n\n") # Output: # 315.0202193084312 # Example 1.0: # lr2 = MyLR([0, 0]) lr2 = MyLR([1, 1], 5e-8, 1500000) lr2.fit_(x, y) print(lr2.thetas, end="\n\n") # Output: # array([[1.40709365], # [1.1150909]]) # Example 1.1: print(lr2.predict_(x), end="\n\n") # Output: # array([[15.3408728], # [25.38243697], # [36.59126492], # [55.95130097], # [65.53471499]]) # Example 1.2: print(lr2.cost_elem_(lr2.predict_(x), y), end="\n\n") # Output: # array([[35.6749755], # [4.14286023], # [1.26440585], # [29.30443042], # [22.27765992]]) # Example 1.3: print(lr2.cost_(lr2.predict_(x), y), end="\n\n")
def plot_cost(x, y): """Plot the data and prediction line from three non-empty numpy.ndarray. Args: x: has to be an numpy.ndarray, a vector of dimension m * 1. y: has to be an numpy.ndarray, a vector of dimension m * 1. theta: has to be an numpy.ndarray, a vector of dimension 2 * 1. Returns: Nothing. Raises: This function should not raise any Exceptions. """ # plt.plot(x, y, 'o') # x = np.linspace(-15,5,100) plt.ylim((10, 50)) plt.xlim((-13, -4.5)) ran = 15 upd = ran * 2 / 6 for t0 in np.arange(89 - ran, 89 + ran, upd): cost_list = [] theta_list = [] for t1 in np.arange(-8 - 100, -8 + 100, 0.1): lr = MyLR(thetas=[t0, t1], alpha=1e-3, max_iter=50000) y_ = lr.predict(x) mse_c = lr.cost_(y, y_) #[0][0] cost_list.append(mse_c) theta_list.append(t1) # print(cost_list[-1]) label = "θ[0]=" + str(int(t0 * 10) / 10) print(label, "done!") plt.plot(theta_list, cost_list, label=label) plt.xlabel("θ[1]") plt.ylabel("MSE(θ[0], θ[1])") plt.legend(loc='upper left') plt.show()
def plot_cost(x: np.ndarray, y: np.ndarray) -> None: plt.xlabel("$θ_1$") plt.ylabel("cost function $J(θ_0, θ_1)$") plt.grid() linear_model = MyLR(np.array([[0], [0]]), max_iter=500) thetas_0 = range(85, 95, 2) for t0 in thetas_0: linear_model.thetas[0][0] = t0 npoints = 100 y_cost = [0] * npoints thetas1 = np.linspace(-15, -3.8, npoints) for i, t1 in enumerate(thetas1): linear_model.thetas[1][0] = t1 y_hat = linear_model.predict_(x) y_cost[i] = linear_model.cost_(y, y_hat) plt.plot(thetas1, y_cost, label="$J(θ_0=%d, θ_1)$" % t0) plt.legend() plt.show()
import pandas as pd from sklearn.metrics import mean_squared_error from my_linear_regression import MyLinearRegression as MyLR 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([[89.0], [-8]])) # linear_model2 = MyLR(np.array([[89.0], [-6]])) Y_model1 = linear_model1.predict_(Xpill) # Y_model2 = linear_model2.predict_(Xpill) print(linear_model1.cost_(Xpill, Yscore)) # 57.60304285714282 >>> print(mean_squared_error(Yscore, Y_model1)) # 57.603042857142825 >>> # print(linear_model2.cost_(Xpill, Yscore)) # 232.16344285714285 # print(mean_squared_error(Yscore, Y_model2)) x= Xpill y = Yscore plt.scatter(x, y) linear_model1.fit_(x, y) plt.xlabel('Quantity of blue pill (in micrograms)') plt.ylabel('Space driving score') plt.title('simple plot') plt.plot(x, linear_model1.predict_(x), color='green') plt.legend(['S_true', 'S_predict']) plt.show()
from my_linear_regression import MyLinearRegression from polynomial_model import add_polynomial_features if __name__ == "__main__": 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() i = 2 arr = np.zeros(9) l = list(range(2, 11)) while i <= 10: x_ = add_polynomial_features(x, i) my_lr = MyLinearRegression(np.ones(i + 1).reshape(-1, 1)) my_lr.fit_(x_, y) arr[i - 2] = (my_lr.cost_(my_lr.predict_(x_), y)) continuous_x = np.arange(1, 10.01, 0.01).reshape(-1, 1) x_ = add_polynomial_features(continuous_x, i) y_hat = my_lr.predict_(x_) plt.scatter(x, y) plt.plot(continuous_x, y_hat, color='orange') plt.show() i += 1 plt.bar(l, arr, color='orange') plt.show() print(arr)
array2 = n[sep:, :] return (array1[:, :-1], array2[:, :-1], array1[:, -1], array2[:, -1]) if __name__ == "__main__": data = pd.read_csv("../resources/are_blue_pills_magics.csv") x = np.array(data[['Micrograms']]) y = np.array(data[['Score']]) lst = data_spliter(x, y, 0.5) x_train = lst[0] y_train = lst[2] y_train = y_train[:, np.newaxis] x_test = lst[1] y_test = lst[3] y_test = y_test[:, np.newaxis] i = 2 my_lr = MyLinearRegression([[1], [1]]) my_lr.fit_(x_train, y_train) y_hat = my_lr.predict_(x_test) print(my_lr.cost_(y_hat, y_test)) while i <= 10: x_ = add_polynomial_features(x_train, i) my_lr = MyLinearRegression(np.ones(i + 1).reshape(-1, 1)) my_lr.fit_(x_, y_train) x_2 = add_polynomial_features(x_test, i) y_hat = my_lr.predict_(x_2) print(my_lr.cost_(y_hat, y_test)) i += 1
lr1.fit_(x1, Y) lr2.fit_(x2, Y) lr3.fit_(x3, Y) lr4.fit_(x4, Y) #lr5.fit_(x5, Y) #lr6.fit_(x6, Y) #lr7.fit_(x7, Y) #lr8.fit_(x8, Y) #lr9.fit_(x9, Y) y_1 = lr1.predict_(x1) y_2 = lr2.predict_(x2) y_3 = lr3.predict_(x3) y_4 = lr4.predict_(x4) #y_5 = lr5.predict_(x5) #y_6 = lr6.predict_(x6) #y_7 = lr7.predict_(x7) #y_8 = lr8.predict_(x8) #y_9 = lr9.predict_(x9) print(lr3.cost_(x3, Y)) plt.plot(X, Y, 'o') plt.plot(X, y_1, 'g') plt.plot(X, y_2, 'r') plt.plot(X, y_3, 'b') #plt.plot(X, y_4) #plt.plot(X, y_6) plt.show()
# [36.24020866], # [42.25621131]]) # Example 0.1: print("\nExample 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("\nExample 0.2") print(lr1.cost_(lr1.predict_(x), y)) # Output: # 315.0202193084312 # Example 1.0: lr2 = MyLR([1, 1], 5e-8, 1500000) lr2.fit_(x, y) print("\nExample 1.0") print(lr2.thetas) # Output: # array([[1.40709365], # [1.1150909 ]]) # Example 1.1: print("\nExample 1.1") print(lr2.predict_(x))
def print_costfn(t0, y): for i in np.linspace(t0 - 10, t0 + 50, 3000): linear_model3 = MyLR(np.array([[-10], [i]])) Y_model3 = linear_model3.predict_(Xpill) plt.plot(linear_model3.thetas[1], linear_model3.cost_(y, Y_model3), 'gs')
plt.plot(linear_model3.thetas[1], linear_model3.cost_(y, Y_model3), 'gs') 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) linear_model1 = MyLR(np.array([[89.0], [-8]])) linear_model2 = MyLR(np.array([[89.0], [-6]])) Y_model1 = linear_model1.predict_(Xpill) Y_model2 = linear_model2.predict_(Xpill) linear_model1_2 = MyLR(linear_model1.fit_(Xpill, Yscore)) Y_model1_2 = linear_model1_2.predict_(Xpill) print(linear_model1.cost_(Yscore, Y_model1) * 2) print(mean_squared_error(Yscore, Y_model1)) print(linear_model1.cost_(Yscore, Y_model2) * 2) print(mean_squared_error(Yscore, Y_model2)) plt.plot(Xpill, Y_model1_2, 'gs') plt.plot(Xpill, Y_model1_2, 'g--', label="Spredict(pills)") plt.plot(Xpill, Yscore, '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() for t0 in range(-10, -5, 1): print_costfn(t0, Yscore)
mylr = MyLR([[1.], [1.], [1.], [1.], [1]]) print("# Example 0:") print(mylr.predict(X)) print("# Output:") print("array([[8.], [48.], [323.]])") print() print("# Example 1:") print(mylr.cost_elem_(X,Y)) print("# Output:") print("array([[37.5], [0.], [1837.5]])") print() print("# Example 2:") print(mylr.cost_(X,Y)) print("# Output:") print(1875.0) print() # sys.lol() print("# Example 3:") mylr.fit_(X, Y) print(mylr.theta) print("# Output:") print("array([[18.023..], [3.323..], [-0.711..], [1.605..], [-0.1113..]])") print() print("# Example 4:") print(mylr.predict(X)) print("# Output:")