自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用Python預(yù)測比特幣價(jià)格

開發(fā) 后端
比特幣是所有加密愛好者普遍使用的加密貨幣之一。即使有幾種突出的加密貨幣,如以太坊,Ripple,Litecoin等,比特幣也位居榜首。

[[399626]]

本文轉(zhuǎn)載自微信公眾號「區(qū)塊鏈研究實(shí)驗(yàn)室」,作者鏈三豐。轉(zhuǎn)載本文請聯(lián)系區(qū)塊鏈研究實(shí)驗(yàn)室公眾號。

在本文中,我們將討論與比特幣價(jià)格預(yù)測有關(guān)的程序。

涉及的主題:

1.什么是比特幣

2.如何使用比特幣

3.使用深度學(xué)習(xí)預(yù)測比特幣價(jià)格

什么是比特幣?

比特幣是所有加密愛好者普遍使用的加密貨幣之一。即使有幾種突出的加密貨幣,如以太坊,Ripple,Litecoin等,比特幣也位居榜首。

加密貨幣通常用作我們貨幣的加密形式,廣泛用于購物,交易,投資等。

它使用對等技術(shù),該技術(shù)背后是,沒有驅(qū)動力或任何第三方來干擾網(wǎng)絡(luò)內(nèi)完成的交易。此外,比特幣是“開源的”,任何人都可以使用。

功能:

  • 快速的點(diǎn)對點(diǎn)交易
  • 全球支付
  • 手續(xù)費(fèi)低

使用的原理-密碼學(xué):

加密貨幣(比特幣)背后的工作原理是“加密”,他們使用此原理來保護(hù)和認(rèn)證協(xié)商,并控制加密貨幣新組件的建立。

如何使用比特幣?

  • 保護(hù)錢包:應(yīng)該更安全地保護(hù)比特幣錢包,以便輕松順利地進(jìn)行交易
  • 比特幣價(jià)格易變:比特幣價(jià)格可能會波動。價(jià)格可以根據(jù)通貨膨脹率,數(shù)量等幾個(gè)因素而增加或減少。

使用深度學(xué)習(xí)預(yù)測比特幣價(jià)格

1. 數(shù)據(jù)收集:

導(dǎo)入CSV文件數(shù)據(jù)集。

  1. import pandas as pd 
  2. import numpy as np 
  3. import matplotlib.pyplot as plt 

現(xiàn)在,使用pandas和numpy導(dǎo)入數(shù)據(jù)集。Numpy主要用于python中的科學(xué)計(jì)算,

  1. coindata = pd.read_csv(‘Dataset.csv’) 
  2. googledata = pd.read_csv(‘DS2.csv’) 

