LogisticRegression逻辑回归

本文通过使用Python中的sklearn库实现逻辑回归算法,并在经典的Iris数据集上进行训练与测试。代码中详细展示了数据集的加载、划分、模型训练及预测的过程,并最终评估了模型的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# coding:utf-8
import sklearn.datasets
import sklearn.linear_model
import numpy.random
import matplotlib.pyplot

if __name__ == "__main__":
    # Load iris dataset
    iris = sklearn.datasets.load_iris()

    # Split the dataset with sampleRatio
    sampleRatio = 0.5
    n_samples = len(iris.target)
    sampleBoundary = int(n_samples * sampleRatio)

    # Shuffle the whole data
    shuffleIdx = range(n_samples)
    numpy.random.shuffle(shuffleIdx)

    # Make the training data
    train_features = iris.data[shuffleIdx[:sampleBoundary]]
    train_targets = iris.target[shuffleIdx[:sampleBoundary]]

    # Make the testing data
    test_features = iris.data[shuffleIdx[sampleBoundary:]]
    test_targets = iris.target[shuffleIdx[sampleBoundary:]]

    # Train
    logisticRegression = sklearn.linear_model.LogisticRegression()
    logisticRegression.fit(train_features, train_targets)

    # Predict
    predict_targets = logisticRegression.predict(test_features)

    # Evaluation
    n_test_samples = len(test_targets)
    X = range(n_test_samples)
    correctNum = 0
    for i in X:
        if(predict_targets[i] == test_targets[i]):
            correctNum += 1
    accuracy = correctNum * 1.0 / n_test_samples
    print("Logistic Regression (Iris) Accuracy: %.2f" %(accuracy))

    # Draw
    matplotlib.pyplot.subplot(2, 1, 1)
    matplotlib.pyplot.title("Logistic Regression (Iris)")
    matplotlib.pyplot.plot(X, predict_targets, 'ro-', label = 'Predict Labels')
    matplotlib.pyplot.ylabel("Predict Class")
    legend = matplotlib.pyplot.legend()

    matplotlib.pyplot.subplot(2, 1, 2)
    matplotlib.pyplot.plot(X, test_targets, 'g+-', label='True Labels')
    legend = matplotlib.pyplot.legend()

    matplotlib.pyplot.ylabel("True Class")
    matplotlib.pyplot.savefig("Logistic Regression (Iris).png", format='png')
    matplotlib.pyplot.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值