Pytoch机器学习乱玩(一):数学建模作业,体重与心率

动物心率与体重的模型

动物消耗的能量p主要用于维持体温,而体内热量通过其表面积S散失,记动物体重为w,则\(P \propto S \propto w^{\alpha}\)。又\(P\)正比于血流量\(Q\),而\(Q=wr\),其中\(q\)是动物每次心跳泵出的血流量,\(r\)为心率。假设\(q\)\(r\)成正比,于是\(P \propto wr\)。于是有\(r \propto w^{\alpha-1}=w^a\),有\(r=kw^a+b\)

import numpy as np
import matplotlib.pyplot as plt
import torch
import math
%matplotlib inline
r=np.array([[670],[420],[205],[120],[85],[70],[72],[38]])
w=np.array([[25],[200],[2000],[5000],[30000],[50000],[70000],[450000]])
plt.plot(w,r,'bo')
x_sample = np.arange(85, 450000, 0.1)
bottom_range = [1,2,3,4,5]
color = ['red','green','pink','black','blue']
for i in range(5):
    y_sample = 5000*x_sample**(-1/bottom_range[i])
    plt.plot(x_sample, y_sample, color[i],label='real curve')

1530134-20190318102107379-1299980064.png

由上图的预模拟,考虑\(r\)的指数为\(-1\),\(-\frac{1}{2}\),\(-\frac{1}{3}\),\(-\frac{1}{4}\),\(-\frac{1}{5}\),从中选取误差最小的

from torch.autograd import Variable
from torch import nn
from torch import optim
import math

#生成目标函数 构建数据集
x_train = w
x_train = torch.from_numpy(x_train).float()
x_train = Variable(x_train)

y_train = torch.from_numpy(r).float()
y_train = Variable(y_train)

#构建模型
class poly_model(nn.Module):
    def __init__(self,bottom):
        super(poly_model,self).__init__()
        self.k = nn.Parameter(torch.randn(1))
        self.b = nn.Parameter(torch.zeros(1))
        self.bottom = bottom
    
    def forward(self,x):
        out = (x)**(-1/self.bottom)*self.k+self.b
        return out
for i in range(5):
    print("exponential is -1/%d"%(bottom_range[i]))
    model = poly_model(bottom_range[i])
    criterion = nn.MSELoss()
    optimizer = optim.SGD(model.parameters(),lr=1e-3)

    # 更新参数
    for j in range(150000):
        output = model(x_train)
        loss = criterion(output,y_train)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        if(j%50000 == 0):
            print(loss.item())
        if(loss.item() < 1e-3): break

    print(model.parameters())
    y_pred = model(x_train)

    plt.plot(x_train.data.numpy()[:, 0], y_pred.data.numpy(), label='fitting curve', color=color[i])
    plt.plot(w, r, label='real curve', color='orange')

经过150000轮预训练,我们得到如下图,表中为曲线颜色对应的指数

指数颜色误差
-1/141184
-1/2绿10599
-1/31195
-1/4360
-1/5468

其中误差最小的项为\(-\frac{1}{4}\)

1530134-20190318102124472-425876335.png

这里可以做一些交叉熵验证找一个最佳的learning rate代码就不贴了 随机生成学习率即可,经过100次验证 我得到的最佳学习率是0.20485,收敛的很快

model = poly_model(4)
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(),lr=0.20485)
for j in range(50001):
    output = model(x_train)
    loss = criterion(output,y_train)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    if(j%50000 == 0):
        print(loss.item())
y_pred = model(x_train)
plt.plot(x_train.data.numpy()[:, 0], y_pred.data.numpy(), label='fitting curve', color=color[i])
plt.plot(w, r, label='real curve', color='orange')

1530134-20190318102128919-950337399.png

打印模型参数

param = list(model.parameters())
print(param)
[Parameter containing:
tensor([1591.8446], requires_grad=True), Parameter containing:
tensor([-33.6434], requires_grad=True)]

通过交叉验证,使用0.20485的学习率学习50000轮后,最终模型为\(r=1591.84w^{-\frac{1}{4}}-33.64​\),均方误差为304.288

动物实际心率预测心率偏差
田鼠670680+10
家鼠420390-30
205204-1
小狗120155+35
大狗8587+2
7072+2
7263-9
3827-11

1530134-20190318102132880-830141626.png

转载于:https://www.cnblogs.com/ChetTlittilebread/p/10550686.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值