Logistic regression intuition and conditional probabilities


logit函数输入参与p属于(0,1),函数值为整个实数域,可以在特征值与逻辑比率之间建立线性关系



这里



样本x属于分类1的条件概率
现在如何去预测一个特定样本属于一个特定类的概率,转化一个函数形式,



注意这里是y=1的概率,后面算似然函数特别注意这点,这里y|x只有两个分类,y=1|x,y=0|x,P(y=0|x)=1-P(y=1|x),注意下面的处理手法,

似然函数

将问题转化一下,求lnL最大值,也就是求-lnL最小值,易知-lnL>0


为了更好掌握损失函数J(w),看一下单个样本的例子



y=1或者y=0


import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.001, 0.999, 100)
plt.plot(x, -np.log(x),'b', label='y=1')
plt.plot(x, -np.log(1-x), 'r--', label='y=0')
plt.ylim(0, 5)
plt.xlim(0, 1)
plt.xlabel('$\phi(x)$')
plt.ylabel('$J(w)$')
plt.legend()
plt.show()

可以发现如果预测错误,损失函数将变的无穷大

使用sc-learn训练logistic regression 模型

from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.cross_validation import train_test_split
import numpy as np
import matplotlib
from sklearn import datasets
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from matplotlib.colors import ListedColormap
iris = datasets.load_iris()
# print iris
X = iris.data[:, [2, 3]]
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
# 测试集做同样的标准化,就是对测试集做相同的平移伸缩操作
X_test_std = sc.transform(X_test)
'''sc.scale_标准差, sc.mean_平均值, sc.var_方差'''

lr = LogisticRegression(C=1000.0, random_state=0)
lr.fit(X_train_std, y_train)

# 预测
y_pred = lr.predict(X_test_std)

print('Misclassified samples: %d' % (y_test != y_pred).sum())
print('Accuracy: %.2f' % accuracy_score(y_test, y_pred))

x1_min, x1_max = X_train_std[:, 0].min() - 1, X_train_std[:, 0].max() + 1
x2_min, x2_max = X_train_std[:, 1].min() - 1, X_train_std[:, 1].max() + 1

resolution = 0.01
# xx1 X轴,每一个横都是x的分布,所以每一列元素一样,xx2 y轴 每一列y分布,所以每一横元素一样
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),np.arange(x2_min, x2_max, resolution))

# .ravel() 函数是将多维数组降位一维,注意是原数组的视图,转置之后成为两列元素
z = lr.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
'''
contourf画登高线函数要求 *X* and *Y* must both be 2-D with the same shape as *Z*, or they
    must both be 1-D such that ``len(X)`` is the number of columns in
    *Z* and ``len(Y)`` is the number of rows in *Z*.
'''
# z形状要做调整
z = z.reshape(xx1.shape)

# 填充等高线的颜色, 8是等高线分为几部分
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])

for i, value in enumerate(np.unique(y)):
    temp = X_train_std[np.where(y_train==value)]
    plt.scatter(x=temp[:,0],y=temp[:,1], marker=markers[value],s=69, c=colors[value], label=value)

plt.scatter(x=X_test_std[:, 0],y=X_test_std[:,1], marker= 'o',s=69, c='none', edgecolors='r', label='test test')

plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.contourf(xx1, xx2, z, len(np.unique(y)), alpha = 0.4, cmap = cmap)
plt.legend(loc='upper left')
plt.show()

对个样本的损失函数求导


使用正则化(regularization)处理过拟合(overftting )

在机器学习中,过拟合是一个普遍问题,模型对于训练数据有很好表现,但对于测试数据的表现却很差。如果一个模型出现过拟合,也可以说模型具有高方差,包含太多参数,这对于潜在数据太过复杂;再就是低度拟合(underftting),对训练数据和测试数据都不能很好的刻画


一种方法就是通过正则化达到偏差-方差权衡( bias-variance tradeoff),调整模型的复杂度。正则化是一种非常有用的方法,例如处理共线性、过滤噪音、防止过拟合。
最普遍的正则化就是所谓的L2regularization



为了应用正则化,需要在损失函数加上正则化项!


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

xmajorLocator = MultipleLocator(2)
xminorLocator = MultipleLocator(1)
ymajorLocator = MultipleLocator(0.5)

N = 7
x = np.linspace(-N, N, 100)
z = 1/(1+np.e**(-x))
fig = plt.figure(1)
axes = plt.subplot(111)

plt.ylim(-0.1, 1.1)
plt.axvline(0.0, color='k')
plt.axhline(0, ls='dotted',color='r')
plt.axhline(0.5, ls='dotted',color='r')
plt.axhline(1, ls='dotted',color='r')
#plt.axhspan(0.0,1.0, facecolor='1.0', alpha=1.0, ls='dotted')
axes.xaxis.set_major_locator(xmajorLocator)
axes.xaxis.set_minor_locator(xminorLocator)
axes.yaxis.set_major_locator(ymajorLocator)
plt.xlabel("z")
plt.ylabel("$\phi (z)$")
plt.plot(x, z)
plt.show()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容