12

Code is here

return self.activator(reduce(lambda a, b: a+b, map(lambda x, w: x*w, zip(input_vec, self.weights)), 0.0) + self.bias)

The python2.7-version code is like lambda (x, w)

But now the Tuple parameter unpacking was removed so I dont know how to figure it :(

smci
  • 32,567
  • 20
  • 113
  • 146
yizhuo liu
  • 123
  • 1
  • 1
  • 4
  • If i get you right, you see that map expects a function with just one element. If you map a list of tuples, you can get the values with indices. x = (13, 37) print(x[0], x[1]) – Schorsch Apr 03 '18 at 09:42
  • emmmmm I cant get what you mean.The argument of w is still not enough – yizhuo liu Apr 03 '18 at 11:37
  • @yizhui liu you shouldn't use x and y as parameters but only one parameter and indices in the function-body. I made an answer with the code for that. Hope that helps. [Look here](https://stackoverflow.com/a/49632316/4667743) – Schorsch Apr 03 '18 at 14:17
  • Please clarify: I think you mean you're using Python 3, and since tuple-unpacking was removed, you can no longer declare a lambda fn whose input is a tuple as `lambda (x, w)` and automatically get its input arg unpacked into `x,w`. Right? – smci Feb 18 '19 at 22:29

2 Answers2

8

It is a good thing to make a small running example which shows the problem. In your case, that is not the fact since we are missing some variables. Like i said in the other comment, your list you map over is made of tuples. Like you already know, you cannot unpack the tuples anymore, but you can use indices like you would use on an array. A simple working example:

val = reduce(lambda a, b: a+b, map(lambda t: t[0]*t[1], zip([10, 20, 30], [0.1, 0.3, 0.7])), 0.0)
print(val)

Like you see, the lambda function passed to the map function just has one parameter now. I called it t to make clear that this is a tuple, you can call it x if you want. In the function-body i use indices to get the first and second element of the tuple. If you run this code, you see that it works. So next step is to adept that to your code:

return self.activator(reduce(lambda a, b: a+b, map(lambda t: t[0]*t[1], zip(input_vec, self.weights)), 0.0) + self.bias)

And that should do the trick.

Schorsch
  • 319
  • 1
  • 14
6

you can't unpack anymore. But, you can just take tuple as it is, and use indexing in the formula:

map(lambda t: t[0]*t[1], zip(input_vec, self.weights))

using map with lambda has little interest, generator comprehension equivalent:

(x*w for x,w in zip(input_vec, self.weights))    

(and unpacking works)

The same construct needs to be repeated with the outer lambda and even reduce, which can be completely eliminated with sum which performs sums of the elements:

return self.activator(sum(x*w for x,w in zip(input_vec, self.weights)) + self.bias)

no more lambdas, shorter and clearer

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219