首页 > 解决方案 > 逻辑回归模型不学习

问题描述

我使用具有 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):

标签: pythonarrayspython-3.xnumpymachine-learning

解决方案


破碎的衍生品

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

此外,您正在计算错误变量的导数 - 似乎您需要 self.sigmoid_prime(pred) 而不是 self.sigmoid_prime(pred1)。

对玩具示例进行测试

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


推荐阅读