尝试在python中编写逻辑回归的正则化项。
在Octive中,我使用了以下代码:
reg_term = (lambda / (2 * m) * theta_revised' * theta_revised;
在python中尝试了以下代码;
reg_term = (lambda / (2 * m)) * np.transpose(theta_revised).dot(theta_revised);
使用指针指向“/”
获取SyntaxError: invalid syntax
#sigmoid function that calculates 1/(1 + e**-x)
def sigmoid(x):
return 1 / (1+ np.exp(-x))
#h is the prediction calculated taking the sigmoid of X * theta
h = sigmoid(np.dot(X,theta));
#need to remove the first theta term for regularization
theta_less = theta[1:size(theta)];
theta_revised = np.append([0],theta_less);
#Calculate the regularization term
#reg_term = (lambda/(2*m)) * (theta_revised' * theta_revised);
reg_term = (lambda / (2 * m)) * np.transpose(theta_revised).dot(theta_revised);
答案 0 :(得分:0)
lambda
是reserved keyword,您无法将其用作常规变量名称。
重命名变量;在名称中添加_
将是一种简单的解决方法:
reg_term = (lambda_ / (2 * m)) * np.transpose(theta_revised).dot(theta_revised)
请注意,您尚未在任何地方为lambda_
定义值,因此不会有NameError
例外。另请注意,Python表达式不需要以;
结尾,您通常不会使用分号。