已加載的原始數(shù)據(jù)集已打印,

  1. coindata = coindata.drop([‘#’], axis=1) 
  2. coindata.columns = [‘Date’,’Open’,’High’,’Low’,’Close’,’Volume’] 
  3. googledata = googledata.drop([‘Date’,’#’], axis=1) 

未使用的列將放在此處。

從硬幣數(shù)據(jù)和Google數(shù)據(jù)集中刪除兩列,因?yàn)樗鼈兪俏词褂玫牧小?/p>

從數(shù)據(jù)集中刪除未使用的列后,將為兩個(gè)數(shù)據(jù)集打印最終結(jié)果。

  1. last = pd.concat([coindata,googledata], axis=1) 

將兩個(gè)數(shù)據(jù)集(硬幣數(shù)據(jù)和谷歌數(shù)據(jù))連接起來,并使用函數(shù)將其打印出來

  1. last.to_csv(‘Bitcoin3D.csv’, index=False

2.一維RNN:

現(xiàn)在將兩個(gè)數(shù)據(jù)集串聯(lián)后,將導(dǎo)出最終數(shù)據(jù)集。

  1. import pandas as pd 
  2. import matplotlib.pyplot as plt 
  3. import numpy as np 
  4. import math 
  5. from sklearn.preprocessing import MinMaxScaler 
  6. from sklearn.metrics import mean_squared_error 
  7. from keras.models import Sequential 
  8. from keras.layers import Dense, Activation, Dropout 
  9. from keras.layers import LSTM 

在這里使用Keras庫。Keras僅需幾行代碼即可使用有效的計(jì)算庫訓(xùn)練神經(jīng)網(wǎng)絡(luò)模型。

MinMaxScaler會通過將每個(gè)特征映射到給定范圍來轉(zhuǎn)換特征。sklearn軟件包將提供該程序所需的一些實(shí)用程序功能。

密集層將執(zhí)行以下操作,并將返回輸出。

  1. output = activation(dot(input, kernel) + bias) 
  2. def new_dataset(dataset, step_size): 
  3.     data_X, data_Y = [], [] 
  4.     for i in range(len(dataset)-step_size-1): 
  5.         a = dataset[i:(i+step_size), 0] 
  6.         data_X.append(a) 
  7.         data_Y.append(dataset[i + step_size, 0]) 
  8.     return np.array(data_X), np.array(data_Y) 

將在數(shù)據(jù)預(yù)處理階段收集的一維數(shù)據(jù)分解為時(shí)間序列數(shù)據(jù),

  1. df = pd.read_csv(“Bitcoin1D.csv”) 
  2. df[‘Date’] = pd.to_datetime(df[‘Date’]) 
  3. df = df.reindex(index= df.index[::-1]) 

數(shù)據(jù)集已加載。該功能是從Bitcoin1D.csv文件中讀取的。另外,將“日期”列轉(zhuǎn)換為“日期時(shí)間”。通過“日期”列重新索引所有數(shù)據(jù)集。

  1. zaman = np.arange(1, len(df) + 1, 1) 
  2. OHCL_avg = df.mean(axis=1) 

直接分配一個(gè)新的索引數(shù)組。

  1. OHCL_avg = np.reshape(OHCL_avg.values, (len(OHCL_avg),1)) #7288 data 
  2. scaler = MinMaxScaler(feature_range=(0,1)) 
  3. OHCL_avg = scaler.fit_transform(OHCL_avg) 

分配定標(biāo)器后規(guī)格化數(shù)據(jù)集,

  1. #print(OHCL_avg) 
  2. train_OHLC = int(len(OHCL_avg)*0.56) 
  3. test_OHLC = len(OHCL_avg) — train_OHLC 
  4. train_OHLC, test_OHLC = OHCL_avg[0:train_OHLC,:], OHCL_avg[train_OHLC:len(OHCL_avg),:] 
  5. #Train the datasets and test it 
  6. trainX, trainY = new_dataset(train_OHLC,1) 
  7. testX, testY = new_dataset(test_OHLC,1) 

從平均OHLC(開高低開)中創(chuàng)建一維維度數(shù)據(jù)集,

  1. trainX = np.reshape(trainX, (trainX.shape[0],1,trainX.shape[1])) 
  2. testX = np.reshape(testX, (testX.shape[0],1,testX.shape[1])) 
  3. step_size = 1 

以3D維度重塑LSTM的數(shù)據(jù)集。將step_size分配給1。

  1. model = Sequential() 
  2. model.add(LSTM(128, input_shape=(1, step_size))) 
  3. model.add(Dropout(0.1)) 
  4. model.add(Dense(1)) 
  5. model.add(Activation(‘linear’)) 

創(chuàng)建LSTM模型,

  1. model.compile(loss=’mean_squared_error’, optimizer=’adam’) 
  2. model.fit(trainX, trainY, epochs=10, batch_size=25, verbose=2) 

將紀(jì)元數(shù)定義為10,batch_size為25,

  1. trainPredict = model.predict(trainX) 
  2. testPredict = model.predict(testX) 
  3. trainPredict = scaler.inverse_transform(trainPredict) 
  4. trainY = scaler.inverse_transform([trainY]) 
  5. testPredict = scaler.inverse_transform(testPredict) 
  6. testY = scaler.inverse_transform([testY]) 

完成了歸一化以進(jìn)行繪圖,

  1. trainScore = math.sqrt(mean_squared_error(trainY[0],  
  2.                        trainPredict[:,0])) 
  3. testScore = math.sqrt(mean_squared_error(testY[0],  
  4.                        testPredict[:,0])) 

針對預(yù)測的測試數(shù)據(jù)集計(jì)算性能度量RMSE,

  1. trainPredictPlot = np.empty_like(OHCL_avg) 
  2. trainPredictPlot[:,:] = np.nan 
  3. trainPredictPlot[step_size:len(trainPredict)+step_size,:] = 
  4.                                                   trainPredict 

將轉(zhuǎn)換后的train數(shù)據(jù)集用于繪圖,

  1. testPredictPlot = np.empty_like(OHCL_avg) 
  2. testPredictPlot[:,:] = np.nan 
  3. testPredictPlot[len(trainPredict)+(step_size*2)+1:len(OHCL_avg)-1,:] 
  4.                     = testPredict 

將轉(zhuǎn)換后的預(yù)測測試數(shù)據(jù)集用于繪圖,

最終將預(yù)測值可視化。

  1. OHCL_avg = scaler.inverse_transform(OHCL_avg) 
  2. plt.plot(OHCL_avg, ‘g’, label=’Orginal Dataset’) 
  3. plt.plot(trainPredictPlot, ‘r’, label=’Training Set’) 
  4. plt.plot(testPredictPlot, ‘b’, label=’Predicted price/test set’) 
  5. plt.title(“ Bitcoin Predicted Prices”) 
  6. plt.xlabel(‘ Time’, fontsize=12) 
  7. plt.ylabel(‘Close Price’, fontsize=12) 
  8. plt.legend(loc=’upper right’) 
  9. plt.show() 

3.多變量的RNN:

  1. import pandas as pd 
  2. from pandas import DataFrame 
  3. from pandas import concat 
  4. from math import sqrt 
  5. from numpy import concatenate 
  6. import matplotlib.pyplot as pyplot 
  7. import numpy as np 
  8. from sklearn.metrics import mean_squared_error 
  9. from sklearn.preprocessing import MinMaxScaler 
  10. from keras import Sequential 
  11. from keras.layers import LSTM, Dense, Dropout, Activation 
  12. from pandas import read_csv 

使用Keras庫。Keras僅需幾行代碼就可以使用有效的計(jì)算庫來訓(xùn)練神經(jīng)網(wǎng)絡(luò)模型。sklearn軟件包將提供該程序所需的一些實(shí)用程序功能。

密集層將執(zhí)行以下操作,并將返回輸出。

  1. dataset = read_csv(‘Bitcoin3D.csv’, header=0, index_col=0) 
  2. print(dataset.head()) 
  3. values = dataset.values 

使用Pandas庫加載數(shù)據(jù)集。在這里準(zhǔn)備了可視化的列。

  1. groups = [0, 1, 2, 3, 5, 6,7,8,9] 
  2. i = 1 

將系列轉(zhuǎn)換為監(jiān)督學(xué)習(xí)。

  1. def series_to_supervised(data, n_in=1, n_out=1, dropnan=True): 
  2.     n_vars = 1 if type(data) is list else data.shape[1] 
  3.     df = DataFrame(data) 
  4.     cols, names = list(), list() 
  5.     # Here is created input columns which are (t-n, … t-1) 
  6.     for i in range(n_in, 0, -1): 
  7.         cols.append(df.shift(i)) 
  8.         names += [(‘var%d(t-%d)’ % (j+1, i)) for j in range(n_vars)] 
  9. #Here, we had created output/forecast column which are (t, t+1, … t+n) 
  10.     for i in range(0, n_out): 
  11.         cols.append(df.shift(-i)) 
  12.         if i == 0: 
  13.             names += [(‘var%d(t)’ % (j+1)) for j in range(n_vars)] 
  14.         else
  15.             names += [(‘var%d(t+%d)’ % (j+1, i)) for j in 
  16.                                              range(n_vars)] 
  17.     agg = concat(cols, axis=1) 
  18.     agg.columns = names 
  19.     # drop rows with NaN values  
  20.     if dropnan: 
  21.         agg.dropna(inplace=True
  22.     return agg 

檢查值是否為數(shù)字格式,

  1. values = values.astype(‘float32’) 

數(shù)據(jù)集值通過使用MinMax方法進(jìn)行歸一化,

  1. scaler = MinMaxScaler(feature_range=(0,1)) 
  2. scaled = scaler.fit_transform(values

將規(guī)范化的值轉(zhuǎn)換為監(jiān)督學(xué)習(xí),

  1. reframed = series_to_supervised(scaled,1,1) 
  2. #reframed.drop(reframed.columns[[9,10,11,12,13,14,15]], axis=1, inplace=True

數(shù)據(jù)集分為兩組,分別是訓(xùn)練集和測試集,

  1. values = reframed.values 
  2. train_size = int(len(values)*0.70) 
  3. train = values[:train_size,:] 
  4. test = values[train_size:,:] 

拆分的數(shù)據(jù)集被拆分為trainX,trainY,testX和testY,

  1. trainX, trainY = train[:,:-1], train[:,13] 
  2. testX, testY = test[:,:-1], test[:,13] 

訓(xùn)練和測試數(shù)據(jù)集以3D尺寸重塑以用于LSTM,

  1. trainX = trainX.reshape((trainX.shape[0],1,trainX.shape[1])) 
  2. testX = testX.reshape((testX.shape[0],1,testX.shape[1])) 

創(chuàng)建LSTM模型并調(diào)整神經(jīng)元結(jié)構(gòu),

  1. model = Sequential() 
  2. model.add(LSTM(128, input_shape=(trainX.shape[1], trainX.shape[2]))) 
  3. model.add(Dropout(0.05)) 
  4. model.add(Dense(1)) 
  5. model.add(Activation(‘linear’)) 
  6. model.compile(loss=’mae’, optimizer=’adam’) 

通過使用trainX和trainY訓(xùn)練數(shù)據(jù)集,

  1. history = model.fit(trainX, trainY, epochs=10, batch_size=25, validation_data=(testX, testY), verbose=2, shuffle=False

計(jì)算每個(gè)訓(xùn)練時(shí)期的損耗值,并將其可視化,

  1. pyplot.plot(history.history[‘loss’], label=’train’) 
  2. pyplot.plot(history.history[‘val_loss’], label=’test’) 
  3. pyplot.title(“Test and Train set Loss Value Rate”) 
  4. pyplot.xlabel(‘Epochs Number’, fontsize=12) 
  5. pyplot.ylabel(‘Loss Value’, fontsize=12) 
  6. pyplot.legend() 
  7. pyplot.show() 

對訓(xùn)練數(shù)據(jù)集執(zhí)行預(yù)測過程,

  1. trainPredict = model.predict(trainX) 
  2. trainX = trainX.reshape((trainX.shape[0], trainX.shape[2])) 

對測試數(shù)據(jù)集執(zhí)行預(yù)測過程,

  1. testPredict = model.predict(testX) 
  2. testX = testX.reshape((testX.shape[0], testX.shape[2])) 

訓(xùn)練數(shù)據(jù)集反轉(zhuǎn)縮放比例以進(jìn)行訓(xùn)練,

  1. testPredict = model.predict(testX) 
  2. testX = testX.reshape((testX.shape[0], testX.shape[2])) 

測試數(shù)據(jù)集反轉(zhuǎn)縮放以進(jìn)行預(yù)測,

  1. testPredict = concatenate((testPredict, testX[:, -9:]), axis=1) 
  2. testPredict = scaler.inverse_transform(testPredict) 
  3. testPredict = testPredict[:,0] 
  4. # invert scaling for actual 
  5. testY = testY.reshape((len(testY), 1)) 
  6. inv_y = concatenate((testY, testX[:, -9:]), axis=1) 
  7. inv_y = scaler.inverse_transform(inv_y) 
  8. inv_y = inv_y[:,0] 

通過將mean_squared_error用于train和測試預(yù)測來計(jì)算性能指標(biāo),

  1. rmse2 = sqrt(mean_squared_error(trainY, trainPredict)) 
  2. rmse = sqrt(mean_squared_error(inv_y, testPredict)) 

訓(xùn)練和測試的預(yù)測集串聯(lián)在一起

  1. final = np.append(trainPredict, testPredict) 
  2. final = pd.DataFrame(data=final, columns=[‘Close’]) 
  3. actual = dataset.Close 
  4. actual = actual.values 
  5. actual = pd.DataFrame(data=actual, columns=[‘Close’]) 

最后,將訓(xùn)練和預(yù)測結(jié)果可視化。

  1. pyplot.plot(actual.Close, ‘b’, label=’Original Set’) 
  2. pyplot.plot(final.Close[0:16781], ‘r’ , label=’Training set’) 
  3. pyplot.plot(final.Close[16781:len(final)], ‘g’, 
  4.             label=’Predicted/Test set’) 
  5. pyplot.title(“ Bitcoin Predicted Prices”) 
  6. pyplot.xlabel(‘ Time’, fontsize=12) 
  7. pyplot.ylabel(‘Close Price’, fontsize=12) 
  8. pyplot.legend(loc=’best’) 
  9. pyplot.show() 

目前為止,我們使用歷史比特幣價(jià)格數(shù)據(jù)集開發(fā)價(jià)格預(yù)測模型,通過使用Python中的RNN和LSTM算法來找到價(jià)格預(yù)測。

 

責(zé)任編輯:武曉燕 來源: 區(qū)塊鏈研究實(shí)驗(yàn)室
相關(guān)推薦

2021-02-02 10:43:13

比特幣區(qū)塊鏈加密貨幣

2021-01-08 14:40:56

比特幣加密貨幣區(qū)塊鏈

2018-10-24 10:40:41

2021-01-12 16:07:37

比特幣礦工投資

2021-02-10 16:50:35

比特幣加密貨幣貨幣

2020-12-15 20:00:09

比特幣加密貨幣區(qū)塊鏈

2020-12-29 09:00:00

比特幣區(qū)塊鏈安全

2021-02-05 14:28:13

比特幣疫情數(shù)據(jù)

2019-11-25 00:01:25

Satan勒索病毒比特幣

2021-02-14 00:54:20

比特幣虛擬貨幣區(qū)塊鏈

2022-09-30 14:15:07

區(qū)塊鏈比特幣虛擬貨幣

2020-12-02 16:26:45

比特幣數(shù)字資產(chǎn)貨幣

2021-02-16 23:52:58

比特幣加密貨幣數(shù)據(jù)

2021-01-26 00:50:45

DDoS勒索攻擊網(wǎng)絡(luò)安全

2021-06-08 21:49:06

比特幣區(qū)塊鏈礦工

2021-03-10 09:12:16

比特幣區(qū)塊鏈加密貨幣

2022-01-05 22:56:49

比特幣加密貨幣貨幣

2018-07-05 15:37:46

2021-02-18 00:23:51

比特幣加密貨幣區(qū)塊鏈

2020-05-20 20:00:46

比特幣數(shù)字貨幣區(qū)塊鏈
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號