使用scipy.optimize时矩阵形状存在问题

时间:2019-04-23 19:44:21

标签: python numpy scipy numpy-broadcasting

这是我正在尝试的机器学习问题的代码。请注意,正在读取的.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,)的矩阵。

真的很高兴为此提供任何帮助或指导。

1 个答案:

答案 0 :(得分:0)

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