- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个函数,g1(x,y)
和 g2(x,y)
返回一个 float
例如,g1(1,2)
--> 返回 0.345g2(1,2)
--> 返回 0.453
现在,为了绘制决策边界,我想满足:
g2(x,y) == g1(x,y)
,
或者重新排列为:g1(x,y) - g2(x,y) == 0
如果我生成一系列 x
值 1,2,3,4,5
,我如何找到产生 g1( x,y) - g2(x,y) == 0
?
我真的不知道该怎么做,如果有任何想法,我将不胜感激。你认为 scipy.optimize.minimize
是个好方法吗?如果是这样,我究竟该怎么做(我尝试过语法但失败了)。
感谢您的帮助!
编辑:
你问的是 g1() 和 g2() 的方程式,它们在这里:)
$\Rightarrow g_1(\pmb{x}) =\pmb{x}^{\,t} -\frac{1}{2}\Sigma_1^{-1}\pmb{x} +\bigg (\Sigma_1^{-1}\pmb{\mu}{\,1}\bigg)^t +\bigg( -\frac{1}{2}\pmb{\mu} {\,1}^{\,t}\Sigma_{1}^{-1}\pmb{\mu}_{\,1} -\frac{1}{2} ln(|\Sigma_1|)\比格)\\quad g_2(\pmb{x}) =\pmb{x}^{\,t} -\frac{1}{2}\Sigma_2^{-1}\pmb{x} +\bigg(\Sigma_2^ {-1}\pmb{\mu}{\,2}\bigg)^t +\bigg( -\frac{1}{2}\pmb{\mu}{\,2 }^{\,t}\Sigma_{2}^{-1}\pmb{\mu}_{\,2} -\frac{1}{2} ln(|\Sigma_2|)\bigg) $
(嗯,不知何故 Latex 无法正常工作,我将其作为图片上传):
这就是我实现它们的方式:
def discriminant_function(x_vec, cov_mat, mu_vec):
"""
Calculates the value of the discriminant function for a dx1 dimensional
sample given covariance matrix and mean vector.
Keyword arguments:
x_vec: A dx1 dimensional numpy array representing the sample.
cov_mat: numpy array of the covariance matrix.
mu_vec: dx1 dimensional numpy array of the sample mean.
Returns a float value as result of the discriminant function.
"""
W_i = (-1/2) * np.linalg.inv(cov_mat)
assert(W_i.shape[0] > 1 and W_i.shape[1] > 1), 'W_i must be a matrix'
w_i = np.linalg.inv(cov_mat).dot(mu_vec)
assert(w_i.shape[0] > 1 and w_i.shape[1] == 1), 'w_i must be a column vector'
omega_i_p1 = (((-1/2) * (mu_vec).T).dot(np.linalg.inv(cov_mat))).dot(mu_vec)
omega_i_p2 = (-1/2) * np.log(np.linalg.det(cov_mat))
omega_i = omega_i_p1 - omega_i_p2
assert(omega_i.shape == (1, 1)), 'omega_i must be a scalar'
g = ((x_vec.T).dot(W_i)).dot(x_vec) + (w_i.T).dot(x_vec) + omega_i
return float(g)
为了对我写的数据进行分类:
导入操作符
def classify_data(x_vec, g, mu_vecs, cov_mats):
"""
Classifies an input sample into 1 out of x classes determined by
maximizing the discriminant function g_i().
Keyword arguments:
x_vec: A dx1 dimensional numpy array representing the sample.
g: The discriminant function.
mu_vecs: A list of mean vectors as input for g.
cov_mats: A list of covariance matrices as input for g.
Returns a tuple (g_i()_value, class label).
"""
assert(len(mu_vecs) == len(cov_mats)), 'Number of mu_vecs and cov_mats must be equal.'
g_vals = []
for m,c in zip(mu_vecs, cov_mats):
g_vals.append(g(x_vec, mu_vec=m, cov_mat=c))
max_index, max_value = max(enumerate(g_vals), key=operator.itemgetter(1))
return (max_value, max_index + 1)
到目前为止,该代码可用于分类,例如,
import prettytable
classification_dict, error = empirical_error(all_samples, [1,2], classify_data, [discriminant_function,\
[mu_est_1, mu_est_2],
[cov_est_1, cov_est_2]])
labels_predicted = ['w{} (predicted)'.format(i) for i in [1,2]]
labels_predicted.insert(0,'training dataset')
train_conf_mat = prettytable.PrettyTable(labels_predicted)
for i in [1,2]:
a, b = [classification_dict[i][j] for j in [1,2]]
# workaround to unpack (since Python does not support just '*a')
train_conf_mat.add_row(['w{} (actual)'.format(i), a, b])
print(train_conf_mat)
print('Empirical Error: {:.2f} ({:.2f}%)'.format(error, error * 100))
+------------------+----------------+----------------+
| training dataset | w1 (predicted) | w2 (predicted) |
+------------------+----------------+----------------+
| w1 (actual) | 49 | 1 |
| w2 (actual) | 1 | 49 |
+------------------+----------------+----------------+
Empirical Error: 0.02 (2.00%)
对于像这样的简单数据集:
编辑:
对于协方差相等的简单情况(线性决策边界),我能够使用 fsolve
函数:
from scipy.optimize import fsolve
x = list(np.arange(-2, 6, 0.1))
y = [fsolve(lambda y: discr_func(i, y, cov_mat=cov_est_1, mu_vec=mu_est_1) - \
discr_func(i, y, cov_mat=cov_est_2, mu_vec=mu_est_2), 0) for i in x]
但是,它不适用于二次解,我明白了
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/scipy/optimize/minpack.py:236: RuntimeWarning: The iteration is not making good progress, as measured by the
improvement from the last five Jacobian evaluations.
warnings.warn(msg, RuntimeWarning)
有任何提示或替代方案吗?
编辑 2:
我能够通过 scipy.optimize.bisect
(模拟到 fsolve)来解决它。结果看起来是“正确的”——我求解了一个更简单的方程,其中决策边界是一个线性函数 (x2 = 3-x1),当我对它使用 bisect
时,它计算例如,x1 = 3 和 x2 = 3 的精确结果。
无论如何,这是二次函数的结果(我在这里通过最大似然估计来估计参数)和协方差相等的线性情况!非常感谢您的宝贵时间和帮助!
为了
from matplotlib import pyplot as plt
import numpy as np
import scipy.optimize
x = np.arange(-6,6,0.1)
true_y = [true_dec_bound(x1) for x1 in x]
for i in [50,1000,10000]:
# compute boundary for MLE estimate
y_est = []
for j in x:
y_est.append(scipy.optimize.bisect(lambda y: discr_func(j, y, cov_mat=cov1_ests[i], mu_vec=mu1_ests[i]) - \
discr_func(j, y, cov_mat=cov2_ests[i], mu_vec=mu2_ests[i]), -10, 10))
y_est = [float(i) for i in y_est]
# plot data
f, ax = plt.subplots(figsize=(7, 7))
plt.ylabel('$x_2$', size=20)
plt.xlabel('$x_1$', size=20)
ax.scatter(samples_c1[i][:,0], samples_c1[i][:,1], \
marker='o', color='green', s=40, alpha=0.5, label='$\omega_1$')
ax.scatter(samples_c2[i][:,0], samples_c2[i][:,1], \
marker='^', color='red', s=40, alpha=0.5, label='$\omega_2$')
plt.title('%s bivariate random training samples per class' %i)
plt.legend()
# plot boundaries
plt.plot(x_true50, y_true50, 'b--', lw=3, label='true param. boundary')
plt.plot(x_est50, y_est50, 'k--', lw=3, label='MLE boundary')
plt.legend(loc='lower left')
plt.show()
最佳答案
现在只是想发布我的初步解决方案。但这可能不是最佳的......
def discr_func(x, y, cov_mat, mu_vec):
"""
Calculates the value of the discriminant function for a dx1 dimensional
sample given covariance matrix and mean vector.
Keyword arguments:
x_vec: A dx1 dimensional numpy array representing the sample.
cov_mat: numpy array of the covariance matrix.
mu_vec: dx1 dimensional numpy array of the sample mean.
Returns a float value as result of the discriminant function.
"""
x_vec = np.array([[x],[y]])
W_i = (-1/2) * np.linalg.inv(cov_mat)
assert(W_i.shape[0] > 1 and W_i.shape[1] > 1), 'W_i must be a matrix'
w_i = np.linalg.inv(cov_mat).dot(mu_vec)
assert(w_i.shape[0] > 1 and w_i.shape[1] == 1), 'w_i must be a column vector'
omega_i_p1 = (((-1/2) * (mu_vec).T).dot(np.linalg.inv(cov_mat))).dot(mu_vec)
omega_i_p2 = (-1/2) * np.log(np.linalg.det(cov_mat))
omega_i = omega_i_p1 - omega_i_p2
assert(omega_i.shape == (1, 1)), 'omega_i must be a scalar'
g = ((x_vec.T).dot(W_i)).dot(x_vec) + (w_i.T).dot(x_vec) + omega_i
return float(g)
#g1 = discr_func(x, y, cov_mat=cov_mat1, mu_vec=mu_vec_1)
#g2 = discr_func(x, y, cov_mat=cov_mat2, mu_vec=mu_vec_2)
x_est50 = list(np.arange(-6, 6, 0.1))
y_est50 = []
for i in x_est50:
y_est50.append(scipy.optimize.bisect(lambda y: discr_func(i, y, cov_mat=cov_est_1, mu_vec=mu_est_1) - \
discr_func(i, y, cov_mat=cov_est_2, mu_vec=mu_est_2), -10,10))
y_est50 = [float(i) for i in y_est50]
结果如下:(蓝色为二次情况,红色为线性情况(等方差)
关于python - 在评估等同于 2 个函数调用的结果时,寻找一种方法(最好是在 Python 中)获取第二个参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23205571/
我需要您在以下方面提供帮助。近一个月来,我一直在阅读有关任务和异步的内容。 我想尝试在一个简单的 wep api 项目中实现我新获得的知识。我有以下方法,并且它们都按预期工作: public Htt
我的可执行 jar 中有一个模板文件 (.xls)。不需要在运行时我需要为这个文件创建 100 多个副本(稍后将唯一地附加)。用于获取 jar 文件中的资源 (template.xls)。我正在使用
我在查看网站的模型代码时对原型(prototype)有疑问。我知道这对 Javascript 中的继承很有用。 在这个例子中... define([], function () { "use
影响我性能的前三项操作是: 获取滚动条 获取偏移高度 Ext.getStyle 为了解释我的应用程序中发生了什么:我有一个网格,其中有一列在每个单元格中呈现网格。当我几乎对网格的内容做任何事情时,它运
我正在使用以下函数来获取 URL 参数。 function gup(name, url) { name = name.replace(/[\[]/, '\\\[').replace(/[\]]/,
我最近一直在使用 sysctl 来做很多事情,现在我使用 HW_MACHINE_ARCH 变量。我正在使用以下代码。请注意,当我尝试获取其他变量 HW_MACHINE 时,此代码可以完美运行。我还认为
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 关闭 9 年前。 要求提供代码的问题必须表现出对所解决问题的最低限度的理解。包括尝试过的解决方案、为什么
由于使用 main-bower-files 作为使用 Gulp 的编译任务的一部分,我无法使用 node_modules 中的 webpack 来require 模块code> dir 因为我会弄乱当
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 5 年前。 Improve this qu
我使用 Gridlayout 在一行中放置 4 个元素。首先,我有一个 JPanel,一切正常。对于行数变大并且我必须能够向下滚动的情况,我对其进行了一些更改。现在我的 JPanel 上添加了一个 J
由于以下原因,我想将 VolumeId 的值保存在变量中: #!/usr/bin/env python import boto3 import json import argparse import
我正在将 MSAL 版本 1.x 更新为 MSAL-browser 的 Angular 。所以我正在尝试从版本 1.x 迁移到 2.X.I 能够成功替换代码并且工作正常。但是我遇到了 acquireT
我知道有很多关于此的问题,例如 Getting daily averages with pandas和 How get monthly mean in pandas using groupby但我遇到
This is the query string that I am receiving in URL. Output url: /demo/analysis/test?startDate=Sat+
我正在尝试使用 javascript 中的以下代码访问 Geoserver 层 var gkvrtWmsSource =new ol.source.ImageWMS({ u
API 需要一个包含授权代码的 header 。这就是我到目前为止所拥有的: var fullUrl = 'https://api.ecobee.com/1/thermostat?json=\{"s
如何获取文件中的最后一个字符,如果是某个字符,则删除它而不将整个文件加载到内存中? 这就是我目前所拥有的。 using (var fileStream = new FileStream("file.t
我是这个社区的新手,想出了我的第一个问题。 我正在使用 JSP,我成功地创建了 JSP-Sites,它正在使用jsp:setParameter 和 jsp:getParameter 具有单个字符串。
在回答 StoreStore reordering happens when compiling C++ for x86 @Peter Cordes 写过 For Acquire/Release se
我有一个函数,我们将其命名为 X1,它返回变量 Y。该函数在操作 .on("focusout", X1) 中使用。如何获取变量Y?执行.on后X1的结果? 最佳答案 您可以更改 Y 的范围以使其位于函
我是一名优秀的程序员,十分优秀!