Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

PyTorch how to build ANN to realize time Series Wind Speed Forecast

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces PyTorch how to build ANN to achieve time series wind speed prediction related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this PyTorch how to build ANN to achieve time series wind speed prediction article will have a harvest, let's take a look.

Data set

The data set is the meteorological data of Barcelona for a certain period of time, including temperature, humidity, wind speed and so on. In this paper, we will simply build up to predict the wind speed.

Characteristic structure

For the prediction of wind speed, in addition to considering the historical wind speed data, we should also fully consider the influence of other meteorological factors. Therefore, we predict the wind speed at the next moment based on the wind speed of the first 24 moments plus the rest of the meteorological data of the next moment.

Data processing 1. Data preprocessing

In the data preprocessing stage, the text data on some columns are converted into numerical data, and the original data is normalized at the same time. The text data is as follows:

After conversion, each of the above categories is assigned different values, such as "sky is clear" is 0 and "few clouds" is 1.

Def load_data (): global Max, Min df = pd.read_csv ('Barcelona/Barcelona.csv') df.drop_duplicates (subset= [df.columns [0]], inplace=True) # weather_main listType = df [' weather_main'] .unique () df.fillna (method='ffill' Inplace=True) dic = dict.fromkeys (listType) for i in range (len (listType)): Dickey [df ['weather_main'] = df [' weather_main'] .map (dic) # weather_description listType = df ['weather_description'] .unique () dic = dict.fromkeys (listType) for i in range (len (listType)): Dickey [listType.I] = I df ['weather_description'] = df [' weather_description'] .map (dic) # weather_icon listType = df ['weather_icon'] .unique () dic = dict.fromkeys (listType) for i in range (len (listType)): dic [listType [I] = I df [' weather_icon'] = df ['weather_icon'] .map (dic) # print (df) columns = df.columns Max = np. Max (df ['wind_speed']) # Normalized Min = np.min (df [' wind_speed']) for i in range (2 17): column = columns [I] if column = 'wind_speed': continue df [column] = DF [column] .astype (' float64') if len (DF [df [column] = = 0]) = = len (df): # all 0 continue mx = np.max (DF [column]) mn = np.min (DF [co lumn]) df [column] = (df [column]-mn) / (mx-mn) # print (df.isna (). Sum ()) return df2. Data set construction

The meteorological data of the current moment and the wind speed data of the first 24 hours are used to predict the wind speed of the current moment:

Def nn_seq (): "": param flag:: param data: data to be processed: return: X and Y data sets, X = [year of the current time Month, hour, day, lowtemp, hightemp Load at the current moment of the previous day and 23 hours before] Y = [current load] "" print ('processing data:') data = load_data () speed = data ['wind_speed'] speed = speed.tolist () speed = torch.FloatTensor (speed). View (- 1) data = data.values.tolist () Seq = [] for i in range (len (data)-30): train_seq = [] train_label = [] for j in range (I I + 24): train_seq.append (speed [j]) # add temperature, humidity, air pressure and other information for c in range (2,7): train_seq.append (data [I + 24] [c]) for c in range (8 17): train_seq.append (data [I + 24] [c]) train_label.append (speed [I + 24]) train_seq = torch.FloatTensor (train_seq). View (- 1) train_label = torch.FloatTensor (train_label). View (- 1) seq.append ((train_seq) Train_label) # print (seq [: 5]) Dtr = seq [0:int (len (seq) * 0.5)] Den = seq [int (len (seq) * 0.50): int (len (seq) * 0.75)] Dte = seq [int (len (seq) * 0.75): len (seq)] return Dtr, Den, Dte

Arbitrarily output one of the pieces of data:

(tensor ([1.0000e+00, 1.0000e+00, 2.0000e+00, 1.0000e+00, 1.0000e+00, 1.0000e+00, 1.0000e+00, 1.0000e+00, 0.0000e+00, 1.0000e+00, 5.0000e+00, 0.0000e+00, 2.0000e+00, 0.0000e+00, 0.0000e+00, 5.0000e+00, 0.0000e+00, 2.0000e+00, 2.0000e+00, 5.0000e+00, 6.0000e+00, 5.0000e+00, 5.0000e+00, 5.0000e+00, 5.3102e-01, 5.5466e-01 4.6885e-01, 1.0066e-03, 5.8000e-01, 6.6667e-01, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 9.9338e-01, 0.0000e+00, 0.0000e+00, 0.0000e+00]), tensor ([5.])

The data is divided into three parts: Dtr, Den and Dte,Dtr as the training set and Dte as the test set.

ANN model 1. Model training

The ANN model is built as follows:

Def ANN (): Dtr, Den, Dte = nn_seq () my_nn = torch.nn.Sequential (torch.nn.Linear (38,64), torch.nn.ReLU (), torch.nn.Linear (64,128), torch.nn.ReLU (), torch.nn.Linear (128,1) ) model = my_nn.to (device) loss_function = nn.MSELoss (). To (device) optimizer = torch.optim.Adam (model.parameters (), lr=0.001) train_inout_seq = Dtr # training epochs = 50 for i in range (epochs): print ('current', I) for seq Labels in train_inout_seq: seq = seq.to (device) labels = labels.to (device) y_pred = model (seq) single_loss = loss_function (y_pred) Labels) optimizer.zero_grad () single_loss.backward () optimizer.step () # if I% 2 = = 1: print (f'epoch: {single_loss.item 3} loss: {single_loss.item (): 10.8f}') print (f'epoch: {single_loss.item (): 10.10f}') state = {'model': model.state_dict () 'optimizer': optimizer.state_dict (),' epoch': epochs} torch.save (state, 'Barcelona' + ANN_PATH)

As you can see, the code snippet defined by the model is:

My_nn = torch.nn.Sequential (torch.nn.Linear (38,64), torch.nn.ReLU (), torch.nn.Linear (64,128), torch.nn.ReLU (), torch.nn.Linear (128,1),)

The input dimension of the first layer is 38 (wind speed in the first 24 hours + 14 kinds of meteorological data) and the output dimension is 64; the second layer input is 64 and the output is 128; the third layer input is 128 and the output is 1.

two。 Model prediction and performance def ANN_predict (ann, test_seq): pred = [] for seq, labels in test_seq: seq = seq.to (device) with torch.no_grad (): pred.append (ann (seq). Item ()) pred = np.array ([pred]) return pred

Test:

Def test (): Dtr, Den, Dte = nn_seq () ann = torch.nn.Sequential (torch.nn.Linear (38,64), torch.nn.ReLU (), torch.nn.Linear (64,128), torch.nn.ReLU (), torch.nn.Linear (128,1) ) ann = ann.to (device) ann.load_state_dict (torch.load ('Barcelona' + ANN_PATH) [' model']) ann.eval () pred = ANN_predict (ann, Dte) print (mean_absolute_error (te_y, pred2.T), np.sqrt (mean_squared_error (te_y, pred2.T)

The performance of ANN on Dte is shown in the following table:

MAERMSE1.041.46

This is the end of the article on "how to build PyTorch ANN to achieve time series wind speed prediction". Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report