最近闲着没事,想把coursera上斯坦福ML课程里面的练习,用Python来实现一下,一是加深ML的基础,二是熟悉一下numpy,matplotlib,scipy这些库。
在EX2中,优化theta使用了matlab里面的fminunc函数,不知道Python里面如何实现。搜索之后,发现stackflow上有人提到用scipy库里面的minimize函数来替代。我尝试直接调用我的costfunction和grad,程序报错,提示(3,)和(100,1)dim维度不等,gradient vector不对之类的,试了N多次后,终于发现问题何在。。
首先来看看使用np.info(minimize)查看函数的介绍,传入的参数有:
fun : callable
The objective function to be minimized.
``fun(x, *args) -> float``
where x is an 1-D array with shape (n,) and `args`
is a tuple of the fixed parameters needed to completely
specify the function.
x0 : ndarray, shape (n,)
Initial guess. Array of real elements of size (n,),
where 'n' is the number of independent variables.
args : tuple, optional
Extra arguments passed to the objective function and its
derivatives (`fun`, `jac` and `hess` functions).
method : str or callable, optional
Type of solver. Should be one of
- 'Nelder-Mead' :re

在尝试将Stanford ML课程的练习用Python实现时,遇到了寻找fminunc替代的问题。通过stackflow的建议,使用scipy的minimize函数进行优化。遇到theta维度不匹配的错误,经过研究发现,minimize函数要求theta为1D数组,并且jac参数返回的梯度也应为1D。最终结果与MATLAB的fminunc一致,强调了正确理解和使用帮助文档的重要性,以及优化算法的效率优势。
最低0.47元/天 解锁文章
452

被折叠的 条评论
为什么被折叠?



