pytorch 曲线拟合

#!/usr/bin/env python
# coding: utf-8

# In[1]:


import numpy as np
import torch
import matplotlib.pyplot as plt
from torch.autograd import Variable as var


# In[2]:


def get_data(x,w,b,d):
    c,r = x.shape
    y = (w * x * x + b*x + d)+ (0.1*(5*np.random.rand(c,r)-1))
    return(y)


# In[3]:


xs = np.arange(0,5,0.01).reshape(-1,1)
ys = get_data(xs,1,-2,3)

xs = var(torch.Tensor(xs))
ys = var(torch.Tensor(ys))


# In[4]:


class Fit_model(torch.nn.Module):
    def __init__(self):
        super(Fit_model,self).__init__()
        self.linear1 = torch.nn.Linear(1,32)
        self.relu = torch.nn.ReLU()
        self.linear2 = torch.nn.Linear(32,32)
        self.linear3 = torch.nn.Linear(32,1)
        #torch.nn.

        self.criterion = torch.nn.MSELoss()
        self.opt = torch.optim.SGD(self.parameters(),lr=0.01)
        
    def forward(self, input):
        y = self.linear1(input)
        y = self.relu(y)
        y = self.linear2(y)
        y = self.relu(y)
        y = self.linear3(y)
        return y


# In[5]:


model = Fit_model()


# In[6]:


for e in range(40001):
    y_pre = model(xs)

    loss = model.criterion(y_pre,ys)
    if(e%200==0):
        print(e,loss.data)
    
    # Zero gradients
    model.opt.zero_grad()
    # perform backward pass
    loss.backward()
    # update weights
    model.opt.step()


# In[7]:


ys_pre = model(xs)


# In[8]:


plt.title("curve")
plt.plot(xs.data.numpy(),ys.data.numpy())
plt.plot(xs.data.numpy(),ys_pre.data.numpy())
plt.legend("ys","ys_pre")
plt.show()


# In[9]:


a = 1.5


# In[14]:


ys_preq = model(torch.Tensor([a]))


# In[21]:


print(ys_preq.item())
print(np.array(ys_preq.item()))
print(ys_preq.detach().numpy())


# In[ ]:



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值