Проблема Идентификация почему: ValueError: бесконечность или слишком большая ПОСЛЕ нормализации - PullRequest
0 голосов
/ 12 апреля 2019

У меня есть набор данных, который я сначала нормализую, сбросив na, теперь я пытаюсь df [col] = preprocessing.scale (df [col] .values), и здесь я получаю ошибку: ValueError: Ввод содержит бесконечность или значение слишком большое для dtype ('float64').

Вот шаги, которые я сделал:

1- Убедитесь, что таблица данных (панды) не имеет NAN, удалив Nan 2 - нормализовать значения, используя pct_change 3 - сбросить сразу после вызова pct_change

и затем пробуя функцию масштабирования и получая ошибку

вот фрагмент кода:

от основного звонка:

dataset = f"./Data/Original/{RATIO_TO_PREDICT}.csv"
df = pd.read_csv(dataset)
df.set_index("Timestamp", inplace = True)

#calculate volume candle type 1

#calculate volume candle type 2

#df['VC1_Future'] = df["VC1"].shift(-FUTURE_PERIOD_PREDICT)
#df['VC1_Target'] = list(map(classify,df["VC1"], df["VC1_Future"]))

#df['VC2_Future'] = df["VC2"].shift(-FUTURE_PERIOD_PREDICT)
#df['VC2_Target'] = list(map(classify,df["VC2"], df["VC2_Future"]))

df.fillna(method="ffill", inplace = True)
df.dropna(inplace=True)

df['Price_Future'] = df["Close"].shift(-FUTURE_PERIOD_PREDICT) # We go N number of time to the future, get that value and put it in this row's FUTURE PRICE value
df['Price_Target'] = list(map(classify,df["Close"], df["Price_Future"])) 
# Now we compare the current price with that future price to see if we went up, down or none, here we use the 0.015 or 1.5% spread to make sure we pass commision

# Now we want to separate part of the data for training and another part for testing
times = sorted(df.index.values)
last_5pct = times[-int(0.1 * len(times))]


# We get the final columns we want, making sure we are not including any of the High, Low, and Open values. Remember that Price Target is last. That is OUR GOAL !!!
#dfs = df[["Close", "Volume", "Price_Future", "Price_Target"]]#, "VC1", "VC2", "VC1_Future", "VC2_Future", "VC1_Target", "VC2_Target", "Price_Future", "Price_Target"]]


# We finally separate the data into two different lists
validation_df = df[(df.index >= last_5pct)]
training_df = df[(df.index < last_5pct)]

# We save each list into a file so that we don't need to make this process walk through again unless A) we get new data B) we loose previous data on hard drive
Message(name)
print(len(df), len(training_df), len(validation_df))
Message(len(df))
#training_df.dropna(inplace=True)
print(np.isfinite(training_df).all())

print('')

#validation_df.dropna(inplace=True)
print(np.isfinite(validation_df).all())


Train_X, Train_Y = preprocess(training_df)

Теперь, когда дело доходит до функции, вот начало:

def preprocess(df) :
    df.drop('Price_Future', 1)
    #df.drop('VC1_Future', 1)
    #df.drop('VC2_Future', 1)
    for col in df.columns:
        if col != "Price_Target" and col != "VC1_Target" and col != "VC2_Target":
            df[col] = df[col].pct_change() # gets the percent change, other than the volume, the data now should sit between -1 and 1, the formula : (value[i] / value[i-1]) - 1
            df.dropna(inplace=True)
            df[col] = preprocessing.scale(df[col].values)

Когда я вызываю main, как вы могли заметить, я проверяю nan, результат:

Open             True
High             True
Low              True
Close            True
Volume           True
Price_Future    False
Price_Target     True
dtype: bool

и в самом начале функции я опускаю столбец Price_Future, поэтому, ПОЧЕМУ я получаю эту ошибку на линии масштабирования?

Кроме того, приведенный выше код вызывает много предупреждений:

Значение пытается быть установлено для копии среза из DataFrame. Попробуйте использовать .loc [row_indexer, col_indexer] = значение вместо

Но я новичок в python и во всем этом, поэтому я не знаю, как исправить код функции.

Кто-то, пожалуйста, помогите.

Спасибо

1 Ответ

0 голосов
/ 12 апреля 2019

OUCH, обнаружена основная проблема;

df [col] = preprocessing.scale (df [col] .values)

неверно

df [col]= preprocessing.scale (df [col])

Обратите внимание на отсутствие .values ​​в вызове масштаба !!!

Но, пожалуйста, кто-нибудь, помогите мне с этими предупреждающими сообщениями.

...