Ошибка при изменении размера данных в массиве numpy - PullRequest
0 голосов
/ 02 декабря 2010

У меня есть два массива, которые я хочу изменить, но я также хочу сохранить исходные значения.Приведенный ниже код изменяет размеры массивов, но проблема в том, что он перезаписывает исходные значения, как вы можете видеть, глядя на выходные данные команд

print(x) 
print(y)

в конце сценария.,Однако, если мы закомментируем строку

# NewX,NewY=resize(x,y,xmin=MinRR,xmax=MaxRR,ymin=minLVET,ymax=maxLVET) 

, то исходные значения x и y будут распечатаны правильно.Однако, если мы удалим комментарий и оставим код как есть, тогда x и y явно перезаписаны, потому что команды

print(x) 
print(y)

затем выводят значения для NewX и NewY соответственно.

Мой код ниже. Может кто-нибудь показать мне, как исправить приведенный ниже код, чтобы x и y сохраняли свои исходные значения, и чтобы NewX и NewY получали новые значения с измененным размером?

import numpy as np

def GetMinRR(age):
    MaxHR = 208-(0.7*age)
    MinRR = (60/MaxHR)*1000
    return MinRR

def resize(x,y,xmin=0.0,xmax=1.0,ymin=0.0,ymax=1.0):
    # Create local variables
    NewX = x
    NewY = y
    # If the mins are greater than the maxs, then flip them.
    if xmin>xmax: xmin,xmax=xmax,xmin 
    if ymin>ymax: ymin,ymax=ymax,ymin
    #----------------------------------------------------------------------------------------------    
    # The rest of the code below re-calculates all the values in x and then in y with these steps:
    #       1.) Subtract the actual minimum of the input x-vector from each value of x
    #       2.) Multiply each resulting value of x by the result of dividing the difference
    #           between the new xmin and xmax by the actual maximum of the input x-vector
    #       3.) Add the new minimum to each value of x
    # Note: I wrote in x-notation, but the identical process is also repeated for y
    #----------------------------------------------------------------------------------------------    
    # Subtracts right operand from the left operand and assigns the result to the left operand.
    # Note: c -= a is equivalent to c = c - a
    NewX -= x.min()

    # Multiplies right operand with the left operand and assigns the result to the left operand.
    # Note: c *= a is equivalent to c = c * a
    NewX *= (xmax-xmin)/NewX.max()

    # Adds right operand to the left operand and assigns the result to the left operand.
    # Note: c += a is equivalent to c = c + a
    NewX += xmin

    # Subtracts right operand from the left operand and assigns the result to the left operand.
    # Note: c -= a is equivalent to c = c - a
    NewY -= y.min()

    # Multiplies right operand with the left operand and assigns the result to the left operand.
    # Note: c *= a is equivalent to c = c * a
    NewY *= (ymax-ymin)/NewY.max()

    # Adds right operand to the left operand and assigns the result to the left operand.
    # Note: c += a is equivalent to c = c + a
    NewY += ymin

    return (NewX,NewY)

# Declare raw data for use in creating logistic regression equation
x = np.array([821,576,473,377,326],dtype='float') 
y = np.array([255,235,208,166,157],dtype='float') 

# Call resize() function to re-calculate coordinates that will be used for equation
MinRR=GetMinRR(34)
MaxRR=1200
minLVET=(y[4]/x[4])*MinRR
maxLVET=(y[0]/x[0])*MaxRR
NewX,NewY=resize(x,y,xmin=MinRR,xmax=MaxRR,ymin=minLVET,ymax=maxLVET) 

print 'x is:  ',x 
print 'y is:  ',y

Ответы [ 3 ]

3 голосов
/ 02 декабря 2010
NewX = x.copy()
NewY = y.copy()

numpy массивы также поддерживают интерфейс __copy__ и могут быть скопированы с помощью модуля копирования, поэтому это также будет работать:

NewX = copy.copy(x)
NewY = copy.copy(y)

Если вы хотите сохранить текущее поведение функции как есть, вам необходимо заменить все вхождения x и y на NewX и NewY. Если текущее поведение функции неверно, вы можете оставить их как есть.

1 голос
/ 02 декабря 2010

Делайте явные копии x и y в resize:

def resize(...):
    NewX = [t for t in x]
    NewY = [t for t in y]

Python всегда передается по ссылке, поэтому любые изменения, которые вы делаете в подпрограммах, вносятся в фактические переданные объекты.

0 голосов
/ 02 декабря 2010

Оригинал resize повторяется. Все, что сделано для x, повторяется для y. Это нехорошо , потому что это означает, что вам нужно поддерживать вдвое больше кода, чем вам действительно нужно. Решение состоит в том, чтобы resize работал только с одним массивом и вызывал его дважды (или по мере необходимости):

def resize(arr,lower=0.0,upper=1.0):
    # Create local variables
    result = arr.copy()
    # If the mins are greater than the maxs, then flip them.
    if lower>upper: lower,upper=upper,lower 
    #----------------------------------------------------------------------------------------------    
    # The rest of the code below re-calculates all the values in x and then in y with these steps:
    #       1.) Subtract the actual minimum of the input x-vector from each value of x
    #       2.) Multiply each resulting value of x by the result of dividing the difference
    #           between the new lower and upper by the actual maximum of the input x-vector
    #       3.) Add the new minimum to each value of x
    # Note: I wrote in x-notation, but the identical process is also repeated for y
    #----------------------------------------------------------------------------------------------    
    # Subtracts right operand from the left operand and assigns the result to the left operand.
    # Note: c -= a is equivalent to c = c - a
    result -= result.min()

    # Multiplies right operand with the left operand and assigns the result to the left operand.
    # Note: c *= a is equivalent to c = c * a
    result *= (upper-lower)/result.max()

    # Adds right operand to the left operand and assigns the result to the left operand.
    # Note: c += a is equivalent to c = c + a
    result += lower
    return result

Назовите это так:

NewX=resize(x,lower=MinRR,upper=MaxRR)
NewY=resize(y,lower=minLVET,upper=maxLVET)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...