机器学习之逻辑回归

机器学习中线性回归可以用来做预测,经典的例子就是房价预测。逻辑回归主要解决的问题是二分类问题,通过 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

总结

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

相关推荐
机器之心1 小时前
李飞飞最新长文:AI的下一个十年——构建真正具备空间智能的机器
人工智能·openai
机器之心1 小时前
豆包编程模型来了,我们用四个关卡考了考它!
人工智能·openai
阿里云大数据AI技术1 小时前
让 ETL 更懂语义:DataWorks 支持数据集成 AI 辅助处理能力
人工智能·阿里云·dataworks·ai辅助
hoiii1871 小时前
基于交替方向乘子法(ADMM)的RPCA MATLAB实现
人工智能·算法·matlab
Elastic 中国社区官方博客2 小时前
Elasticsearch:如何为 Elastic Stack 部署 E5 模型 - 下载及隔离环境
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
xier_ran2 小时前
深度学习:神经网络中的参数和超参数
人工智能·深度学习
8Qi82 小时前
伪装图像生成之——GAN与Diffusion
人工智能·深度学习·神经网络·生成对抗网络·图像生成·伪装图像生成
阿里云大数据AI技术3 小时前
PAI Physical AI Notebook详解2:基于Cosmos世界模型的操作动作数据扩增与模仿学习
人工智能
傻啦嘿哟3 小时前
Python高效实现Word转HTML:从基础到进阶的全流程方案
人工智能·python·tensorflow
该用户已不存在3 小时前
Gemini CLI 核心命令指南,让工作从从容容游刃有余
人工智能·程序员·aigc