0

I write a pocket algorithm in python with numpy and found that if I change

w += (x[:, col_idx] * y[col_idx, 0]).transpose()(wrong answer)

to w = w + (x[:, col_idx] * y[col_idx, 0]).transpose()(right answer)

the result that the algorithm will print different.

I have printed the w, x, y and the two version are the same.

And w is only being on the left side in above statement and have initialised.

I also have checked the algorithm and ensure that it is right.

What I cannot understand is that why only change w+=() to w=w+() will

change the whole result?(error_rate)

I have tested it that the w value will print the same.

The function part is

def pocket(x, y, update=50):

    w = np.zeros(shape=(1, 5))
    w_pocket = np.zeros(shape=(1, 5))

    update_idx = 0
    col_idx = 0
    col_number = x.shape[1]

    error_pocket = error_rate(x, y, w_pocket)

    for update_idx in range(update):
        col_range = random.sample(range(col_number), col_number)

        for col_idx in col_range:
            perceptron_score = w * x[:, col_idx]
            if label(perceptron_score) != y[col_idx, 0]:
                print "1:", col_idx, ":", x[:, col_idx].transpose(), y[col_idx, 0], w
                w = w + (x[:, col_idx] * y[col_idx, 0]).transpose()
                # w += (x[:, col_idx] * y[col_idx, 0]).transpose()
                print "2:", col_idx, ":", x[:, col_idx].transpose(), y[col_idx, 0], w
                error = error_rate(x, y, w)
                if error < error_pocket:
                    w_pocket = w
                    error_pocket = error
                break
    return w_pocket

and if you want to test it

you need the file

https://github.com/lypan/Machine_Learning_Foundations

214976eed5abc4514832daa9e6adf6d0250d3371

just unzip and run the script

Jason
  • 1,573
  • 3
  • 18
  • 46
  • 5
    `+=` (*"augmented assignment"*) isn't just syntactic sugar, it's implemented by a different method - `__iadd__` rather than `__add__`. You therefore cannot always expect `x += y` to behave identically to `x = x + y`. – jonrsharpe Sep 30 '15 at 13:40
  • 1
    Take a look at [this question](https://stackoverflow.com/questions/32799300/are-tuples-really-immutable-in-python), I know the scope is broader, but you have a specific example ther where "+=" behaves different than "value = value + (...)" I think it will help you understand). – jlnabais Sep 30 '15 at 13:44
  • thanks all of you, I am reading them now – Jason Sep 30 '15 at 13:45

0 Answers0