深度学习笔记(1)

130 阅读7分钟

搭建PyTorch神经网络进行气温预测

搭建过程

导入相关库

其中warnings是在运行代码时,对一些正常运行的代码做出处理,ignore为不发出警报

warnings.filterwarnings(action, 
			message='', 
			category=Warning, 
			module='', 
			lineno=0, 
			append=False)

过滤警告,在 警告过滤器规则 列表中插入一个条目。默认情况下,条目插入在前面;如果append为真,则在末尾插入。它检查参数的类型,编译messagemodule的正则表达式,并将它们作为警告过滤器列表中的元组插入。如果多个地方都匹配特定的警告,那么更靠近列表前面的条目会覆盖列表中后面的条目,省略的参数默认为匹配一切的值。

action是以下表格左侧的值:

处理方式
“error”将匹配警告转换为异常
“ignore”忽略匹配的警告
“always”始终输出匹配的警告
“default”对于同样的警告只输出第一次出现的警告
“module”在一个模块中只输出第一次出现的警告
“once”输出第一次出现的警告,而不考虑它们的位置

message是包含正则表达式的字符串,警告消息的开始必须匹配,不区分大小写

category是一个警告类型(必须是 Warning 的子类)

module是包含模块名称的正则表达式字符串,区分大小写

lineno是一个整数,警告发生的行号,为 0 则匹配所有行号

读取数据,查看数据,处理数据

features = pd.read_csv('temps.csv')

#看看数据长什么样子
features.head()

print('数据维度:', features.shape)

# 处理时间数据
import datetime

# 分别得到年,月,日
years = features['year']
months = features['month']
days = features['day']

# datetime格式
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]

strptime:
p表示parse,表示分析的意思,所以strptime是给定一个时间字符串和分析模式,返回一个时间对象
strftime:
f表示format,表示格式化,和strptime正好相反,要求给一个时间对象和输出格式,返回一个时间字符串

绘制图像

# 准备画图
# 指定默认风格
plt.style.use('fivethirtyeight')

# 设置布局
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (10,10))
fig.autofmt_xdate(rotation = 45)

# 标签值
ax1.plot(dates, features['actual'])
ax1.set_xlabel(''); ax1.set_ylabel('Temperature'); ax1.set_title('Max Temp')

# 昨天
ax2.plot(dates, features['temp_1'])
ax2.set_xlabel(''); ax2.set_ylabel('Temperature'); ax2.set_title('Previous Max Temp')

# 前天
ax3.plot(dates, features['temp_2'])
ax3.set_xlabel('Date'); ax3.set_ylabel('Temperature'); ax3.set_title('Two Days Prior Max Temp')

# 我的逗逼朋友
ax4.plot(dates, features['friend'])
ax4.set_xlabel('Date'); ax4.set_ylabel('Temperature'); ax4.set_title('Friend Estimate')

plt.tight_layout(pad=2)

创建子图布局fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(10,10)) 创建一个包含 2 行 2 列的子图布局,整体图形大小为 10x10 英寸。

ax1ax2ax3ax4 是四个子图的坐标轴对象。

自动格式化日期fig.autofmt_xdate(rotation=45) 会自动格式化 x 轴的日期标签,并将其旋转 45 度,以避免重叠。

绘制数据

ax1.plot(dates, features['actual']) 在第一个子图(ax1)上绘制实际温度数据。dates 是 x 轴数据,features['actual'] 是 y 轴数据。

  • 独热编码:独热编码(One-Hot Encoding)是一种将分类数据转换为数值格式的方法。在独热编码中,每个类别用一个二进制向量表示,其中只有一个位置为1,其余位置为0。具体来说:
# 独热编码
features = pd.get_dummies(features)
features.head(5)

pd.get_dummies(features):将 features 数据框中的所有分类特征转换为独热编码形式,自动生成新的列,表示每个类别的存在与否。

# 标签
labels = np.array(features['actual'])

# 在特征中去掉标签
features= features.drop('actual', axis = 1) # axis = 1证明删除的是列

# 名字单独保存一下,以备后患
feature_list = list(features.columns)

# 转换成合适的格式
features = np.array(features)
DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

参数说明

  • labels: 要删除的行或列的标签,可以是单个标签或列表。axis = 0删除行,axis = 1删除列,默认删除行。
  • axis: 指定要删除的是行还是列。0 表示删除行(默认),1 表示删除列。
  • index: 指定要删除的行的标签,可以是单个标签或列表。
  • columns: 指定要删除的列的标签,可以是单个标签或列表。
  • level: 如果是多级索引,指定要删除的级别。
  • inplace: 如果为 True,则直接在原数据框上进行操作,而不返回新的数据框;如果为 False(默认),则返回一个新的数据框。
  • errors: 指定在标签不存在时的行为,'raise'(默认)会引发错误,'ignore' 将忽略不存在的标签

