numpy.clip()如何在适当位置修改变量?

时间:2019-06-13 19:41:54

标签: python numpy

我正在学习一门课程,并发现了numpy.clip()函数的某些奇怪行为。似乎它正在修改所引用的变量而不是局部变量。我希望有人能提供一些见解,以了解这种情况的发生,因为我无法用更简单的案例进行复制。

*我已经提取了实际的作业,这只是我所看到的特征的一个示例。它在jupyter笔记本上运行。

import numpy as np
from utils import *
import random

def mod1(scores):
    score1, score2 = scores['score1'], scores['score2']

    for num in [score1, score2]:
        np.clip(num, -5, 5, num)

    scores = {'score1': score1, 'score2': score2}
    return scores

def mod2(scores):
    score1, score2 = scores['score1'], scores['score2']

    for num in [score1, score2]:
        num = np.clip(num, -2, 2)

    scores = {'score1': score1, 'score2': score2}
    return scores

def mod3(scores):
    score1, score2 = scores['score1'], scores['score2']

    for num in [score1, score2]:
        num = num + 1

    scores = {'score1': score1, 'score2': score2}
    return scores

score1 = np.random.randn(2,1)*10
score2 = np.random.randn(2,1)*10
scores = {"score1": score1, "score2": score2}
print("before scores = ", scores)
scores = mod1(scores)
print("after mod1 scores = ", scores)
scores = mod2(scores)
print("after mod2 scores = ", scores)
scores = mod3(scores)
print("after mod3 scores = ", scores)

我希望分数保持不变,但会成功被削减。

before scores =  {'score1': array([[-7.37464837],
       [-1.68090099]]), 'score2': array([[ 19.09276809],
       [  8.14814541]])}
after mod1 scores =  {'score1': array([[-5.        ],
       [-1.68090099]]), 'score2': array([[ 5.],
       [ 5.]])}
after mod2 scores =  {'score1': array([[-5.        ],
       [-1.68090099]]), 'score2': array([[ 5.],
       [ 5.]])}
after mod3 scores =  {'score1': array([[-5.        ],
       [-1.68090099]]), 'score2': array([[ 5.],
       [ 5.]])}

0 个答案:

没有答案