逻辑回归模型不学习

时间:2019-01-06 19:09:19

标签: python arrays numpy machine-learning logistic-regression

我使用具有9个属性和一个标签向量的数据编写了逻辑回归算法,但它不是训练。
我认为我在更新权重时必须转置一些输入,但不确定,尝试了一些反复试验但没有运气。
如果有人可以帮助谢谢。

class logistic_regression(neural_network):
    def __init__(self,data):

        self.data = data   # to store the the data location in a varable 
        self.data1 = load_data(self.data) # load the data 
        self.weights =  np.random.normal(0,1,self.data1.shape[1] -1)   # use the number of attributes to get the number of weights
        self.bias = np.random.randn(1) #  set the bias to a random number 
        self.x = self.data1.iloc[:,0:9] # split the xs and ys
        self.y = self.data1.iloc[:,9:10]
        self.x = np.array(self.x)
        self.y = np.array(self.y)

        print(self.weights)
        print(np.dot(self.x[0].T,self.weights))
    def load_data(self,file):
        data = pd.read_csv(file)
        return data
    def sigmoid(self,x): # acivation function to limit the value to 0 and 1
        return 1 / (1 + np.exp(-x))
    def sigmoid_prime(self,x):
        return self.sigmoid(x) * (1 - self.sigmoid(x))
    def train(self):
        error = 0 # init the error to zero
        learning_rate = 0.01
        for interation in range(100):
            for i in range(len(self.x)): # loop though all the data
                pred = np.dot(self.x[i].T,self.weights) + self.bias # calculate the output
                pred1 = self.sigmoid(pred)
                error = (pred1 - self.y[i])**2 # check the accuracy of the network

                self.bias -= learning_rate * pred1 - self.y[i] * self.sigmoid_prime(pred1)
                self.weights -= learning_rate * (pred1 - self.y[i]) * self.sigmoid_prime(pred1) *  self.x[i]

            print(str(pred1)+"pred")
            print(str(error) + "error")  # print the result
            print(pred1[0] - self.y[i][0])
    def test(self):

2 个答案:

答案 0 :(得分:1)

您不能仅使用一个标签来训练任何机器学习模型。无论使用什么测试数据,训练后提供的标签都会对结果模型产生一个响应。

答案 1 :(得分:1)

残破的衍生产品

self.bias调整中有一个错误,缺少关于pred1-self.y [i]的括号。

此外,您正在从错误的变量计算导数-似乎需要self.sigmoid_prime(pred1)代替self.sigmoid_prime(pred1)。

测试玩具示例

对于任何这样的代码,我建议您首先在一个非常简单的函数上对其进行测试,该函数可以轻松打印 all 中间值并在纸上进行验证。例如,布尔AND和OR函数。这将向您显示更新公式是否正确,将学习代码与实际学习任务的特殊性隔离开来。