机器学习2-简单的二分类问题

需求:

假设现在需要对数据进行二分类,小于0.5的,打上0的标记,大于0.5的,打上1的标记,怎么做

分析:

这是一个简单的二分类问题,使用逻辑回归模型。

代码:

# 导入所需的库,如需安装:pip install scikit-learn matplotlib
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix

# 创建一个随机的二分类数据集
np.random.seed(42)
X = np.random.rand(100, 1)
print("X:\n", X)
y = (X > 0.5).astype(int)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print("X_train:\n", X_train)

# 创建并训练逻辑回归模型
model = LogisticRegression()
model.fit(X_train, y_train)

# 预测测试集
y_pred = model.predict(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')

# 可视化决策边界
plt.scatter(X, y, color='blue', marker='o', label='Class 0')
plt.scatter(X_test, y_test, color='red', marker='x', label='Test Data')
plt.xlabel('Feature')
plt.ylabel('Class')
plt.legend()
plt.title('Logistic Regression Decision Boundary')
plt.axhline(0.5, color='green', linestyle='--', linewidth=2, label='Decision Boundary')
plt.show()

运行结果:

如图可见Test Data的标记都是正确的

执行下来的准确率

Accuracy: 1.0

结论:模型预测使用测试集 (X_test) 进行预测,得到预测值 y_pred,都满足预期

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

dracularking

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

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

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

打赏作者

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

抵扣说明:

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

余额充值