요새 ChatGPT가 코딩계에 큰 파문을 일으키고 있다. 구글 검색도 없어지고 프로그래머들도 일자리가 줄어들거라는 얘기까지 나올 정돈데, 실제로 어느 정도 성능인지 실험해보았다. ChatGPT를 이용해 작성할 코드는 LSTM을 이용해 bitcoin 가격을 예측하는 파이썬 코드이다. 우선 데이터를 긁어와야 하는데, 이 글에서는 upbit 데이터를 사용하겠다. 일 시켜보자!
오... 도움이 되긴 하지만 데이터 전처리와 모델, 학습까지 시키고 싶으니 더 자세히 물어보자.
import numpy as np
import pandas as pd
import pyupbit
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout
# Get BTC-KRW data from upbit
df = pyupbit.get_ohlcv("KRW-BTC", interval="minute60")
# Preprocess the data
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(df.values)
# Split the data into training and testing sets
train_data = scaled_data[:int(len(scaled_data) * 0.8)]
test_data = scaled_data[int(len(scaled_data) * 0.8):]
# Define a function to create the LSTM model
def create_model():
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(train_data.shape[1], 1)))
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(optimizer='adam', loss='mean_squared_error')
return model
# Create the LSTM model
model = create_model()
# Train the model
X_train = []
y_train = []
for i in range(60, len(train_data)):
X_train.append(train_data[i-60:i, 0])
y_train.append(train_data[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
model.fit(X_train, y_train, epochs=10, batch_size=32)
# Make predictions on the test data
X_test = []
y_test = []
for i in range(60, len(test_data)):
X_test.append(test_data[i-60:i, 0])
y_test.append(test_data[i, 0])
X_test, y_test = np.array(X_test), np.array(y_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)
# Plot the predictions
import matplotlib.pyplot as plt
plt.figure(figsize=(10,6))
plt.plot(y_test, color='blue', label='Actual BTC Price')
plt.plot(predictions, color='green', label='Predicted BTC Price')
plt.title('BTC Price Prediction')
plt.xlabel('Time')
plt.ylabel('BTC Price')
plt.legend()
plt.show()
오... 그럴싸해 보인다. 그런데 돌려보니 에러가 난다.
보아하니 input shape을 안 맞춰줘서 생긴 문제 같은데, 이것도 한번 물어보자.
요렇게 바꿔보란다. 어 그런데 나는 초보 코더라 이걸 어떻게 해야할지 모르겠어~ 니가 알아서 좀 해줘봐!
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
from keras.preprocessing.sequence import TimeseriesGenerator
# Load the data from Upbit
df = pd.read_csv('upbit_BTC.csv')
# Use only the 'Close' column for training
data = df.filter(['Close']).values
# Normalize the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# Split the data into training and testing sets
train_data = scaled_data[:int(len(scaled_data) * 0.8)]
test_data = scaled_data[int(len(scaled_data) * 0.8):]
# Prepare the data for training
lookback = 60
train_generator = TimeseriesGenerator(train_data, train_data, length=lookback, batch_size=20)
# Build the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(lookback, 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Train the model
model.fit(train_generator, epochs=5)
# Prepare the data for prediction
prediction_input = test_data[-lookback:].reshape(1, lookback, 1)
# Make the prediction
predicted_price = model.predict(prediction_input)
# Inverse transform the prediction to get the actual price
predicted_price = scaler.inverse_transform(predicted_price)
print(predicted_price)
이것도 에러가 난다. 우선 csv 파일이 없으니 upbit api를 통해 읽어와야 하고, api를 통해 읽어온 column 중에는 'Close'가 없다. 'close'가 있지. 요것들만 고치면 잘 돌아갈까?
안된다는데? 다시 물어보자.
제로패딩해서 맞춰주겠단다. 그게 문제가 아닌거 같은데? 다음 글에서 살펴보자
'머신러닝' 카테고리의 다른 글
ChatGPT를 이용해 비트코인 가격을 예측해보자 (3) (0) | 2023.03.01 |
---|---|
ChatGPT를 이용해 비트코인 가격을 예측해보자 (2) (0) | 2023.02.19 |