1. 程式人生 > 實用技巧 >總是遇到奇怪問題一

總是遇到奇怪問題一

遇到報錯:ValueError: optimizer got an empty parameter list

在pycharm上也是報相同的錯誤

完整程式碼:

 1 import torch
 2 import torch.nn as nn
 3 from torch.optim import SGD
 4 import torch.utils.data as Data
 5 from sklearn.datasets import load_boston
 6 from sklearn.preprocessing import StandardScaler
 7 import pandas as pd
8 import numpy as np 9 import matplotlib.pyplot as plt 10 ##讀取資料 11 boston_X,boston_y= load_boston(return_X_y=True) 12 print("boston_X.shape:",boston_X.shape) 13 plt.figure() 14 plt.hist(boston_y,bins=20) 15 plt.show() 16 ##資料標準化處理 17 ss = StandardScaler(with_mean=True,with_std=True) 18 boston_Xs= ss.fit_transform(boston_X)
19 ##將資料預處理為可以使用pytorch進行批量訓練的形式 20 ##訓練X轉化為張量 21 train_xt= torch.from_numpy(boston_Xs.astype(np.float32)) 22 ##訓練集y轉化為張量 23 train_yt = torch.from_numpy(boston_y.astype(np.float32)) 24 ##將訓練集轉化為張量後,使用TensorDataset將X和Y整理到一起 25 train_data = Data.TensorDataset(train_xt,train_yt) 26 ##定義一個數據載入器,將訓練資料集進行批量處理
27 train_loader = Data.DataLoader( 28 dataset = train_data, ##使用的資料集 29 batch_size = 128, ##批量處理樣本的大小 30 shuffle = True, ##每次迭代前打亂資料 31 num_workers = 1, ##使用兩個程序 32 ) 33 ##使用繼承Module的方式定義全連線神經網路 34 class MLPmodel(nn.Module): 35 def _init_(self): 36 super(MLPmodel,self)._init_() 37 ##定義第一個隱藏層 38 self.hidden1 = nn.Linear( 39 in_features = 13, ##第一個隱藏層的輸入,資料的特徵數 40 out_feature = 10, ##第一個隱藏層的輸出,神經元的數量 41 bias = True, 42 ) 43 self.activel = nn.ReLU() 44 ##定義第二個隱藏層 45 self.hidden2 = nn.Linear(10,10) 46 self.active2 = nn.ReLU() 47 ##定義預測迴歸層 48 self.regression = nn.Linear(10,1) 49 ##定義網路的前向傳播路徑 50 def forward(self, x): 51 x=self.hidden1(x) 52 x=self.active1(x) 53 x=self.hidden2(x) 54 x=self.active2(x) 55 output=self.regression(x) 56 ##輸出為output 57 return output 58 ##輸出網路結構 59 mlp1 = MLPmodel() 60 print(mlp1) 61 ##對迴歸模型mlp1進行訓練並輸出損失函式的變化情況,定義優化器和損失函式 62 optimizer = SGD(mlp1.parameters(),lr=0.001) 63 loss_func = nn.MSELoss() ##最小均方根誤差 64 train_loss_all = [ ] ##輸出每個批次訓練的損失函式 65 ##進行訓練,並輸出每次迭代的損失函式 66 for epoch in range(30): 67 ##對訓練資料的載入器進行迭代計算 68 for step,(b_x,b_y) in enumerate(train_loader): 69 output = mlp1(b_x).flatten() ##MLP在訓練batch上的輸出 70 train_loss = loss_func(output,b_y) ##均方根誤差 71 optimizer.zero_grad() ##每個迭代步的梯度初始化為0 72 train_loss.backward() ##損失的向後傳播,計算梯度 73 optimizer.step() ##使用梯度進行優化 74 train_loss_all.append(train_loss.item()) 75 plt.figure() 76 plt.plot(train_loss_all,"r-") 77 plt.title("Train loss per iteration") 78 plt.show()
View Code