LogisticRegressionModel二分类概率问题

import torch
import torch.nn.functional as F
import matplotlib.pylab as plt
import torch.nn as nn
import numpy as np


#1.构建数据集 y=x+1
x=torch.tensor([[1.0],
                [2.0],
                [3.0]])
y=torch.tensor([[0.0],
                [0.0],
                [1.0]])

plt.plot(x,y)
plt.show()

#2.搭建神经网络
class LogisticRegressionModel(nn.Module):
    def __init__(self,num_input,num_output):
        super(LogisticRegressionModel,self).__init__() #这里遗忘
        self.predict=nn.Linear(num_input,num_output,bias=True)   #与线性回归一样

    def forward(self,x):
        y=torch.sigmoid(self.predict(x)) #用sigmoid 将线性变换后的值映射到0~1之间
        return y

net=LogisticRegressionModel(1,1)

#3.定义优化器和损失函数
optimizer=torch.optim.SGD(net.parameters(),lr=0.05)
loss_func=nn.BCELoss() #二分类交叉熵损失函数 算概率损失 MSE 线性损失 不取均值后学习率上升没×1/N

#4.训练模型
for epoch in range(1000):
    y_prediction=net(x)
    loss=loss_func(y_prediction,y)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()


x=np.linspace(0,10,200)# 0~10 分成200份
x_test=torch.FloatTensor(x).view((200,1))
y_test=net(x_test)
y=y_test.data.numpy()
plt.plot(x,y)
plt.xlabel('hours')
plt.ylabel('Probability of Pass')
plt.show()
Logistic Regression是一种广泛用于二分类问题的线性模型,它基于sigmoid函数将线性回归的结果转换到0到1之间,从而表示预测样本属于正类的概率。在处理乳腺癌数据集时,首先你需要准备数据,这通常包括特征量如肿瘤大小、形状等,以及目标标签,即癌症是否发生。 步骤如下: 1. **数据加载**:使用Python的sklearn库中的`load_breast_cancer()`函数从sklearn.datasets模块获取乳腺癌数据集。 ```python from sklearn.datasets import load_breast_cancer data = load_breast_cancer() X = data.data y = data.target ``` 2. **数据预处理**:标准化或归一化数值特征,如果需要的话,可以将类别量编码为数值形式。 3. **拆分数据集**:通常会将数据分为训练集和测试集,例如70%训练,30%测试。 ```python from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) ``` 4. **建立模型**:创建LogisticRegression实例,并设置必要的参数,比如惩罚项(penalty)、迭代次数(max_iter)等。 ```python from sklearn.linear_model import LogisticRegression model = LogisticRegression(penalty='l2', max_iter=1000) ``` 5. **拟合模型**:使用训练数据对模型进行训练。 ```python model.fit(X_train, y_train) ``` 6. **评估模型**:用测试集进行预测并计算准确率或其他评估指标。 ```python y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShuaS2020

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值