pytroch笔记

pytroch基础应用

1.环境:

Python3.x
pytorch1.4.0
matplotlib3.3.2
sklearn0.23.2

2.代码功能:练习一般神经网络的主要步骤:数据准备,初始化权重,激活函数,向前计算,损失函数,计算损失,反向计算,更新参数

import torch
import matplotlib.pyplot as plt
import torch.nn.functional as F
from sklearn.datasets import load_iris
from torch.autograd import Variable
from torch.optim import SGD

class Net(torch.nn.Module): #torch.nn.modules
    #初始化函数
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden) 
        self.predict = torch.nn.Linear(n_hidden, n_output) 
    #向前传播
    def forward(self, x):
        x= F.sigmoid(self.hidden(x))
        x= self.predict(x)
        out = F.log_softmax(x, dim =1)
        return out
use_cuda = torch.cuda.is_available()
print("use_cuda:",use_cuda)

#加载数据集
iris = load_iris()
print(iris.keys())

x = iris['data'] #特征信息
y = iris['target'] #目标分类
print(x.shape)
print(y.shape)
x = torch.FloatTensor(x)
y = torch.LongTensor(y)
x,y = Variable(x),Variable(y)
net = Net(n_feature=4 , n_hidden = 5, n_output = 4)
print(net)
optimizer =SGD(net.parameters(),lr=0.5)
px,py =[],[] 
for i in range(10000):
    prediction = net(x) #数据集传入网络向前计算
    #计算loss
    loss = F.nll_loss(prediction,y)
    #清除网络状态
    optimizer.zero_grad()
    #loss反向传播
    loss.backward()
    
    # 更新参数
    optimizer.step()
    #在训练过程中 打印每次迭代的损失情况:
#     print( 'loss: ', loss.data[0]) 
    train_loss =loss.item()
    print(i, " loss: ", train_loss)
    px.append(i)
    py.append(train_loss)
    if i % 100 == 0 and i>0:
        #打印结果
        plt.cla()
        plt.plot(px,py,'r-',lw=1)
        plt.text(0,0, 'Loss=%.4f' % train_loss,fontdict={'size': 20,'color':'red'})
        plt.pause(0.1)

结果:运行结果
在这里插入图片描述
My first article

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值