山东大学神经网络与深度学习 实验1
一个和另外一个同学准备构建ing资源分享网站,求建议(用户名test,密码随意)
github
CSDN上的还得上传图片,github上有完整的带图片的
jupyter:
kernelspec:
display_name: venv
language: python
name: python3
language_info:
codemirror_mode:
name: ipython
version: 3
file_extension: .py
mimetype: text/x-python
name: python
nbconvert_exporter: python
pygments_lexer: ipython3
version: 3.8.10
nbformat: 4
nbformat_minor: 2
::: {.cell .code execution_count=“32”}
import torch
import matplotlib.pyplot as plt
import torch.nn as nn
from torch.utils.data import DataLoader,TensorDataset
:::
::: {.cell .markdown}
构造数据
:::
::: {.cell .code execution_count=“33”}
nums_data = 100
x = torch.linspace(0, 1, nums_data).unsqueeze(dim=1)
k = 2
#添加随机噪声
y = k * x + torch.randn(x.size()) * 0.1
# 可视化原始数据
plt.scatter(x.numpy(), y.numpy(),marker='x',s=10)
plt.title("origin_data")
plt.show()
::: {.output .display_data}
:::
:::
::: {.cell .markdown}
定义线性模型类
:::
::: {.cell .code execution_count=“34”}
class LinearModel(nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.linear = nn.Linear(1, 1)
def forward(self, x):
return self.linear(x)
:::
::: {.cell .markdown}
定义训练的criterion,optimizer,dataloader
:::
::: {.cell .code execution_count=“35”}
model = LinearModel()
#使用均方误差作为损失函数
criterion = nn.MSELoss()
#随机梯度下降优化
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)#学习率
data_set=TensorDataset(x,y)
#数据分批次
#这里一共100个数据,分成10份,也就是一个batch10个数据
data_loader=DataLoader(data_set,batch_size=10,shuffle=True)
:::
::: {.cell .markdown}
展示初始化的模型的预测结果
:::
::: {.cell .code execution_count=“36”}
outputs=model(x)
plt.scatter(x.numpy(),outputs.detach().numpy(),marker='o',c='red',s=10)
plt.scatter(x,y,marker='x',s=10)
::: {.output .execute_result execution_count=“36”}
<matplotlib.collections.PathCollection at 0x7f75bbe83310>
:::
::: {.output .display_data}
:::
:::
::: {.cell .markdown}
训练
:::
::: {.cell .code execution_count=“37”}
num_epochs = 100
step=0
for epoch in range(num_epochs):
#因为要求展示训练几个step的,所以对训练数据分批次训练
model.train()#确保模型处于训练状态
for x_batch,y_batch in data_loader:
optimizer.zero_grad()#每次训练独立,清空梯度
outputs=model(x_batch)
loss=criterion(outputs,y_batch)
loss.backward()
optimizer.step()
#展示训练两个step的模型
outputs=model(x)
step+=1
if(step==2):
plt.scatter(x.numpy(), y.numpy(),s=10,marker='x', label='step 2')
plt.scatter(x.numpy(), outputs.detach().numpy(), c='red', s=10,marker='o',label='fit line')
plt.legend()
plt.show()
if epoch == 0:
plt.scatter(x.numpy(), y.numpy(),s=10,marker='x', label='epoch 1')
plt.scatter(x.numpy(), outputs.detach().numpy(), c='red', s=10,marker='o',label='fit line')
plt.legend()
plt.show()
::: {.output .display_data}
:::
::: {.output .display_data}
:::
:::
::: {.cell .markdown}
最终训练结果可视化
:::
::: {.cell .code execution_count=“38”}
model.eval()
with torch.no_grad():
final_outputs = model(x)
plt.scatter(x.numpy(), y.numpy(),s=10,marker='x', label='Original Data')
plt.scatter(x.numpy(), final_outputs.numpy(), c='red', s=10,marker='o',label='fit')
plt.title("final")
plt.legend()
plt.show()
::: {.output .display_data}
:::
:::