【问题标题】:Changing value of matrix and assigning value改变矩阵的值并赋值
【发布时间】:2018-05-25 10:56:44
【问题描述】:

下面的代码基于http://www.johnwittenauer.net/machine-learning-exercises-in-python-part-1/工作

theta = np.matrix(np.array([0, 0]))
def computeCost(X, y, theta, iterations, alpha):

    temp = np.matrix(np.zeros(theta.shape))
    m = len(X)
    theta_trans = theta.T
    for j in range(iterations):
        hyp = np.dot(X, theta_trans)-y

        term = np.multiply(hyp, X[:,0])
        temp[0,0] = theta[0,0] - ((alpha / len(X)) * np.sum(term))

        term = np.multiply(hyp, X[:,1])
        temp[0,1] = theta[0,1] - ((alpha / len(X)) * np.sum(term))

        theta = temp
        theta_trans = theta.T
    return theta

但是,当我直接使用 theta 而不是 temp 时,例如theta[0,0] = theta[0,0] - ((alpha / len(X)) * np.sum(term))) 并注释掉 theta = temp 我总是得到 0 和 0 的 theta。

当我在函数之外进行类似操作时,theta 会改变。例如,

theta = np.matrix(np.array([0,0]))
theta[0,0] = theta[0,0] - 1
print(theta)

theta 显示为 [-1 , 0]。

为什么这种类型的赋值在函数内部不起作用?

【问题讨论】:

  • 我不明白你的代码:你有一个循环,但没有使用迭代变量j
  • 能否也越过调用函数的行,以便我们在与我们相同的条件下对其进行测试。

标签: python numpy machine-learning


【解决方案1】:

一个可能的解释:这是类型问题(int vs float)。

任务

theta = np.matrix(np.array([0, 0]))

创建一个整数矩阵。当您直接分配其系数时,存在一些到整数的隐式转换:

>>> m = np.matrix(np.array([0, 0]))
>>> m
matrix([[0, 0]])
>>> m[0,0] = 0.5    # float
>>> m
matrix([[0, 0]])    # no effect, 0.5 converted to 0
>>> m[0,0] = 1      # int
>>> m
matrix([[1, 0]])

相比之下,temp 变量是一个浮点数矩阵(因为np.zeros 在未指定dtype 时会创建一个浮点数数组),因此浮点数的分配按预期工作。

所以只需将theta 直接声明为浮点矩阵就可以了。

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2018-07-16
    • 2020-11-19
    相关资源
    最近更新 更多