Я создал следующий код TensorFlow, который запускаю в блокноте Azure, но он не очень точен для прогнозирования цены криптовалюты. оно дает общее направление будущего времени, но не очень точное.
Буду признателен, если кто-нибудь сможет добавить этому значение.
# Assuming 'df' is already defined and has the necessary columns
Window_Size = 5
Future_Projection = 12 # Number of future steps to predict
# Step 1: Prepare the dataset
features = df[['Close', 'High', 'Low', 'Price', 'Average', 'Volume', 'Cumulative_Return',
'Daily_Return', 'Timestamp_Unix', 'Crypto_Hashed', 'RSI14', 'MACD',
'MACD Signal', 'MACD Histogram', 'Stoch14', 'Stoch14d',
'Bollinger Bands Lower', 'Bollinger Bands Middle',
'Bollinger Bands Upper', 'CMF14', 'Support', 'Resistance',
'MA50', 'MA200']].values # Use multiple features
scaler = MinMaxScaler(feature_range=(0, 1)) # Normalize the data
scaled_data = scaler.fit_transform(features) # Scale the dataset
# Step 2: Split the dataset into training and testing sets
training_size = int(np.ceil(len(scaled_data) * 0.75)) # Use 95% of data for training
train_data = scaled_data[0:training_size, :] # Training data
test_data = scaled_data[training_size - Window_Size:, :] # Testing data
# Step 3: Prepare training data
x_train, y_train = [], []
# Create sequences of Window_Size time steps
for i in range(Window_Size, len(train_data)):
x_train.append(train_data[i-Window_Size:i, :]) # Previous Window_Size time steps with all features
y_train.append(train_data[i, :]) # Current time step (all features as labels)
# Convert to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
# Step 4: Build the LSTM-GRU model
model = Sequential()
model.add(GRU(units=100, return_sequences=True, input_shape=(x_train.shape[1], x_train.shape[2]))) # GRU layer
model.add(Dropout(0.2)) # Dropout for regularization
model.add(LSTM(units=100)) # LSTM layer
model.add(Dropout(0.2)) # Dropout for regularization
model.add(Dense(features.shape[1])) # Output layer with all features
# Step 5: Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Step 6: Setup callbacks for early stopping and model checkpointing
early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
model_checkpoint = ModelCheckpoint('best_model.keras', save_best_only=True, monitor='val_loss')
# Step 7: Train the model
history = model.fit(x_train, y_train, epochs=50, batch_size=8, validation_split=0.1,
callbacks=[early_stopping, model_checkpoint])
# Step 8: Prepare testing data
x_test, y_test = [], []
# Create sequences for testing
for i in range(Window_Size, len(test_data)):
x_test.append(test_data[i-Window_Size:i, :]) # Previous Window_Size time steps with all features
y_test.append(test_data[i, :]) # All features for the current time step
# Convert to numpy arrays
x_test = np.array(x_test)
y_test = np.array(y_test) # Ensure y_test includes all features
# Step 9: Make predictions on the test data
predictions = model.predict(x_test) # Predict the test data
# Inverse transform predictions
predictions_inverse = scaler.inverse_transform(predictions) # Inverse transform all features
y_test_inverse = scaler.inverse_transform(y_test) # Inverse transform actual values as well
# Step 10: Evaluate the model
mse = np.mean((predictions_inverse - y_test_inverse) ** 2, axis=0) # Mean Squared Error for each feature
#print("Mean Squared Error for each feature:", mse)
# Step 11: Prepare for future predictions
# Use the last 'Window_Size' periods of the scaled data for future predictions
last_window = scaled_data[-Window_Size:].reshape(1, Window_Size, features.shape[1]) # Reshape for model input
# Initialize a list to hold future predictions
future_predictions = np.zeros((Future_Projection, features.shape[1])) # Shape: (future_steps, number_of_features)
# Generate future predictions
for step in range(Future_Projection):
next_pred = model.predict(last_window) # Predict next values for all features
future_predictions[step, :] = next_pred[0, :] # Store predicted values for the current step
# Update last_window with the new predicted values
next_pred_reshaped = next_pred.reshape(1, 1, features.shape[1]) # Reshape to match last_window
last_window = np.append(last_window[:, 1:, :], next_pred_reshaped, axis=1) # Append new prediction
# Inverse transform future predictions
future_predictions_inverse = scaler.inverse_transform(future_predictions)
# Step 12: Create a DataFrame for future predictions
# Assuming the last timestamp is in the 'Timestamp' column of the original DataFrame
future_dates = [df['Timestamp'].iloc[-1] + (i + 1) * (df['Timestamp'].iloc[-1] - df['Timestamp'].iloc[-2]) for i in range(Future_Projection)]
# Create a DataFrame for future predictions
future_df = pd.DataFrame(future_predictions_inverse, columns=['Close'] + [f'Feature_{i}' for i in range(1, features.shape[1])])
future_df['Timestamp'] = future_dates
# Rearranging the DataFrame to have Timestamp first
future_df = future_df[['Timestamp'] + ['Close'] + [f'Feature_{i}' for i in range(1, features.shape[1])]]
# Display the future predictions in a nice table
#print("\nFuture Predictions Table:")
#print(future_df)
# Step 13: Append future predictions to the original DataFrame
df = pd.concat([df, future_df], ignore_index=True)
# Ensure the Timestamp column is in datetime format
df['Timestamp'] = pd.to_datetime(df['Timestamp'])
Подробнее здесь: https://stackoverflow.com/questions/791 ... -predictor
Нужны рекомендации по предсказателю TensorFlow [закрыто] ⇐ Python
Программы на Python
-
Anonymous
1731093050
Anonymous
Я создал следующий код TensorFlow, который запускаю в блокноте Azure, но он не очень точен для прогнозирования цены криптовалюты. оно дает общее направление будущего времени, но не очень точное.
Буду признателен, если кто-нибудь сможет добавить этому значение.
# Assuming 'df' is already defined and has the necessary columns
Window_Size = 5
Future_Projection = 12 # Number of future steps to predict
# Step 1: Prepare the dataset
features = df[['Close', 'High', 'Low', 'Price', 'Average', 'Volume', 'Cumulative_Return',
'Daily_Return', 'Timestamp_Unix', 'Crypto_Hashed', 'RSI14', 'MACD',
'MACD Signal', 'MACD Histogram', 'Stoch14', 'Stoch14d',
'Bollinger Bands Lower', 'Bollinger Bands Middle',
'Bollinger Bands Upper', 'CMF14', 'Support', 'Resistance',
'MA50', 'MA200']].values # Use multiple features
scaler = MinMaxScaler(feature_range=(0, 1)) # Normalize the data
scaled_data = scaler.fit_transform(features) # Scale the dataset
# Step 2: Split the dataset into training and testing sets
training_size = int(np.ceil(len(scaled_data) * 0.75)) # Use 95% of data for training
train_data = scaled_data[0:training_size, :] # Training data
test_data = scaled_data[training_size - Window_Size:, :] # Testing data
# Step 3: Prepare training data
x_train, y_train = [], []
# Create sequences of Window_Size time steps
for i in range(Window_Size, len(train_data)):
x_train.append(train_data[i-Window_Size:i, :]) # Previous Window_Size time steps with all features
y_train.append(train_data[i, :]) # Current time step (all features as labels)
# Convert to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
# Step 4: Build the LSTM-GRU model
model = Sequential()
model.add(GRU(units=100, return_sequences=True, input_shape=(x_train.shape[1], x_train.shape[2]))) # GRU layer
model.add(Dropout(0.2)) # Dropout for regularization
model.add(LSTM(units=100)) # LSTM layer
model.add(Dropout(0.2)) # Dropout for regularization
model.add(Dense(features.shape[1])) # Output layer with all features
# Step 5: Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Step 6: Setup callbacks for early stopping and model checkpointing
early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
model_checkpoint = ModelCheckpoint('best_model.keras', save_best_only=True, monitor='val_loss')
# Step 7: Train the model
history = model.fit(x_train, y_train, epochs=50, batch_size=8, validation_split=0.1,
callbacks=[early_stopping, model_checkpoint])
# Step 8: Prepare testing data
x_test, y_test = [], []
# Create sequences for testing
for i in range(Window_Size, len(test_data)):
x_test.append(test_data[i-Window_Size:i, :]) # Previous Window_Size time steps with all features
y_test.append(test_data[i, :]) # All features for the current time step
# Convert to numpy arrays
x_test = np.array(x_test)
y_test = np.array(y_test) # Ensure y_test includes all features
# Step 9: Make predictions on the test data
predictions = model.predict(x_test) # Predict the test data
# Inverse transform predictions
predictions_inverse = scaler.inverse_transform(predictions) # Inverse transform all features
y_test_inverse = scaler.inverse_transform(y_test) # Inverse transform actual values as well
# Step 10: Evaluate the model
mse = np.mean((predictions_inverse - y_test_inverse) ** 2, axis=0) # Mean Squared Error for each feature
#print("Mean Squared Error for each feature:", mse)
# Step 11: Prepare for future predictions
# Use the last 'Window_Size' periods of the scaled data for future predictions
last_window = scaled_data[-Window_Size:].reshape(1, Window_Size, features.shape[1]) # Reshape for model input
# Initialize a list to hold future predictions
future_predictions = np.zeros((Future_Projection, features.shape[1])) # Shape: (future_steps, number_of_features)
# Generate future predictions
for step in range(Future_Projection):
next_pred = model.predict(last_window) # Predict next values for all features
future_predictions[step, :] = next_pred[0, :] # Store predicted values for the current step
# Update last_window with the new predicted values
next_pred_reshaped = next_pred.reshape(1, 1, features.shape[1]) # Reshape to match last_window
last_window = np.append(last_window[:, 1:, :], next_pred_reshaped, axis=1) # Append new prediction
# Inverse transform future predictions
future_predictions_inverse = scaler.inverse_transform(future_predictions)
# Step 12: Create a DataFrame for future predictions
# Assuming the last timestamp is in the 'Timestamp' column of the original DataFrame
future_dates = [df['Timestamp'].iloc[-1] + (i + 1) * (df['Timestamp'].iloc[-1] - df['Timestamp'].iloc[-2]) for i in range(Future_Projection)]
# Create a DataFrame for future predictions
future_df = pd.DataFrame(future_predictions_inverse, columns=['Close'] + [f'Feature_{i}' for i in range(1, features.shape[1])])
future_df['Timestamp'] = future_dates
# Rearranging the DataFrame to have Timestamp first
future_df = future_df[['Timestamp'] + ['Close'] + [f'Feature_{i}' for i in range(1, features.shape[1])]]
# Display the future predictions in a nice table
#print("\nFuture Predictions Table:")
#print(future_df)
# Step 13: Append future predictions to the original DataFrame
df = pd.concat([df, future_df], ignore_index=True)
# Ensure the Timestamp column is in datetime format
df['Timestamp'] = pd.to_datetime(df['Timestamp'])
Подробнее здесь: [url]https://stackoverflow.com/questions/79168971/need-guidance-with-tensorflow-predictor[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия