机器学习之逻辑回归

机器学习中线性回归可以用来做预测,经典的例子就是房价预测。逻辑回归主要解决的问题是二分类问题,通过 Sigmoid 函数,输出的结果是一个概率(0,1),逻辑回归的损失函数通过交叉熵来实现。本文将通过 Sklearn 实现逻辑回归。

  • Sigmoid 函数
  • 交叉熵损失函数

准备数据集

复制代码
# 导入matplotlib绘图库
import matplotlib.pyplot as plt
# 导入生成分类数据函数
# from sklearn.datasets.samples_generator import make_classification
from sklearn.datasets import make_classification
# 生成100*2的模拟二分类数据集
X, labels = make_classification(
    n_samples=100,
    n_features=2,
    n_redundant=0,
    n_informative=2,
    random_state=1,
    n_clusters_per_class=2)

print (X[:5])
print (labels[:5])

# 设置随机数种子
rng = np.random.RandomState(2)
# 对生成的特征数据添加一组均匀分布噪声
X += 2 * rng.uniform(size=X.shape)
# 标签类别数
unique_lables = set(labels)
# 根据标签类别数设置颜色
colors = plt.cm.Spectral(np.linspace(0,1,len(unique_lables)))
# 绘制模拟数据的散点图
for k,col in zip(unique_lables, colors):
    x_k=X[labels==k]
    plt.plot(x_k[:,0],x_k[:,1],'o',markerfacecolor=col,markeredgecolor="k",
             markersize=14)
plt.title('Simulated binary data set')
plt.show();

切分训练集、测试集,1:9 进行切分。

复制代码
# 训练集与测试集的简单划分
offset = int(X.shape[0] * 0.9)
X_train, y_train = X[:offset], labels[:offset]
X_test, y_test = X[offset:], labels[offset:]
y_train = y_train.reshape((-1,1))
y_test = y_test.reshape((-1,1))

print('X_train=', X_train.shape)
print('X_test=', X_test.shape)
print('y_train=', y_train.shape)
print('y_test=', y_test.shape)

训练并测试

复制代码
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(random_state=0).fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_pred

总结

线性回归和逻辑回归是机器学习中两种回归算法,从字面上看会被搞混。线性回归输出为一个实数,均方差作为损失函数,逻辑回归是分类算法,输出为概率,交叉熵作为损失函数。

相关推荐
许泽宇的技术分享38 分钟前
「让AI大脑直连Windows桌面」:深度解析Windows-MCP,开启操作系统下一代智能交互
人工智能·windows·交互
Baihai_IDP1 小时前
许多 AI 智能体评测基准并不可靠
人工智能·面试·llm
钢铁男儿1 小时前
PyTorch基础(使用Tensor及Antograd实现机器学习)
人工智能·pytorch·机器学习
Hcoco_me1 小时前
【8】Transformers快速入门:Decoder 分支和统计语言模型区别?
人工智能·语言模型·自然语言处理
_oP_i1 小时前
Model Context Protocol (MCP)标准化应用程序向大型语言模型 (LLM) 提供上下文协议
人工智能·语言模型·自然语言处理
平行绳1 小时前
智能体一键生成火遍全网的火柴人视频,工作流详细搭建教程来了
人工智能·coze
chenchihwen2 小时前
腾讯codebuddy.ai 安装实测【从零开始开发在线五子棋游戏:完整开发记录】
人工智能·codebuddy
楚韵天工2 小时前
基于机器学习的生活垃圾分类识别系统
python·神经网络·机器学习·计算机视觉·分类·生活
巫婆理发2222 小时前
正向传播与反向传播(神经网络思维的逻辑回归)
人工智能·神经网络·逻辑回归
逻极3 小时前
Dify 从入门到精通(第 30/100 篇):Dify 的分布式部署
人工智能·ai·agent·ai编程·工作流·dify·ai助手