【发布时间】:2019-02-05 04:50:52
【问题描述】:
出于训练目的,我在 python 中实现了线性回归。问题是成本在增加而不是减少。对于数据,我使用翼型自噪声数据集。资料可查here
我导入数据如下:
import pandas as pd
def features():
features = pd.read_csv("data/airfoil_self_noise/airfoil_self_noise.dat.txt", sep="\t", header=None)
X = features.iloc[:, 0:5]
Y = features.iloc[:, 5]
return X.values, Y.values.reshape(Y.shape[0], 1)
我的线性回归代码如下:
import numpy as np
import random
class linearRegression():
def __init__(self, learning_rate=0.01, max_iter=20):
"""
Initialize the hyperparameters of the linear regression.
:param learning_rate: the learning rate
:param max_iter: the max numer of iteration to perform
"""
self.lr = learning_rate
self.max_iter = max_iter
self.m = None
self.weights = None
self.bias = None
def fit(self, X, Y):
"""
Run gradient descent algorithm
:param X: the inputs
:param Y: the outputs
:return:
"""
self.m = X.shape[0]
self.weights = np.random.normal(0, 0.1, (X.shape[1], 1))
self.bias = random.normalvariate(0, 0.1)
for iter in range(0, self.max_iter):
A = self.__forward(X)
dw, db = self.__backward(A, X, Y)
J = (1/(2 * self.m)) * np.sum(np.power((A - Y), 2))
print("at iteration %s cost is %s" % (iter, J))
self.weights = self.weights - self.lr * dw
self.bias = self.bias - self.lr * db
def predict(self, X):
"""
Make prediction on the inputs
:param X: the inputs
:return:
"""
Y_pred = self.__forward(X)
return Y_pred
def __forward(self, X):
"""
Compute the linear function on the inputs
:param X: the inputs
:return:
A: the activation
"""
A = np.dot(X, self.weights) + self.bias
return A
def __backward(self, A, X, Y):
"""
:param A: the activation
:param X: the inputs
:param Y: the outputs
:return:
dw: the gradient for the weights
db: the gradient for the bias
"""
dw = (1 / self.m) * np.dot(X.T, (A - Y))
db = (1 / self.m) * np.sum(A - Y)
return dw, db
然后我实例化线性回归类如下:
X, Y = features()
model = linearRegression()
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=42)
model.fit(X_train, y_train)
我试图找出成本增加的原因,但到目前为止我无法找出原因。如果有人能指出我正确的方向,将不胜感激。
【问题讨论】:
-
发布创建类实例并调用函数的完整代码。允许其他人重现错误/问题
-
我编辑了我的帖子
-
当您在数据上使用其他包时会得到什么样的结果?手动进行几次迭代会得到什么?
-
这可能是您的数据。当我将
features()中的行更改为X = features.iloc[:, 1:2](而不是使用前四列)时,您的成本开始下降。即使我使用 sklearn,使用原始数据也无法获得比 0.6 更好的分数。尝试构建一个人工数据集,您知道该数据集可以很好地与线性回归相结合——看看您会得到什么样的结果
标签: python machine-learning linear-regression