#  Kernel density estimation
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from sklearn.neighbors import KernelDensity
# Code reference: http://scikit-learn.org/stable/auto_examples/neighbors/
# plot_kde_1d.html
N = 200
np.random.seed(1)
# Create 2 normal distributed data set
norm_data_1 = np.random.normal(0, 1, int(0.3 * N))
norm_data_2 = np.random.normal(5, 1, int(0.7 * N))
norm_data = np.concatenate((norm_data_1, norm_data_2)) X_plot = np.linspace(-5, 10, 1000) # Create x axis range
# Create linear combination of 2 normal distributed random variable
norm_linear = (0.3 * norm(0, 1).pdf(X_plot) + 0.7 * norm(5, 1).pdf(X_plot)) # figure
fig, ax = plt.subplots()
# Plot the real distribution
ax.fill(X_plot, norm_linear, fc='black', alpha=0.2,
label='Linearcombination')
# Use 3 different kernels to estimate
for kernel in ['gaussian', 'tophat', 'epanechnikov']:
# Initial an object to use kernel function to fit data,
# bandwidth will affect the result
kde = KernelDensity(kernel=kernel, bandwidth=0.5).fit(norm_data.reshape(-1, 1))
# Evaluate the density model on the data
log_dens = kde.score_samples(X_plot.reshape(-1, 1))
ax.plot(X_plot, np.exp(log_dens), '-',
label="kernel ='{0}'".format(kernel)) # Add text on the plot, position argument can be arbitrary
ax.text(6, 0.38, "N={0} points".format(N))
ax.legend(loc='upper left')
# Plot the random points, squeeze them into narrow space
ax.plot(norm_data, -0.005 - 0.01 *
np.random.random(norm_data.shape[0]), '+k') # Set x-axis y-axis limit to adjust the figure
ax.set_xlim(-4, 9)
ax.set_ylim(-0.03, 0.4)
fig.savefig('kernel_estimation.png', dpi=300)
plt.show()

二维散点图:

# Using the Box-Mueller Method to generate 2-dim normally distributed variables
import numpy as np
import matplotlib.pyplot as plt np.random.seed(100) # Set seed from comparability
# For mu = (0,0), covariance matrix Sigma = identity matrix
n = 500 # Number of random numbers
msize = 0.1 # determines the size of the plotted points # a good size might be msize=5 for n=500 pts and msize=0.1 for n>50K
a = np.random.exponential(scale=1, size=n)
phi = np.random.uniform(low=0, high=2 * np.pi, size=n)
# change to cartesian coordinates
x = a * np.cos(phi)
y = a * np.sin(phi)
plt.figure(figsize=(4, 4))
plt.plot(x, y, 'ro', markersize=msize) # for covariance matrix Sigma = A: Y = X/sqrt(Sigma) ~ N(0,I) => Y*sqrt(Sigma)
# Calculate sqrt(A) with Jordan decomposition
A = [[3, 1], [1, 1]]
A_eig = np.linalg.eig(A) E_val = A_eig[0]
Gamma = A_eig[1]
Lambda = np.diag(E_val)
np.sqrt(Lambda)
Lambda12 = np.sqrt(Lambda) A12 = np.dot(np.dot(Gamma, Lambda12), np.transpose(Gamma)) # Solve with matrix multiplication
c = [x, y]
tfxy = np.dot(A12, c) # print(N)
plt.figure(2, figsize=(6, 4))
plt.plot(tfxy[0], tfxy[1], 'ro', markersize=msize)

