这是我的代码,可以让lstm用gpu运行吗,如果不行,如何调用全部的cpu import yfinance as yf from sklearn.preprocessing…
- User
这是我的代码,可以让lstm用gpu运行吗,如果不行,如何调用全部的cpu import yfinance as yf from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import LSTM, Dense, Dropout from sklearn.model_selection import train_test_split import numpy as np import pandas as pd import datetime from datetime import timedelta
Define the tickers
tickers = ['AAPL', 'TSLA', 'NVDA']
Define start and end date for fetching data
start_date = datetime.datetime.now() - timedelta(days=10*365) end_date = datetime.datetime.now()
Function to create a dataset suitable for LSTM
def create_dataset(X, y, time_steps=1): Xs, ys = [], [] for i in range(len(X) - time_steps): v = X.iloc[i:(i + time_steps)].values Xs.append(v) ys.append(y.iloc[i + time_steps]) return np.array(Xs), np.array(ys)
LSTM model definition
def create_lstm_model(input_shape): model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape)) model.add(Dropout(0.2)) model.add(LSTM(units=50, return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(units=50, return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(units=50)) model.add(Dropout(0.2)) model.add(Dense(units=1)) model.compile(loss='mean_squared_error', optimizer='adam') return model
Dictionary to store models for each ticker
lstm_models = {} scalers = {}
for ticker in tickers: # Fetch the data data = yf.download(ticker, start=start_date, end=end_date)
# Fill any NaNs data = data.dropna() # Preprocess the data scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(data[['Open', 'High', 'Low', 'Close', 'Volume']].values) # Store the fitted scaler in the dictionary scalers[ticker] = scaler # Create the dataset time_steps = 50 # Number of time steps you want to look back X, y = create_dataset(pd.DataFrame(scaled_data), pd.DataFrame(scaled_data[:,3]), time_steps) # Split the data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0) # Reshape the data to fit the model input X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 5)) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 5)) # Define the LSTM model model = create_lstm_model((X_train.shape[1], 5)) # Train the model model.fit(X_train, y_train, epochs=100, batch_size=64, verbose=1) # Save model in the dictionary lstm_models[ticker] = model # Making predictions predictions = model.predict(X_test) # Inverse transform to get actual values predictions = scaler.inverse_transform(np.concatenate((X_test[:, -1, :3], predictions, X_test[:, -1, 4:]), axis=1))[:, 3] actual_prices = scaler.inverse_transform(np.concatenate((y_test, y_test, y_test, y_test, y_test), axis=1))[:, 0] # Calculate MSE mse = np.mean(np.square(predictions - actual_prices)) print(f'{ticker} MSE: {mse}') - Assistant