贤者不可变矢量错误

时间:2015-03-27 12:06:52

标签: immutability sage

我试图在sage中实现一些东西,并且我不断收到以下错误:

*Error in lines 38-53
Traceback (most recent call last):
  File "/projects/42e45a19-7a43-4495-8dcd-353625dfce66/.sagemathcloud/sage_server.py", line 879, in execute
    exec compile(block+'\n', '', 'single') in namespace, locals
  File "", line 13, in <module>
  File "sage/modules/vector_integer_dense.pyx", line 185, in sage.modules.vector_integer_dense.Vector_integer_dense.__setitem__ (build/cythonized/sage/modules/vector_integer_dense.c:3700)
    raise ValueError("vector is immutable; please change a copy instead (use copy())")
ValueError: vector is immutable; please change a copy instead (use copy())*

我已经确定了确切位置(&#34;打印&#39;标记1&#39;&#34;&#34;打印&#39;标记2&#39;&#34;在最后的while循环中,请参见下面的代码)并且似乎我不允许更改矩阵的条目&#34;权重&#34; (我在循环之前定义)来自循环内部。错误消息说使用copy()函数,但我不知道这将如何解决我的问题,因为我只会制作一个本地副本,循环的下一次迭代不会改变这些价值观吧?那么有谁知道如何定义这个矩阵,以便我可以从循环内部改变它?如果不可能,有人可以解释原因吗?

感谢您的帮助。


代码:

m = 3  # Dimension of inputs to nodes
n = 1  # Dimension of output
v = 4  # Number of training vectors
r = 0.1 # Learning Rate
T = 10     # Number of iterations

# Input static Biases, i.e. sum must be smaller than this vector. For dynamic biases, set this vector to 0, increase m by one and set xi[0]=-1 for all inputs i (and start the acual input at xi[1])
bias = list(var('s_%d' % i) for i in range(n))
bias[0] = 0.5

# Input the training vectors and targets

x0 = list(var('s_%d' % i) for i in range(m))
x0[0]=1
x0[1]=0
x0[2]=0
target00=1

x1 = list(var('s_%d' % i) for i in range(m))
x1[0]=1
x1[1]=0
x1[2]=1
target10=1

x2 = list(var('s_%d' % i) for i in range(m))
x2[0]=1
x2[1]=1
x2[2]=0
target20=1

x3 = list(var('s_%d' % i) for i in range(m))
x3[0]=1
x3[1]=1
x3[2]=1
target30=0

targets = matrix(v,n,[[target00],[target10],[target20],[target30]])

g=matrix([x0,x1,x2,x3])
inputs=copy(g)

# Initialize weights, or leave at 0 (i.e.,change nothing)

weights=matrix(m,n)


print weights.transpose()

z = 0
a = list(var('s_%d' % j) for j in range(n))

while(z<T):
    Q = inputs*weights
    S = copy(Q)
    for i in range(v):
        y = copy(a)
        for j in range(n):
            if S[i][j] > bias[j]:
                y[j] = 1
            else:
                y[j] = 0
            for k in range(m):
                print 'marker 1'
                weights[k][j] = weights[k][j] + r*(targets[i][j]-y[j])*inputs[i][k]
                print 'marker 2'
    print weights.transpose

    z +=1

1 个答案:

答案 0 :(得分:5)

这是Sage 向量的基本属性 - 默认情况下它们是不可变的Python对象。

sage: M = matrix([[2,3],[3,2]])
sage: M[0][1] = 5
---------------------------------------------------------------------------
<snip>
ValueError: vector is immutable; please change a copy instead (use copy())

请注意,错误是 vector 是不可变的。那是因为你已经采用0行,这是一个向量(我想是不可变的,可以清除的等等)。

但是如果你使用以下语法,你应该是金色的。

sage: M[0,1] = 5
sage: M
[2 5]
[3 2]

您在此处直接修改元素。希望这有帮助,享受Sage!