Gaussion的更多相关文章

  1. GA代码中的细节

    GA-BLX交叉-Gaussion变异 中的代码细节: 我写了一个GA的代码,在2005测试函数上一直不能得到与实验室其他同学类似的数量级的结果.现在参考其他同学的代码,发现至少有如下问题: 1.在交 ...

  2. Andrew Ng机器学习课程笔记--week7(SVM)

    本周主要学习SVM 一. 内容概要 Large Margin Classification Optimization Objective(优化Objective(损失函数)) Large Margin ...

  3. Andrew Ng机器学习课程笔记--week9(上)(异常检测&推荐系统)

    本周内容较多,故分为上下两篇文章. 一.内容概要 1. Anomaly Detection Density Estimation Problem Motivation Gaussian Distrib ...

  4. Andrew Ng机器学习课程笔记--week9(下)(推荐系统&协同过滤)

    本周内容较多,故分为上下两篇文章. 本文为下篇. 一.内容概要 1. Anomaly Detection Density Estimation Problem Motivation Gaussian ...

  5. R语言进行机器学习方法及实例(一)

    版权声明:本文为博主原创文章,转载请注明出处   机器学习的研究领域是发明计算机算法,把数据转变为智能行为.机器学习和数据挖掘的区别可能是机器学习侧重于执行一个已知的任务,而数据发掘是在大数据中寻找有 ...

  6. 重写轮子之 GaussionNB

    我仿照sk-learn 中 GaussionNB 的结构, 重写了该算法的轮子,命名为 MyGaussionNB, 如下: # !/usr/bin/python # -*- coding:utf-8 ...

  7. Abnormal Detection(异常检测)和 Supervised Learning(有监督训练)在异常检测上的应用初探

    1. 异常检测 VS 监督学习 0x1:异常检测算法和监督学习算法的对比 总结来讲: . 在异常检测中,异常点是少之又少,大部分是正常样本,异常只是相对小概率事件 . 异常点的特征表现非常不集中,即异 ...

  8. 神经网络训练tricks

    神经网络构建好,训练不出好的效果怎么办?明明说好的拟合任意函数(一般连续)(为什么?可以参考http://neuralnetworksanddeeplearning.com/),说好的足够多的数据(h ...

  9. 高斯混合模型的EM算法

    高斯混合模型的EM算法 混合高斯模型 高斯混合模型的概率分布可以写成多个高斯分布的线形叠加,即 \[ p(\mathbf x) = \sum_{k=1}^{K}\pi_k\mathcal N(\mat ...

随机推荐

  1. 【springboot】 junit 测试

    参考:https://blog.csdn.net/u012100371/article/details/77206863 @RunWith(SpringJUnit4ClassRunner.class) ...

  2. C 静态存储动态存储

    首先,我们可以把程序所占的内存空间分为三个部分:(可以根据静态资源区.栈区.堆区来划分) 静态存储:程序运行期间由系统分配固定得到存储空间(栈): 动态存储:开发者根据自身需要进行动态分配的存储空间( ...

  3. CentOS 6.x 系统中安装原生 Hadoop 2

    2020年整理博客发现原文地址已经失效,推荐学习地址厦门大学数据库实验室 本教程适合于在 CentOS 6.x 系统中安装原生 Hadoop 2,适用于Hadoop 2.7.1, Hadoop 2.6 ...

  4. Struts中整合的强大Ognl学习(一)

    测试使用了一个JavaBean的User,User中的Address单独封装再形成了一个JavaBean: 为了测试静态方法和静态变量调用,写了一个Util方法: 因为测试Ognl功能过多所以直接使用 ...

  5. go语言学习代码

    1.day01 package main //声明文件所在的包,每个go文件必须有归属包 import "fmt" //引入程序中需要用的包,为了使用包下的函数 比如函数:Prin ...

  6. Insights直播预告 | 多媒体管线服务,助您轻松进入“技术流”创新阵地

    [导读] 随着各类音视频移动应用快速发展,短视频.线上直播等娱乐方式逐渐为大众所喜爱.优质的视听效果和交互体验,往往能吸引更多的用户.多媒体管线服务作为一个轻量级的多媒体开发框架,其跨平台.高性能的多 ...

  7. 数据结构(c++)(第二版) Dijkstra最短路径算法 教学示范代码出现重大问题!

    前言 去年在数据结构(c++)的Dijkstra教学算法案例中,发现了一个 bug 导致算法不能正常的运行,出错代码只是4行的for循环迭代代码. 看到那里就觉得有问题,但书中只给了关键代码的部分,其 ...

  8. iframe 内容适用高度

    HTML: <div class="content"> <iframe id="frameObj" src="链接" fr ...

  9. 源码解读Dubbo分层设计思想

    一.Dubbo分层整体设计概述 我们先从下图开始简单介绍Dubbo分层设计概念: (引用自Duboo开发指南-框架设计文档) 如图描述Dubbo实现的RPC整体分10层:service.config. ...

  10. python模块--pathlib

    类/属性/方法 返回值 参数 说明 .Path() p 创建Path对象 path 路径         p.parent Path 返回上一级路径 p.parents iter 上一级路径, 上上级 ...