<jupyter_start><jupyter_text>构建线性回归模型<jupyter_code>class LinerRegressionModel(nn.Module):
    def __init__(self, input_dim, output_dim):
        super().__init__()
        self.liner = nn.Linear(input_dim, output_dim)

    def forward(self, x):
        out = self.liner(x)
        return out<jupyter_output><empty_output><jupyter_text>指定输入输出的维度<jupyter_code>input_dim = 1
output_dim = 1
model = LinerRegressionModel(input_dim, output_dim)

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model.to(device)<jupyter_output><empty_output><jupyter_text>指定参数和损失函数<jupyter_code>epochs = 1000
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
criterion = nn.MSELoss()<jupyter_output><empty_output><jupyter_text>开始训练模型<jupyter_code>for epoch in range(epochs):
    epoch += 1
    
    inputs = torch.from_numpy(x_train).to(device)
    labels = torch.from_numpy(y_train).to(device)

    optimizer.zero_grad()

    outputs = model(inputs)

    loss = criterion(outputs, labels)

    loss.backward()

    optimizer.step()

    if epoch % 100 == 0:
        print("%s : %s " %(epoch, loss.item()))<jupyter_output>100 : 0.0009868270717561245 
200 : 0.00032102401019074023 
300 : 0.0001044380696839653 
400 : 3.3970434742514044e-05 
500 : 1.1052052286686376e-05 
600 : 3.5954492432210827e-06 
700 : 1.1699041806423338e-06 
800 : 3.804425148246082e-07 
900 : 1.2378869485019095e-07 
1000 : 4.0194695571926786e-08<jupyter_text>输出模型预测的结果
（这里虽然输出了预测的结果，但是没有直接给出y=ax+b这样的表达式？）<jupyter_code>predicted = model(torch.from_numpy(x_train).requires_grad_()).data.numpy()
predicted<jupyter_output><empty_output><jupyter_text>模型的保存与读取<jupyter_code>torch.save(model.state_dict(), 'model.pkl')
model.load_state_dict(torch.load('model.pkl'))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.127114020731042, 'fraction_numerical': 0.1303873431533006, 'mean_word_length': 4.993464052287582, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 24, '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': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '359306', 'license': 'MIT', 'n_tokens_mistral': 945, 'n_tokens_neox': 801, 'n_words': 87, 'path': 'linear_regression.ipynb', 'repo_name': 'yexia553/pytorch_learning', 'size': '1833'}