机器学习之逻辑回归

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

总结

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

相关推荐
MARS_AI_1 小时前
云蝠智能 Voice Agent 落地展会邀约场景:重构会展行业的智能交互范式
人工智能·自然语言处理·重构·交互·语音识别·信息与通信
weixin_422456441 小时前
第N7周:调用Gensim库训练Word2Vec模型
人工智能·机器学习·word2vec
HuggingFace5 小时前
Hugging Face 开源机器人 Reachy Mini 开启预定
人工智能
企企通采购云平台5 小时前
「天元宠物」×企企通,加速数智化升级,“链”接萌宠消费新蓝海
大数据·人工智能·宠物
超级小忍5 小时前
Spring AI ETL Pipeline使用指南
人工智能·spring
张较瘦_6 小时前
[论文阅读] 人工智能 | 读懂Meta-Fair:让LLM摆脱偏见的自动化测试新方法
论文阅读·人工智能
巴伦是只猫6 小时前
【机器学习笔记 Ⅲ】4 特征选择
人工智能·笔记·机器学习
好心的小明7 小时前
【王树森推荐系统】召回11:地理位置召回、作者召回、缓存召回
人工智能·缓存·推荐系统·推荐算法
lishaoan777 小时前
使用tensorflow的线性回归的例子(十二)
人工智能·tensorflow·线性回归·戴明回归
Danceful_YJ7 小时前
4.权重衰减(weight decay)
python·深度学习·机器学习