python - 逻辑回归模型不学习
问题描述
我使用具有 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):
解决方案
破碎的衍生品
您在 self.bias 调整中有一个错误,缺少 pred1-self.y[i] 周围的括号。
此外,您正在计算错误变量的导数 - 似乎您需要 self.sigmoid_prime(pred) 而不是 self.sigmoid_prime(pred1)。
对玩具示例进行测试
对于任何这样的代码,我建议您首先在一个非常简单的函数上对其进行测试,其中打印出所有中间值并在纸上验证它们是微不足道的。例如,布尔 AND 和 OR 函数。这将向您显示更新公式是否正确,将学习代码与实际学习任务的特殊性隔离开来。
推荐阅读
- swift - 为什么函数调用需要参数名称,而分配给变量的函数却不允许?
- java - 如何在 Java 中使用 HTTP/REST 交换访问令牌(Oauth 2.0)的授权码?
- python - 如果前一列中的值不同,则计数器会增加,但在其他列值更改时会重置?
- mysql - 从 MySQL 视图中选择
- javascript - 可查看的内容会在设定的时间间隔内发生变化 - 但之前的内容会在之后闪现
- r - 将“绘制”标签保持在 ggplot2 的范围内
- python - 网页开发模板
- r - 使用循环 1 测试素数:sqrt(x)
- excel - Worksheet_Change 在虚拟化 Win Server SP2 上不起作用
- input - 是否也有类似 HTML5 的输入控件?