柚子快報(bào)激活碼778899分享:回歸任務(wù)學(xué)習(xí)筆記
柚子快報(bào)激活碼778899分享:回歸任務(wù)學(xué)習(xí)筆記
天氣預(yù)測回歸任務(wù)學(xué)習(xí)筆記
1. 導(dǎo)入必要的庫
import numpy as np # 導(dǎo)入NumPy庫,主要用于數(shù)值計(jì)算和數(shù)組處理
import pandas as pd # 導(dǎo)入Pandas庫,用于數(shù)據(jù)處理和分析
import matplotlib.pyplot as plt # 導(dǎo)入Matplotlib庫,主要用于數(shù)據(jù)可視化
import torch # 導(dǎo)入PyTorch庫,用于構(gòu)建和訓(xùn)練深度學(xué)習(xí)模型
import torch.optim as optim # 從PyTorch中導(dǎo)入優(yōu)化器模塊,用于設(shè)置模型的優(yōu)化算法
import warnings # 導(dǎo)入warnings庫,用于處理警告信息
warnings.filterwarnings("ignore") # 忽略所有警告信息
%matplotlib inline # 在Jupyter Notebook中顯示Matplotlib繪制的圖像
2. 讀取數(shù)據(jù)
features = pd.read_csv('temps.csv') # 從 'temps.csv' 文件中讀取數(shù)據(jù)
print('數(shù)據(jù)維度:', features.shape) # 顯示數(shù)據(jù)維度
pd.read_csv() 函數(shù)用于從CSV文件中讀取數(shù)據(jù)并存儲為DataFrame,方便數(shù)據(jù)分析和處理。
3. 處理日期數(shù)據(jù)
import datetime # 導(dǎo)入 datetime 模塊,用于處理日期和時(shí)間
# 提取年、月、日并組合成日期
years = features['year']
months = features['month']
days = features['day']
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
4. 可視化數(shù)據(jù)
plt.style.use('fivethirtyeight') # 設(shè)置Matplotlib的繪圖風(fēng)格
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(10, 10)) # 創(chuàng)建子圖布局
fig.autofmt_xdate(rotation=45) # 自動調(diào)整x軸日期標(biāo)簽的格式
# 繪制不同的溫度曲線
ax1.plot(dates, features['actual'])
ax2.plot(dates, features['temp_1'])
ax3.plot(dates, features['temp_2'])
ax4.plot(dates, features['friend'])
plt.tight_layout(pad=2) # 自動調(diào)整子圖之間的間距
5. 獨(dú)熱編碼處理分類變量
features = pd.get_dummies(features) # 將分類變量進(jìn)行獨(dú)熱編碼
features.head(5) # 顯示獨(dú)熱編碼后的數(shù)據(jù)集的前5行
pd.get_dummies() 是處理分類變量的常用方法,將其轉(zhuǎn)換為適合機(jī)器學(xué)習(xí)模型的數(shù)值數(shù)據(jù)。
6. 準(zhǔn)備標(biāo)簽和特征
labels = np.array(features['actual']) # 提取標(biāo)簽
features = features.drop('actual', axis=1) # 去掉標(biāo)簽列
feature_list = list(features.columns) # 保存特征列名
features = np.array(features) # 轉(zhuǎn)換特征為NumPy數(shù)組
drop() 函數(shù)用于刪除DataFrame中的指定行或列。
總結(jié)
本次學(xué)習(xí)內(nèi)容涵蓋數(shù)據(jù)的讀取、預(yù)處理、可視化以及特征和標(biāo)簽的準(zhǔn)備。使用Pandas和Matplotlib庫進(jìn)行數(shù)據(jù)操作和可視化,使用PyTorch進(jìn)行模型構(gòu)建與訓(xùn)練。通過獨(dú)熱編碼將分類變量轉(zhuǎn)換為數(shù)值數(shù)據(jù),以便用于機(jī)器學(xué)習(xí)模型。
7. 數(shù)據(jù)標(biāo)準(zhǔn)化
在訓(xùn)練神經(jīng)網(wǎng)絡(luò)之前,首先對輸入特征進(jìn)行標(biāo)準(zhǔn)化,以確保它們具有均值為0和方差為1的分布。這有助于提高模型的訓(xùn)練效率和收斂速度。
from sklearn import preprocessing # 導(dǎo)入預(yù)處理模塊
input_features = preprocessing.StandardScaler().fit_transform(features) # 標(biāo)準(zhǔn)化數(shù)據(jù)
StandardScaler: 計(jì)算每列的均值和標(biāo)準(zhǔn)差,并將數(shù)據(jù)轉(zhuǎn)換為標(biāo)準(zhǔn)正態(tài)分布。
8. 構(gòu)建神經(jīng)網(wǎng)絡(luò)模型
方法1: 手動構(gòu)建模型
import torch
# 將輸入特征和標(biāo)簽轉(zhuǎn)換為 PyTorch 張量
x = torch.tensor(input_features, dtype=float)
y = torch.tensor(labels, dtype=float)
# 權(quán)重和偏置初始化
weights = torch.randn((14, 128), dtype=float, requires_grad=True) # 隱藏層權(quán)重
biases = torch.randn(128, dtype=float, requires_grad=True) # 隱藏層偏置
weights2 = torch.randn((128, 1), dtype=float, requires_grad=True) # 輸出層權(quán)重
biases2 = torch.randn(1, dtype=float, requires_grad=True) # 輸出層偏置
# 學(xué)習(xí)率和損失記錄
learning_rate = 0.001
losses = []
for i in range(1000): # 訓(xùn)練迭代次數(shù)
hidden = x.mm(weights) + biases # 隱層輸出
hidden = torch.relu(hidden) # ReLU 激活函數(shù)
predictions = hidden.mm(weights2) + biases2 # 輸出層預(yù)測值
loss = torch.mean((predictions - y) ** 2) # 均方誤差損失
losses.append(loss.data.numpy()) # 記錄損失
if i % 100 == 0:
print('loss:', loss)
loss.backward() # 反向傳播
# 更新參數(shù)
weights.data.add_(-learning_rate * weights.grad.data)
biases.data.add_(-learning_rate * biases.grad.data)
weights2.data.add_(-learning_rate * weights2.grad.data)
biases2.data.add_(-learning_rate * biases2.grad.data)
# 清空梯度
weights.grad.data.zero_()
biases.grad.data.zero_()
weights2.grad.data.zero_()
biases2.grad.data.zero_()
方法2: 使用 torch.nn.Sequential 構(gòu)建模型
input_size = input_features.shape[1]
hidden_size1 = 128
hidden_size2 = 64
hidden_size3 = 32
output_size = 1
batch_size = 16 # 小批量大小
# 定義神經(jīng)網(wǎng)絡(luò)模型
my_nn = torch.nn.Sequential(
torch.nn.Linear(input_size, hidden_size1),
torch.nn.Sigmoid(),
torch.nn.Linear(hidden_size1, hidden_size2),
torch.nn.Sigmoid(),
torch.nn.Linear(hidden_size2, hidden_size3),
torch.nn.Sigmoid(),
torch.nn.Linear(hidden_size3, output_size)
)
# 定義損失函數(shù)和優(yōu)化器
cost = torch.nn.MSELoss(reduction='mean')
optimizer = torch.optim.Adam(my_nn.parameters(), lr=0.001)
9. 訓(xùn)練網(wǎng)絡(luò)
使用小批量(Mini-Batch)方法進(jìn)行訓(xùn)練,并記錄每次迭代的平均損失。
losses = []
for i in range(1000):
batch_loss = [] # 初始化每次迭代的損失記錄
for start in range(0, len(input_features), batch_size):
end = start + batch_size if start + batch_size < len(input_features) else len(input_features)
xx = torch.tensor(input_features[start:end], dtype=torch.float, requires_grad=True)
yy = torch.tensor(labels[start:end], dtype=torch.float, requires_grad=True)
prediction = my_nn(xx)
loss = cost(prediction, yy)
optimizer.zero_grad()
loss.backward(retain_graph=True)
optimizer.step()
batch_loss.append(loss.data.numpy())
if i % 100 == 0:
losses.append(np.mean(batch_loss))
print(i, np.mean(batch_loss))
10. 進(jìn)行預(yù)測
將輸入特征傳入訓(xùn)練好的模型,獲取預(yù)測結(jié)果。
predict = my_nn(x).data.numpy() # 獲取模型預(yù)測值
11. 可視化結(jié)果
將真實(shí)值和預(yù)測值進(jìn)行對比,以可視化模型性能。
# 轉(zhuǎn)換日期格式
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
# 創(chuàng)建 DataFrame 存儲真實(shí)值和預(yù)測值
true_data = pd.DataFrame(data={'date': dates, 'actual': labels})
predictions_data = pd.DataFrame(data={'date': test_dates, 'prediction': predict.reshape(-1)})
# 繪圖
plt.plot(true_data['date'], true_data['actual'], 'b-', label='actual') # 真實(shí)值
plt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label='prediction') # 預(yù)測值
plt.xticks(rotation=60) # x軸標(biāo)簽旋轉(zhuǎn)
plt.legend() # 顯示圖例
plt.xlabel('Date') # x軸標(biāo)簽
plt.ylabel('Maximum Temperature (F)') # y軸標(biāo)簽
plt.title('Actual and Predicted Values') # 圖表標(biāo)題
總結(jié)
通過數(shù)據(jù)標(biāo)準(zhǔn)化、神經(jīng)網(wǎng)絡(luò)模型構(gòu)建、訓(xùn)練及結(jié)果可視化,完成了天氣預(yù)測的回歸任務(wù)。使用了多層感知器(MLP)模型,并對比了手動構(gòu)建模型和使用 torch.nn.Sequential 的方法。訓(xùn)練過程中采用了小批量梯度下降法,記錄并分析了模型的損失值變化。
涉及函數(shù) 好的,以下是你學(xué)習(xí)筆記中每部分涉及到的主要函數(shù)總結(jié):
1. 導(dǎo)入必要的庫
import: 用于導(dǎo)入所需的庫和模塊。
2. 讀取數(shù)據(jù)
pd.read_csv('temps.csv'): 從 CSV 文件中讀取數(shù)據(jù)并存儲為 DataFrame。features.shape: 獲取 DataFrame 的維度。
3. 處理日期數(shù)據(jù)
zip(): 將多個(gè)可迭代對象聚合成元組。datetime.datetime.strptime(date, '%Y-%m-%d'): 將字符串轉(zhuǎn)換為日期對象。
4. 可視化數(shù)據(jù)
plt.style.use('fivethirtyeight'): 設(shè)置繪圖風(fēng)格。plt.subplots(nrows=2, ncols=2, figsize=(10, 10)): 創(chuàng)建子圖布局。ax.plot(x, y): 繪制數(shù)據(jù)曲線。plt.tight_layout(pad=2): 自動調(diào)整子圖間距。
5. 獨(dú)熱編碼處理分類變量
pd.get_dummies(features): 將分類變量進(jìn)行獨(dú)熱編碼。
6. 準(zhǔn)備標(biāo)簽和特征
np.array(): 將數(shù)據(jù)轉(zhuǎn)換為 NumPy 數(shù)組。features.drop('actual', axis=1): 去掉標(biāo)簽列。
7. 數(shù)據(jù)標(biāo)準(zhǔn)化
preprocessing.StandardScaler(): 創(chuàng)建標(biāo)準(zhǔn)化對象。fit_transform(features): 計(jì)算均值和標(biāo)準(zhǔn)差并標(biāo)準(zhǔn)化數(shù)據(jù)。
8. 構(gòu)建神經(jīng)網(wǎng)絡(luò)模型
torch.tensor(data, dtype=float): 將數(shù)據(jù)轉(zhuǎn)換為 PyTorch 張量。torch.randn(size, dtype=float, requires_grad=True): 隨機(jī)初始化權(quán)重和偏置。torch.relu(): 應(yīng)用 ReLU 激活函數(shù)。
9. 訓(xùn)練網(wǎng)絡(luò)
loss.backward(): 反向傳播計(jì)算梯度。optimizer.zero_grad(): 清空梯度。optimizer.step(): 更新模型參數(shù)。
10. 進(jìn)行預(yù)測
my_nn(x): 將輸入特征傳入模型以獲取預(yù)測值。
11. 可視化結(jié)果
pd.DataFrame(data={...}): 創(chuàng)建 DataFrame 存儲數(shù)據(jù)。plt.plot(x, y): 繪制真實(shí)值和預(yù)測值的對比圖。plt.legend(): 顯示圖例。plt.xlabel() 和 plt.ylabel(): 設(shè)置 x 軸和 y 軸的標(biāo)簽。
總結(jié)
本部分涵蓋了數(shù)據(jù)的讀取、處理、可視化以及模型構(gòu)建和訓(xùn)練所用到的函數(shù),提供了一個(gè)完整的天氣預(yù)測回歸任務(wù)的流程。
如果需要更深入的討論或者對某個(gè)函數(shù)的具體用法有疑問,歡迎隨時(shí)提問!
柚子快報(bào)激活碼778899分享:回歸任務(wù)學(xué)習(xí)筆記
好文推薦
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。