tammy2442
tammy2442

Reputation: 33

Python Jupyter Notebook not applying function correctly

I have a jupyter notebook in which I am using the logistic function to return an array that is normalized.

Code:

import math
import numpy as np

# takes a list of numbers as input
def logistic_transform(nums):
    e = math.e
    print(e)
    print(nums)
    for num in nums:
        num = 1 / 1 + (e ** num)
    return nums

input = [1, 2, 3]
test = logistic_transform(input)
print(test)

The output is:

2.718281828459045
[1, 2, 3]
[1, 2, 3]

Why are the changes not being applied to the values in input[] ?

Upvotes: 1

Views: 278

Answers (3)

Tanay Agrawal
Tanay Agrawal

Reputation: 412

First, your logistic function doesn't make sense, It should be something like, I guess:

(1 / (1 + (e ** (-num)))

What you are doing is taking out an element saving it in a variable num and updating the variable num, and not updating it in the list nums.

Either use list comprehension:

nums = [(1 / (1 + (e ** (-num)))) for num in nums]

or update the list like

for num in range(len(nums)):
    nums[num] = 1 /(1 + (e ** (-nums[num])))

Here, this should work fine:

import math
def logistic_transform(nums):
    e = math.e
    print(e)
    print(nums)
    nums = [(1 / (1 + (e ** (-num)))) for num in nums]
    return nums

input = [1, 2, 3]
test = logistic_transform(input)
print(test)

Upvotes: 0

JYFelt
JYFelt

Reputation: 1

What u do just get a new list,try a new list:

    new_list = []
    for num in nuns:
        #do ur stuff
        new_list.append(num)
    return new_list

Upvotes: 0

Ashlou
Ashlou

Reputation: 694

Just put your results in another list!

import math
import numpy as np
p_num =[]
# takes a list of numbers as input
def logistic_transform(nums):
    e = math.e
    print('e',e)
    print('nums',nums)
    for num in nums:
        p_num.append(1 / 1 + (e ** num))
return  p_num

input = [1, 2, 3]
test = logistic_transform(input)
print('test',test)

e 2.718281828459045

nums [1, 2, 3]

test [3.718281828459045, 8.389056098930649, 21.085536923187664]

Upvotes: 1

Related Questions