Pytorch学习笔记实例1——二分类

二分类

使用

  • 损失函数: BCEloss
  • 输出层激活方式: sigmoid
#!/usr/bin/env python
# coding: utf-8

# In[1]:


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch


# In[34]:


# 读数据


# In[2]:


data = pd.read_csv('./dataset/credit-a.csv',header=None)


# In[3]:


data


# In[35]:


# 选取数据并把数据转换为张量


# In[4]:


X = data.iloc[:,:-1]


# In[5]:


X= torch.from_numpy(X.values).type(torch.FloatTensor)


# In[6]:


type(X)


# In[7]:


X.shape


# In[8]:


Y = data.iloc[:,-1].replace(-1,0)


# In[9]:


Y = torch.from_numpy(Y.values.reshape(-1,1)).type(torch.FloatTensor)


# In[10]:


Y.size()


# In[13]:


type(Y)


# In[36]:


# 创建模型


# In[14]:


from torch import nn


# In[16]:


model = nn.Sequential(
            nn.Linear(15,1),
            nn.Sigmoid()
)


# In[17]:


model


# In[18]:


loss_fn = nn.BCELoss()


# In[19]:


opt = torch.optim.Adam(model.parameters(), lr=0.0001)


# In[37]:


#用batch来使数据批量选取


# In[23]:


batch = 16
batch_no = 653//16


# In[33]:


for i in range(10000):
    for i in range(batch_no):
        start = i*batch
        end = start + batch
        x = X[start: end]
        y = Y[start: end]
        y_per = model(x)
        loss = loss_fn(y_per, y)
        opt.zero_grad()
        loss.backward()
        opt.step()


# In[38]:


# 计算正确率


# In[32]:


((model(X).data.numpy()>0.5).astype('int') == Y.numpy()).mean()


# In[ ]:





你可能感兴趣的:(深度学习,pytorch,分类,深度学习)