파이썬에서 그래디언트 디센트로 선형 회귀를 구현했습니다. 그것이 얼마나 잘하고 있는지보기 위해서 나는 scikit-learn의 LinearRegression() 클래스와 비교했다. 어떤 이유로 Sklearn은 평균 3의 MSE (항상 테스트를 위해 Boston Housing 데이터 세트를 사용하고 있습니다)로 내 프로그램을 능가합니다. 나는 현재 컨버전스를 확인하기 위해 그라디언트 검사를하고 있지 않다는 것을 이해하지만 많은 반복을 허용하고 학습 속도를 충분히 낮추어 수렴해야합니다. 학습 알고리즘 구현에 명확한 버그가 있습니까? 여기 내 코드는 다음과 같습니다.선형 회귀 구현은 항상 sklearn보다 성능이 우수합니다.
import numpy as np
from sklearn.linear_model import LinearRegression
def getWeights(x):
lenWeights = len(x[1,:]);
weights = np.random.rand(lenWeights)
bias = np.random.random();
return weights,bias
def train(x,y,weights,bias,maxIter):
converged = False;
iterations = 1;
m = len(x);
alpha = 0.001;
while not converged:
for i in range(len(x)):
# Dot product of weights and training sample
hypothesis = np.dot(x[i,:], weights) + bias;
# Calculate gradient
error = hypothesis - y[i];
grad = (alpha * 1/m) * (error * x[i,:]);
# Update weights and bias
weights = weights - grad;
bias = bias - alpha * error;
iterations = iterations + 1;
if iterations > maxIter:
converged = True;
break
return weights, bias
def predict(x, weights, bias):
return np.dot(x,weights) + bias
if __name__ == '__main__':
data = np.loadtxt('housing.txt');
x = data[:,:-1];
y = data[:,-1];
for i in range(len(x[1,:])):
x[:,i] = ((x[:,i] - np.min(x[:,i]))/(np.max(x[:,i]) - np.min(x[:,i])));
initialWeights,initialBias = getWeights(x);
weights,bias = train(x,y,initialWeights,initialBias,55000);
pred = predict(x, weights,bias);
MSE = np.mean(abs(pred - y));
print "This Program MSE: " + str(MSE)
sklearnModel = LinearRegression();
sklearnModel = sklearnModel.fit(x,y);
sklearnModel = sklearnModel.predict(x);
skMSE = np.mean(abs(sklearnModel - y));
print "Sklearn MSE: " + str(skMSE)
대단한 답변을 보내 주셔서 감사합니다. 실제로 SGD를하고 있다는 것을 깨닫지 못했습니다. 당신이 말했듯이, 1/m의 배수를 더하는 것은 그것을 버리고있었습니다; 알고리즘은 이제 scikit-learn만큼 좋은 성능을 보입니다. – rahulm
@rahulm 업데이트 된 코드는 어떻게 생겼습니까? github link? –