PyTorch 深度学习实践 第2讲/作业(Linear Model)

对一组数据进行预测

 训练损失和MSE均方误差损失

 代码示例 y = w * x

import numpy as np
import matplotlib.pyplot as plt

# 准备数据
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

# 定义模型 y = x * w
def forward(x):
    return x * w

def loss(x, y):
    y_pred = forward(x) # y_pred为模型预测值
    return (y_pred - y) ** 2

# 穷举法
w_list = []
mse_list = []
for w in np.arange(0.0, 4.1, 0.1):
    print("w=", w)
    l_sum = 0
    for x_val, y_val in zip(x_data, y_data):
        y_pred_val = forward(x_val) # 只是为了下面打印y_pred_val
        loss_val = loss(x_val, y_val)
        l_sum += loss_val
        print('\t', x_val, y_val, y_pred_val, loss_val)
    print('MSE=', l_sum / 3)
    w_list.append(w)
    mse_list.append(l_sum / 3)

plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()

结果展示

 作业 y = w * x + b

import numpy
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

def forward(x):
    return x * w + b

def loss(x, y):
    y_pred = forward(x)
    return (y_pred - y) ** 2


w = numpy.arange(0.0, 4.1, 0.1) # 权重W从0.0到4.0间隔0.1取数
b = numpy.arange(-2.0, 2.1, 0.1) # 偏置B从-2.0到2.0间隔0.1取数

[w, b] = numpy.meshgrid(w, b) # [X,Y]=np.meshgrid(x,y) 函数用两个坐标轴上的点在平面上画网格。

l_sum = 0
for x_val, y_val in zip(x_data, y_data):
    # y_pred_val = forward(x_val)
    loss_val = loss(x_val, y_val)
    l_sum += loss_val
    
fig = plt.figure()
ax = Axes3D(fig)
ax.set_xlabel("w")
ax.set_ylabel("b")
ax.set_zlabel("loss")
ax.plot_surface(w, b, l_sum/3, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow')) #画曲面图---Axes3D.plot_surface(X, Y, Z)
plt.show()

结果展示 

 reference

《PyTorch深度学习实践》完结合集_哔哩哔哩_bilibili

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的用PyTorch写SD点云深度学习代码的例子: ```python import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader import numpy as np # 定义数据集 class SDDataset(Dataset): def __init__(self, data_path): self.data = np.load(data_path) def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] # 定义模型 class SDNet(nn.Module): def __init__(self): super(SDNet, self).__init__() self.conv1 = nn.Conv2d(1, 16, kernel_size=3, stride=1, padding=1) self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1) self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) self.conv3 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1) self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2) self.fc1 = nn.Linear(64 * 6 * 6, 512) self.fc2 = nn.Linear(512, 10) def forward(self, x): x = self.conv1(x) x = nn.functional.relu(x) x = self.pool1(x) x = self.conv2(x) x = nn.functional.relu(x) x = self.pool2(x) x = self.conv3(x) x = nn.functional.relu(x) x = self.pool3(x) x = x.view(-1, 64 * 6 * 6) x = nn.functional.relu(self.fc1(x)) x = self.fc2(x) return x # 训练代码 def train(model, train_loader, criterion, optimizer, device): model.train() train_loss = 0 for batch_idx, data in enumerate(train_loader): inputs = data[:, :, :, :3] targets = data[:, :, :, 3] inputs = inputs.to(device) targets = targets.to(device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() train_loss += loss.item() return train_loss / len(train_loader) # 测试代码 def test(model, test_loader, criterion, device): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data in test_loader: inputs = data[:, :, :, :3] targets = data[:, :, :, 3] inputs = inputs.to(device) targets = targets.to(device) outputs = model(inputs) test_loss += criterion(outputs, targets).item() preds = outputs.argmax(dim=1) correct += preds.eq(targets.view_as(preds)).sum().item() test_loss /= len(test_loader.dataset) accuracy = correct / len(test_loader.dataset) return test_loss, accuracy # 主函数 def main(): # 设置参数 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") epochs = 10 batch_size = 64 learning_rate = 0.001 data_path = "sd_data.npy" # 加载数据集 dataset = SDDataset(data_path) train_dataset, test_dataset = torch.utils.data.random_split(dataset, [8000, 2000]) train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True) # 初始化模型、损失函数和优化器 model = SDNet().to(device) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) # 训练和测试模型 for epoch in range(1, epochs + 1): train_loss = train(model, train_loader, criterion, optimizer, device) test_loss, accuracy = test(model, test_loader, criterion, device) print("Epoch {}: Train Loss: {:.4f}, Test Loss: {:.4f}, Accuracy: {:.2f}%".format(epoch, train_loss, test_loss, accuracy * 100)) if __name__ == '__main__': main() ``` 上述代码中,我们定义了一个 `SDDataset` 类来加载 SD 点云数据集,定义了一个 `SDNet` 类来实现 SD 点云的深度学习模型。我们使用 PyTorch 自带的 DataLoader 类来加载训练和测试数据集,并使用 Adam 优化器来训练模型。最后,我们使用 `train` 函数来训练模型,使用 `test` 函数来测试模型,并在主函数中执行训练和测试过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值