Tôi cố gắng để thực hiện thuật toán này để tìm tung độ gốc và độ dốc cho biến duy nhất:Simple Linear Regression bằng Python
Đây là mã Python của tôi để cập nhật các Intercept và dốc. Nhưng nó không hội tụ. RSS đang tăng với Iteration thay vì giảm và sau một số lần lặp lại nó trở thành vô hạn. Tôi không tìm thấy bất kỳ lỗi nào khi triển khai thuật toán. Tôi có thể giải quyết vấn đề này như thế nào? Tôi đã đính kèm tệp csv. Đây là mã.
import pandas as pd
import numpy as np
#Defining gradient_decend
#This Function takes X value, Y value and vector of w0(intercept),w1(slope)
#INPUT FEATURES=X(sq.feet of house size)
#TARGET VALUE=Y (Price of House)
#W=np.array([w0,w1]).reshape(2,1)
#W=[w0,
# w1]
def gradient_decend(X,Y,W):
intercept=W[0][0]
slope=W[1][0]
#Here i will get a list
#list is like this
#gd=[sum(predicted_value-(intercept+slope*x)),
# sum(predicted_value-(intercept+slope*x)*x)]
gd=[sum(y-(intercept+slope*x) for x,y in zip(X,Y)),
sum(((y-(intercept+slope*x))*x) for x,y in zip(X,Y))]
return np.array(gd).reshape(2,1)
#Defining Resudual sum of squares
def RSS(X,Y,W):
return sum((y-(W[0][0]+W[1][0]*x))**2 for x,y in zip(X,Y))
#Reading Training Data
training_data=pd.read_csv("kc_house_train_data.csv")
#Defining fixed parameters
#Learning Rate
n=0.0001
iteration=1500
#Intercept
w0=0
#Slope
w1=0
#Creating 2,1 vector of w0,w1 parameters
W=np.array([w0,w1]).reshape(2,1)
#Running gradient Decend
for i in range(iteration):
W=W+((2*n)* (gradient_decend(training_data["sqft_living"],training_data["price"],W)))
print RSS(training_data["sqft_living"],training_data["price"],W)
Here là tệp CSV.
; P đó là từ Đại học Washington lớp máy leanring, tôi lấy nó quá, nó đã rất vui vẻ và làm sáng tỏ. Tôi đề nghị bạn sử dụng diễn đàn trên coursera và bạn có thể nhận được câu trả lời rất tốt từ các cố vấn, tình nguyện viên và sinh viên. https://www.coursera.org/learn/ml-regression/discussions – alvas