<jupyter_start><jupyter_text>介绍了如何利用pytorch快速建立一个贯序模型，并介绍了进行模型保存的基本操作<jupyter_code>import torch
import torch.nn.functional as F<jupyter_output><empty_output><jupyter_text>1. 通过继承Module类搭建的模型<jupyter_code>class Net(torch.nn.Module):
    def __init__(self, n_features, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_features, n_hidden)
        self.output = torch.nn.Linear(n_hidden, n_output)
    
    def forward(self, x):
        x = F.relu(self.hidden(x))
        x = self.output(x)
        return x
net1 = Net(1, 10, 1)
print(net1)<jupyter_output>Net(
  (hidden): Linear(in_features=1, out_features=10, bias=True)
  (output): Linear(in_features=10, out_features=1, bias=True)
)<jupyter_text>2. 贯序模型<jupyter_code>net2 = torch.nn.Sequential(
    torch.nn.Linear(1, 10),
    torch.nn.ReLU(),     # 注意与方法一中relu的区别
    torch.nn.Linear(10, 1)
)
print(net2)<jupyter_output>Sequential(
  (0): Linear(in_features=1, out_features=10, bias=True)
  (1): ReLU()
  (2): Linear(in_features=10, out_features=1, bias=True)
)<jupyter_text>3. 模型的保存和读取<jupyter_code>torch.save(net1, 'net.pkl')
net3 = torch.load('net.pkl')
print(net3)
# 如果只保存网络中的参数
torch.save(net1.state_dict(), 'net_params.pkl')
net4 = torch.load('net_params.pkl')
print(net4)   # 可见模型中其实有初始的随机权重<jupyter_output>OrderedDict([('hidden.weight', tensor([[-0.9739],
        [-0.0022],
        [-0.8892],
        [-0.1679],
        [ 0.7306],
        [ 0.6551],
        [ 0.4333],
        [-0.5697],
        [-0.2109],
        [-0.8125]])), ('hidden.bias', tensor([ 0.3926, -0.1574, -0.8166,  0.5441, -0.9124,  0.3682,  0.0662, -0.0973,
         0.0944, -0.4801])), ('output.weight', tensor([[-0.0877,  0.2857,  0.2743,  0.2837,  0.1657,  0.0533,  0.3034,  0.1524,
          0.2158, -0.1180]])), ('output.bias', tensor([0.2479]))])
{'fraction_non_alphanumeric': 0.18500273672687464, 'fraction_numerical': 0.1056376573617953, 'mean_word_length': 3.581453634085213, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '69395', 'license': 'MIT', 'n_tokens_mistral': 933, 'n_tokens_neox': 867, 'n_words': 111, 'path': 'Pytorch_demos/basic_tutorail/2.2 basic_sequential_model.ipynb', 'repo_name': 'guofei1989/DL_Wiglet', 'size': '1827'}