机器学习中逻辑回归的Python实现——解决分类中的线性可分以及线性不可分问题

线性可分

import numpy as np
import matplotlib.pyplot as plt

# 读入训练数据
train = np.loadtxt('images2.csv', delimiter=',', skiprows=1)
train_x = train[:, 0:2]
train_y = train[:, 2]

# 参数的初始化
theta = np.random.rand(3)

# 标准化
# axis=0表示输出矩阵是1行,也就是求每一列的平均值。
# axis=1表示输出矩阵是1列, 也就是求每一行的平均值
mu = train_x.mean(axis=0)
sigma = train_x.std(axis=0)


def standardize(x):
    return (x - mu) / sigma


train_z = standardize(train_x)

# 构建训练数据矩阵
X = np.hstack((np.ones((train_z.shape[0], 1)), train_z))


# sigmoid函数
def f(X):
    return (1 / (1 + np.exp(-np.dot(X, theta))))

# 分类函数
def classify(x):
    return (f(x) >= 0.5).astype(np.int)

# 重复次数
epoch = 5000

# 学习率
ETA = 1e-3

# 更新次数
count = 1

# 重复学习
for _ in range(epoch):
    theta = theta - ETA * np.dot((f(X) - train_y), X)
    print('第{}次,theta={}'.format(count, theta))
    count += 1

# 绘图
x0 = np.linspace(-2, 2, 100)
plt.plot(train_z[train_y == 1, 0], train_z[train_y == 1, 1], 'o')
plt.plot(train_z[train_y == 0, 0], train_z[train_y == 0, 1], 'x')
plt.plot(x0, -(theta[0] + theta[1] * x0) / theta[2], linestyle='dashed')
plt.axis('scaled')
plt.show()

线性不可分

import numpy as np
import matplotlib.pyplot as plt

# 读入训练数据
train = np.loadtxt('data3.csv', delimiter=',', skiprows=1)
train_x = train[:, 0:2]
train_y = train[:, 2]

# 标准化
mu = train_x.mean(axis=0)
sigma = train_x.std(axis=0)


def standardize(x):
    return (x - mu) / sigma


train_z = standardize(train_x)


# 构建训练数据矩阵
def to_matrix(x):
    # np.newaxis 的功能是增加新的维度,但是要注意 np.newaxis 放的位置不同,产生的矩阵形状也不同。
    # x[:, np.newaxis] ,放在后面,会给列上增加维度
    # x[np.newaxis, :] ,放在前面,会给行上增加维度
    return np.hstack([np.ones([x.shape[0], 1]), x, x[:, 0, np.newaxis] ** 2])


X = to_matrix(train_z)

# 初始化参数
theta = np.random.rand(4)


# sigmoid函数
def f(X):
    return 1 / (1 + np.exp(-np.dot(X, theta)))


# 分类函数
def classify(X):
    return (f(X) >= 0.5).astype(np.int)


# 重复次数
epoch = 5000

# 学习率
ETA = 1e-3

# 更新次数
count = 1

# 精度的历史记录
accuracies = []

# 重复次数
for _ in range(epoch):
    theta = theta - ETA * np.dot(f(X) - train_y, X)
    # 计算现在的精度
    result = classify(X) == train_y
    accuracy = len(result[result == True]) / len(result)
    accuracies.append(accuracy)
    print('第{}次更新,theta={}'.format(count, theta))
    count += 1

# 绘图
x1 = np.linspace(-2, 2, 100)
plt.plot(train_z[train_y == 1, 0], train_z[train_y == 1, 1], 'o')
plt.plot(train_z[train_y == 0, 0], train_z[train_y == 0, 1], 'x')
plt.plot(x1, -(theta[3] * (x1 ** 2) + theta[1] * x1 + theta[0]) / theta[2], linestyle='dashed')
plt.axis('scaled')
plt.show()

# 绘制精度图
x = np.arange(len(accuracies))
plt.plot(x,accuracies)
plt.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python线性分类是一种常用的机器学习分类算法。线性分类器通过使用线性函数将样本为不同的类别。在多类别情况下,可以使用"one-vs-rest"方法来训练多个二分类模型,每个模型与一个类别相关联,并尽量将这个类别与其他类别开。在测试时,通过运行所有二分类器来预测样本所属的类别,并选择数最高的分类器的类别标签作为预测结果。 Python线性分类算法包括Logistic回归分类器(LogisticRegression)和线性支持向量机分类器(LinearSVC)。这些算法可以用于线性可分的样本分类,即可以使用一个线性函数将不同类别的样本开。 在使用Python进行线性分类时,可以使用sklearn库的相应模块来实现。例如,可以使用LinearSVC()来训练线性支持向量机分类器,并使用LogisticRegression()来训练Logistic回归分类器。然后可以使用这些模型来绘制样本布和分类界限。 下面是一个使用LinearSVC和LogisticRegression进行线性分类的示例代码: ``` from sklearn.datasets import make_blobs from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression import mglearn import matplotlib.pyplot as plt # 生成用于分类的样本数据集 X, y = make_blobs() # 使用LinearSVC训练线性支持向量机分类器 svm_model = LinearSVC().fit(X, y) # 使用LogisticRegression训练Logistic回归分类器 logistic_model = LogisticRegression().fit(X, y) # 绘制样本布和分类界限 mglearn.discrete_scatter(X[:, 0], X[:, 1], y) mglearn.plots.plot_2d_separator(svm_model, X, fill=False, alpha=0.7) mglearn.plots.plot_2d_separator(logistic_model, X, fill=False, alpha=0.7) plt.xlabel("Feature 0") plt.ylabel("Feature 1") plt.legend(["Class 0", "Class 1", "SVM boundary", "Logistic boundary"]) plt.show() ``` 上述代码,使用make_blobs函数生成了一个用于分类的样本数据集。然后别使用LinearSVC和LogisticRegression进行训练,并使用mglearn库的函数绘制样本布和分类界限。可以通过调整参数和使用其他数据集来尝试不同的线性分类任务。 总结来说,Python线性分类是一种常用的机器学习分类算法,可以使用LinearSVC和LogisticRegression等模块来实现。通过训练模型并对样本进行预测,可以实现线性可分样本的分类。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [python机器学习(4)线性模型:分类](https://blog.csdn.net/weixin_52662649/article/details/117126553)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [CNN的Python实现——第二章:线性分类器](https://blog.csdn.net/qq_38293297/article/details/107160798)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

秃头鸭鸭鸭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值