构建网络模型

  • preprocessing.StandardScaler() : 创建一个标准化转换器对象。该对象将计算特征数据的均值和标准差。

  • fit_transform(features) :

    • fit: 计算输入数据 features 的均值和标准差。
    • transform: 使用计算出的均值和标准差将数据标准化,即将数据转化为均值为0、标准差为1的分布。
from sklearn import preprocessing
input_features = preprocessing.StandardScaler().fit_transform(features)
input_features[0]
1. 数据转换
x = torch.tensor(input_features, dtype = float)
y = torch.tensor(labels, dtype = float)

2. # 权重参数初始化
weights = torch.randn((14, 128), dtype = float, requires_grad = True) 
biases = torch.randn(128, dtype = float, requires_grad = True) 
weights2 = torch.randn((128, 1), dtype = float, requires_grad = True) 
biases2 = torch.randn(1, dtype = float, requires_grad = True) 

# **`torch.randn(...)`** : 生成符合标准正态分布(均值为0,标准差为1)的随机数,构造权重和偏置。
# **`requires_grad=True`**: 表示这些张量需要计算梯度,以便在反向传播时更新。

3. 学习率和损失函数
learning_rate = 0.001 
losses = []

for i in range(1000):
    # 计算隐层
    hidden = x.mm(weights) + biases
    # 加入激活函数
    hidden = torch.relu(hidden)
    # 预测结果
    predictions = hidden.mm(weights2) + biases2
    # 通计算损失
    loss = torch.mean((predictions - y) ** 2) 
    losses.append(loss.data.numpy())
    
    # 打印损失值
    if i % 100 == 0:
        print('loss:', loss)
    #返向传播计算
    loss.backward()
    
    #更新参数
    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_()
  • 输入层、隐藏层(特征提取重要层)、输出层
  • 激活函数:从数学上看,神经网络是一个多层复合函数。激活函数在很早以前就被引入,其作用是保证神经网络的非线性,因为线性函数无论怎样复合结果还是线性的。激活函数的基本要求必须是非线性的

训练网络:Mini-Batch的方法

一种情况是采用Full-Batch来训练数据;

还有一种情况是在随机梯度下降中,只随机取其中一个数据来计算梯度。其中随机梯度下降可以很好的解决训练数据时遇到的鞍点问题,但是会导致训练时间过长。

所以,接下来我们要学习的是采用Mini-Batch的方法来训练数据,这种方法的优点是可以均衡性能和训练时间上的需求。

采用Mini-Batch的方法来训练数据时,需要使用Dataset和DataLoader两个工具类:

Dataset:用来构造数据集,使数据集可以通过索引快速取出DataLoader:取出一个Mini-Batch,一组数据,采用Mini-Batch训练数据需要掌握的三个概念:

Epoch:1次epoch表示把所有的训练样本都进行了一次前馈和反馈的训练;

Batch-Size:表示一次前馈和反馈所使用的样本数量;

Iteration:将样本一共分成了几个Mini-Batch。 例:10000个样本,其中Batch-size=1000,则Iteration=10000/1000=10。

训练网络

losses = []
for i in range(1000):
    batch_loss = []
    # MINI-Batch方法来进行训练
    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))

预测训练结果

x = torch.tensor(input_features, dtype = torch.float)
predict = my_nn(x).data.numpy()

# 转换日期格式
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]

# 创建一个表格来存日期和其对应的标签数值
true_data = pd.DataFrame(data = {'date': dates, 'actual': labels})

# 同理,再创建一个来存日期和其对应的模型预测值
months = features[:, feature_list.index('month')]
days = features[:, feature_list.index('day')]
years = features[:, feature_list.index('year')]

test_dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]

test_dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in test_dates]

predictions_data = pd.DataFrame(data = {'date': test_dates, 'prediction': predict.reshape(-1)}) 

# 真实值
plt.plot(true_data['date'], true_data['actual'], 'b-', label = 'actual')

# 预测值
plt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label = 'prediction')
plt.xticks(rotation = 60); 
plt.legend()

# 图名
plt.xlabel('Date'); 
plt.ylabel('Maximum Temperature (F)'); 
plt.title('Actual and Predicted Values');