【问题标题】:Problem with matrix shapes while using scipy.optimize使用 scipy.optimize 时出现矩阵形状的问题
【发布时间】:2019-04-23 19:44:20
【问题描述】:

这是我正在尝试的机器学习问题的代码。请注意,正在读取的 .txt 文件包含三列。大多数情况下,无论是方阵还是向量,我都试图将数组形状保持为 (m,n) 而不是 (m,) 的形式。至于向量,我将它们的形状保持为 (m,1)(列向量)而不是 (1,m)(行向量)。

import numpy as np 
import matplotlib.pyplot as plt
import scipy.optimize as opt

X = np.loadtxt('ex2data1.txt', delimiter=',')[:,:-1]
y = np.loadtxt('ex2data1.txt', delimiter=',')[:,[-1]]
# Add the bias column to X
X = np.hstack(( np.ones((len(X),1)) , X ))

# Model parameter initialization
theta = np.zeros(( len(X[0,:]), 1 ))

def cost(X, y, theta):
    h = 1/(1+np.exp(-X@theta))
    return (-1/len(X))*( (y.T @ np.log(h)) + ((1-y).T @ np.log(1-h)) )

def gradient(X, y, theta):
    h = 1/(1+np.exp(-X@theta))
    return (1/len(X))*(X.T@(h-y))

J, grad = cost(X, y, theta), gradient(X, y, theta)

print('Cost at initial theta (zeros):\n', J)
print('Expected cost (approx): 0.693\n')
print('Gradient at initial theta (zeros): \n', grad)
print('Expected gradient (approx):\n -0.1000\n -12.0092\n -11.2628\n')
-------------------------------------
Cost at initial theta (zeros):      |
 [[0.69314718]]                     |
Expected cost (approx): 0.693       |
                                    |
Gradient at initial theta (zeros):  |
 [[ -0.1       ]                    |
 [-12.00921659]                     |
 [-11.26284221]]                    |
Expected gradient (approx):         |
 -0.1000                            |
 -12.0092                           |
 -11.2628                           |
-------------------------------------
X.shape, y.shape, theta.shape, grad.shape, J.shape
----------------------------------------------|
((100, 3), (100, 1), (3, 1), (3, 1), (1, 1))  |
----------------------------------------------|
theta, cost = opt.fmin_ncg(f=cost, x0=theta, fprime=gradient, args=(X,y))
print(cost)
print(theta)

我已将中间输出封装在盒子中。调用 fmin_ncg 函数会给我以下错误消息:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-133-86d5d7f476c2> in <module>
----> 1 theta, cost = opt.fmin_ncg(f=cost, x0=theta, fprime=gradient, args=(X,y))
      2 print(cost)
      3 print(theta)

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in fmin_ncg(f, x0, fprime, fhess_p, fhess, args, avextol, epsilon, maxiter, full_output, disp, retall, callback)
   1454 
   1455     res = _minimize_newtoncg(f, x0, args, fprime, fhess, fhess_p,
-> 1456                              callback=callback, **opts)
   1457 
   1458     if full_output:

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
   1535     k = 0
   1536     gfk = None
-> 1537     old_fval = f(x0)
   1538     old_old_fval = None
   1539     float64eps = numpy.finfo(numpy.float64).eps

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in function_wrapper(*wrapper_args)
    291     def function_wrapper(*wrapper_args):
    292         ncalls[0] += 1
--> 293         return function(*(wrapper_args + args))
    294 
    295     return ncalls, function_wrapper

<ipython-input-129-7fd4b6f3144e> in cost(X, y, theta)
      1 def cost(X, y, theta):
----> 2     h = 1/(1+np.exp(-X@theta))
      3     return (-1/len(X))*( (y.T @ np.log(h)) + ((1-y).T @ np.log(1-h)) )
      4 
      5 def gradient(X, y, theta):

ValueError: shapes (3,) and (100,1) not aligned: 3 (dim 0) != 100 (dim 0)

我不知道为什么会发生这种情况。我小心翼翼地将所有矩阵定义为具有正确的维度,并且我很确定我没有将任何矩阵定义为具有形状 (3,)。

很高兴在这方面提供任何帮助或指导。

【问题讨论】:

  • opt.fmin_ncg 变平 x0。它的文档对此并不清楚,但这是scipy.opitimize 函数中的常见行为。我通过查看代码验证了它(几个函数调用)。
  • @hpaulj:所以基本上theta 从 (3,1) 变平到 (3,)。有什么办法可以纠正这个烂摊子?
  • 形状 (3,1) 的 theta 是否包含 (3,) 不包含的任何重要信息?你不能在costgradient 的开头重塑X 吗?

标签: python numpy scipy array-broadcasting


【解决方案1】:

我会回答我自己的问题,以防其他人遇到同样的问题。成本(要最小化的函数)和梯度函数都需要将 x0(在这种情况下为 theta)作为它们的第一个参数。此外,梯度函数必须返回一个形状为 (n, ) 而不是 (n, 1) 的数组。参数向量 x0 也需要具有形状 (n, ) 而不是 (n, 1)。

【讨论】:

    猜你喜欢
    • 2017-05-23
    • 2020-07-02
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多