1、手動實現訓練集和測試集的切分
1. data_split()函數
??接下來我們開始實踐模型評估過程,首先是對訓練集和測試集的劃分,我們嘗試創建一個切分訓練集和測試集的函數。
def data_split(features, labels, rate=0.7):"""訓練集和測試集切分函數:param features: 輸入的特征張量:param labels:輸入的標簽張量:param rate:訓練集占所有數據的比例:return Xtrain, Xtest, ytrain, ytest:返回特征張量的訓練集、測試集,以及標簽張量的訓練集、測試集 """num_examples = len(features) # 總數據量indices = list(range(num_examples)) # 數據集行索引random.shuffle(indices) # 亂序調整num_train = int(num_examples * rate) # 訓練集數量 indices_train = torch.tensor(indices[: num_train]) # 在已經亂序的的indices中挑出前num_train數量的行索引值indices_test = torch.tensor(indices[num_train: ]) Xtrain = features[indices_train] # 訓練集特征ytrain = labels[indices_train] # 訓練集標簽Xtest = features[indices_test] # 測試集特征ytest = labels[indices_test] # 測試集標簽return Xtrain, Xtest, ytrain, ytest
- 測試函數性能
features = torch.arange(10) # 創建特征0-9
features
labels = torch.arange(1, 11) # 創建標簽1-10,保持和特征+1的關系
labels
data_split(features, labels)
- 實驗結果:
#f
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
#l
tensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
#fs
(tensor([2, 6, 3, 0, 7, 5, 9]),
tensor([1, 8, 4]),
#ls
tensor([ 3, 7, 4, 1, 8, 6, 10]),
tensor([2, 9, 5]))
2. 實踐練習
嘗試帶入訓練集進行建模,利用測試集評估模型建模效果
# 設置隨機數種子
torch.manual_seed(420) # 生成回歸類數據集
features, labels = tensorGenReg()# 切分訓練集和測試集
Xtrain, Xtest, ytrain, ytest = data_split(features, labels)# 初始化核心參數
batch_size = 10 # 小批的數量
lr = 0.03 # 學習率
num_epochs = 5 # 訓練過程遍歷幾次數據
w = torch.zeros(3, 1, requires_grad = True) # 隨機設置初始權重# 2、模型構建
def linreg(X,w): return torch.mm(X, w)# 3、損失函數 mse
def MSE_loss(yhat, y):total = y.numel()sse = torch.sum((yhat.reshape(-1, 1) - y.reshape(-1, 1)) ** 2) return sse / total# 4、優化算法
def sgd(params, lr):params.data -= lr * params.grad # (參數-學習率lr * 梯度)params.grad.zero_()# 5、訓練模型
# 參與訓練的模型方程
net = linreg # 使用回歸方程
loss = MSE_loss # 均方誤差的一半作為損失函數# 模型訓練過程
for epoch in range(num_epochs):for X, y in data_iter(batch_siz