You have to install and use below packages for your HW#1.
numpy: Fundamental package for matrix computation with python.
matplotlib: Package for visualization of graph with python.
pandas: Open source package for data analysis and manipulation.
Do not use other machine learning packages in this homework, e.g., tensorflow, pytorch, jax, etc.
import math
import copy
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
The dataset consists 100 samples of Marks(Grades) of students including their "study time" & "number of courses".
In this homework, we would like to fit the linear regression model on this dataset. For practice, we will only use "study time" attribute.
Dataset
You will start by loading the dataset. Make sure the attached 'Student_Marks.csv' file is in your current directory path (can be downloaded from icampus).
Each column describes the below attributes:
[ time_study ]: Total hour the student has studied.
Assistant
User
한글로 출력해주세요\
Assistant
python
[ Marks ]: The final score the student has achieved.
Run below cells and take a look at the dataset!
Load the dataset
dataset = pd.read_csv("./Student_Marks.csv")
Display top 5 elements
dataset.head(5)
check data type of each attributes
dataset.dtypes
check dataset shape: (num data, num attributes)
dataset.shape
Extract "Hours Studied" and "Performance Index" attributes.
Each attributes will be the data and label, respectively.
data = dataset["time_study"].to_numpy()
label = dataset["Marks"].to_numpy()
Check data statistics
print("The shape of data is", data.shape)
print("The shape of label is", label.shape)
print()
print("The first Five elements of data are", data[:5])
print("The first Five elements of label are", label[:5])
print()
Exercise 1 : Complete the code for the normal equation
Complete the code for the normal equation
def normal_equation(data, label):
"""
Directly compute optimal w* = (w, b) of the linear regression model
code
Args:
data (np.ndarray): Shape (N, ) Input ot the model
label (np.ndarray): Shape (N, ) Label of the data
Return:
w (np.ndarray): weight(slope) of the linear regression model
b (np.ndarray): bias of the linear regression model
"""
#[NOTE] write your from code here!
return w, b
w, b = normal_equation(data, label)
print(f"w: {w:.6f}, b: {b:.6f}")
Plot your linear regression model and check if it works well
Obtain weight and bias of your linear regression model
x = np.array([x_min, x_max])
y = w * x + b
plt.plot(x, y)
plt.show()
3.2 Gradient Descent
Exercise 2 : Complete the code for computing the loss(cost)
> Here, the compute_loss() method computes the loss of the linear regression model.
Feel free to change or add variables, but do not modify the method name and its arguements.
def compute_loss(data, label, w, b):
"""
Compute the loss(cost) of the linear regression model, given data and label.
code
Args:
data (np.ndarray): Shape (N, ) Input to the model
label (np.ndarray): Shape (N, ) Label of the data
w (float): Weight of the linear regression model
b (float): Bias of the linear regression model
Return:
total_loss (float): Total loss of the linear regression model, given data and label
"""
total_loss = 0
#[NOTE] write your code here!
return total_loss
Exercise 4 : Complete the code for computing the gradient of the loss w.r.t weights and bias
> Here, the compute_gradient() method computes the gradient of the loss with respect to the parameters of the linear regression model.
Feel free to change or add variables, but do not modify the method name and its arguments.
def compute_gradient(data, label, w, b):
"""
Compute the loss(cost) of the linear regression model, given data and label.
code
Args:
data (np.ndarray): Shape (N, ) Input to the model
label (np.ndarray): Shape (N, ) Label of the data
w (float): Weight of the linear regression model
b (float): Bias of the linear regression model
Return:
grad_w (float): The gradient of the loss w.r.t weight w
grad_b (float): The gradient of the loss w.r.t bias b
"""
grad_w, grad_b = 0, 0
#[NOTE] write your code here!
return grad_w, grad_b
Exercise 4 : Complete the code of gradient descent algorithm
> gradient_descent() method applies gradient descent on the given dataset. You should make 'loop' inside this method to iteratively update w and b. You must use compute_loss() and compute_gradient() method to calculate loss and gradient, respectively.
Also, for the purpose of visualization of the training curve, this method returns some 'history' lists. You can just simply append updated values to the corresponding 'history' list.
Feel free to change or add variables, but do not modify the method name, its arguments, and return values.
def gradient_descent(data, label, w_init, b_init, iters=1500, lr=0.0001):
"""
Performs batch gradient descent to obatain weight and bias of the linear regression model.
code
Args:
data (np.ndarray): Shape (N,)
label (np.ndarray): Shape (N,)
w_init (float): Initial value of weight of the model
b_init (float): Initial values of bias of the model
lr (float): Learning rate
iters (int): Number of iterations to run gradient descent
Returns
w (float): Weight of the 1D linear regression model obtained with BGD
b (float): Bias of the 1D linear regression model obtained with BGD
loss_history (list): loss values of every iteration steps
w_history (list): w values of every iteration steps
b_history (list): b values of every iteration steps
"""
loss_history = []
w_history = []
b_history = []
w = w_init
b = b_init
loss = 0
for i in range(iters):
#[NOTE] write your code here!
# print loss for every 100 iterations
if i % 100 == 99:
print(f"[ {i + 1:4}/{iters} ] Loss: {loss:.4f} | w: {w:.4f} | b: {b:.4f}")
return w, b, loss_history, w_history, b_history
Now apply your gradient descent algorithm. (Also try other hyperparameter values!)
print("w,b found by gradient descent:", w_gd, b_gd)
obtain w and b with normal equation
w_ne, b_ne = normal_equation(data, label)
print("w,b found by normal equation:", w_ne, b_ne)
loss_history = loss_history[100:] # it is okay to remove this line
import math
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
# Load the dataset
dataset = pd.read_csv("./Student_Marks.csv")
# Display top 5 elements
print(dataset.head(5))
# Extract "time_study" and "Marks" attributes.
data = dataset["time_study"].to_numpy()
label = dataset["Marks"].to_numpy()
# Plot data
plt.scatter(data, label, marker='x', c='r')
plt.title("Study Time - Grade")
plt.xlabel("Study Time")
plt.ylabel("Grade")
plt.show()
# Normal Equation
def normal_equation(data, label):
X_b = np.c_[np.ones((len(data), 1)), data] # add bias term
theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(label)
w = theta_best[1]
b = theta_best[0]
return w, b
# Compute Loss
def compute_loss(data, label, w, b):
m = len(data)
total_loss = 0
for i in range(m):
total_loss += (w * data[i] + b - label[i]) ** 2
return total_loss / (2 * m)
# Compute Gradient
def compute_gradient(data, label, w, b):
m = len(data)
grad_w, grad_b = 0, 0
for i in range(m):
grad_w += (w * data[i] + b - label[i]) * data[i]
grad_b += (w * data[i] + b - label[i])
return grad_w / m, grad_b / m
# Gradient Descent
def gradient_descent(data, label, w_init, b_init, iters=1500, lr=0.0001):
w = w_init
b = b_init
loss_history = []
w_history = []
b_history = []
for i in range(iters):
grad_w, grad_b = compute_gradient(data, label, w, b)
w -= lr * grad_w
b -= lr * grad_b
loss = compute_loss(data, label, w, b)
loss_history.append(loss)
w_history.append(w)
b_history.append(b)
if i % 100 == 99:
print(f"[ {i + 1:4}/{iters} ] Loss: {loss:.4f} | w: {w:.4f} | b: {b:.4f}")
return w, b, loss_history, w_history, b_history
w_init, b_init = .0, .0
iters = 1500
learning_rate = 0.0001
# Gradient Descent
w_gd, b_gd, loss_history, w_history, b_history = gradient_descent(data, label, w_init, b_init, iters=iters, lr=learning_rate)
print("w, b found by gradient descent:", w_gd, b_gd)
# Normal Equation
w_ne, b_ne = normal_equation(data, label)
print("w, b found by normal equation:", w_ne, b_ne)
# Plot Training Curve
plt.plot(range(len(loss_history)), loss_history)
plt.title("Training Curve")
plt.xlabel("Iter")
plt.ylabel("Loss")
plt.show()
This script provides a complete resolution to the lab practice as described, from loading and visualizing the dataset to implementing linear regression through the normal equation and gradient descent methods. Additionally, it calculates and demonstrates losses to visualize the training process. This comprehensive solution includes utility functions for necessary calculations and generates visual insights to confirm the effectiveness of the linear regression model.
import math
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
# 데이터셋 불러오기
dataset = pd.read_csv("./Student_Marks.csv")
# 상위 5개 요소 표시
print(dataset.head(5))
# "time_study" 및 "Marks" 속성 추출
data = dataset["time_study"].to_numpy()
label = dataset["Marks"].to_numpy()
# 데이터 플롯
plt.scatter(data, label, marker='x', c='r')
plt.title("공부 시간 - 성적")
plt.xlabel("공부 시간")
plt.ylabel("성적")
plt.show()
# 정규 방정식
def normal_equation(data, label):
X_b = np.c_[np.ones((len(data), 1)), data] # 바이어스 항 추가
theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(label)
w = theta_best[1]
b = theta_best[0]
return w, b
# 손실 계산
def compute_loss(data, label, w, b):
m = len(data)
total_loss = 0
for i in range(m):
total_loss += (w * data[i] + b - label[i]) ** 2
return total_loss / (2 * m)
# 기울기 계산
def compute_gradient(data, label, w, b):
m = len(data)
grad_w, grad_b = 0, 0
for i in range(m):
grad_w += (w * data[i] + b - label[i]) * data[i]
grad_b += (w * data[i] + b - label[i])
return grad_w / m, grad_b / m
# 경사 하강법
def gradient_descent(data, label, w_init, b_init, iters=1500, lr=0.0001):
w = w_init
b = b_init
loss_history = []
w_history = []
b_history = []
for i in range(iters):
grad_w, grad_b = compute_gradient(data, label, w, b)
w -= lr * grad_w
b -= lr * grad_b
loss = compute_loss(data, label, w, b)
loss_history.append(loss)
w_history.append(w)
b_history.append(b)
if i % 100 == 99:
print(f"[ {i + 1:4}/{iters} ] 손실: {loss:.4f} | w: {w:.4f} | b: {b:.4f}")
return w, b, loss_history, w_history, b_history
w_init, b_init = .0, .0
iters = 1500
learning_rate = 0.0001
# 경사 하강법 적용
w_gd, b_gd, loss_history, w_history, b_history = gradient_descent(data, label, w_init, b_init, iters=iters, lr=learning_rate)
print("경사 하강법으로 찾은 w, b:", w_gd, b_gd)
# 정규 방정식 사용
w_ne, b_ne = normal_equation(data, label)
print("정규 방정식으로 찾은 w, b:", w_ne, b_ne)
# 훈련 곡선 플롯
plt.plot(range(len(loss_history)), loss_history)
plt.title("훈련 곡선")
plt.xlabel("반복")
plt.ylabel("손실")
plt.show()
이 스크립트는 제공된 데이터셋을 불러오고 시각화하는 것부터 시작하여, 정규 방정식 및 경사 하강법을 통한 선형 회귀 구현에 이르기까지 설명된 실습 작업에 대한 완전한 해결책을 제공합니다. 필요한 계산을 위한 유틸리티 함수를 포함하고 선형 회귀 모델의 효과성을 확인하기 위해 시각적인 인사이트를 생성합니다.