pytorch计算模型准确率过程

# Lab 5 Logistic Regression Classifier
import torch
from torch.autograd import Variable
import numpy as np
from sklearn.preprocessing import MinMaxScaler

torch.manual_seed(777)  # for reproducibility

xy = np.loadtxt('./data-03-diabetes.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, -1:]
x_data=MinMaxScaler().fit_transform(x_data)
# Make sure the shape and data are OK
print(x_data.shape, y_data.shape)
# 数据预处理 浮点型tensor并且需要进行梯度运算(Variable)
X = Variable(torch.Tensor(x_data).float())
Y = Variable(torch.Tensor(y_data).float())


# 声明功能层 两层全连接 一个二分类sigmoid激活层
linear1 = torch.nn.Linear(in_features=8, out_features=6, bias=True)
linear = torch.nn.Linear(in_features=6, out_features=1, bias=True)
sigmoid = torch.nn.Sigmoid()
# Sequential构建模型
model = torch.nn.Sequential(linear1,linear,sigmoid)
# 二分类交叉熵损失函数
loss_cost=torch.nn.BCELoss()
# 随机梯度下降优化器 (可换其他)
optimizer = torch.optim.SGD(model.parameters(), lr=0.05)

for step in range(10001):
    optimizer.zero_grad() # 梯度置零
    hypothesis = model(X) # x代入model中计算预测值
    cost=loss_cost(hypothesis,Y) # 损失计算
    cost.backward() # 梯度反向传播计算
    optimizer.step() # 参数权重更新
    # 每迭代200次输出当前损失值
    if step % 200 == 0:
        print(step, cost.data.numpy())

# 0.89>0.5 -> 1  0.14<=0.5 -> 0
# 将预测值的概率归为 0 或 1 类别
predicted = (model(X).data > 0.5).float()
# 与标签计算模型预测的准确率
accuracy = (predicted == Y.data).float().mean()
print("\nHypothesis: ", hypothesis.data.numpy(), "\nCorrect (Y): ", predicted.numpy(), "\nAccuracy: ", accuracy)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值