TensorFlow的初次使用+Python画3D图和计算KL散度

ython计算KL散度import numpy as np
import scipy.stats

x = [np.random.randint(1,11) for i in range(10)]
print(x)
print(np.sum(x))
px = x/np.sum(x)#归一化
print(px)

y = [np.random.randint(1, 11) for i in range(10)]
print(y)
print(np.sum(y))
py = y / np.sum(y)#归一化
print(py)
## scipy计算函数可以处理非归一化情况,因此这里使用# scipy.stats.entropy(x, y)或scipy.stats.entropy(px, py)均可
KL = scipy.stats.entropy(x, y)
print(KL)

#自己编程实现
kl= 0.0
for i in range(10):
    kl += px[i] * np.log(px[i]/py[i])
print(kl)

#TensorFlow的神经网络
import sys;
sys.path.append("/home/hxj/anaconda3/lib/python3.6/site-packages")
import tensorflow as tf
import numpy as np

x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1+0.3
print(x_data)
print(y_data)

Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weights*x_data + biases
print(y)
loss = tf.reduce_mean(tf.square(y-y_data))

optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

for step in range(201):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(Weights), sess.run(biases))
#Python画2D图from functools import partial

import numpy

from matplotlib import pyplot

# Define a PDF

x_samples = numpy.arange(-3, 3.01, 0.01)

PDF = numpy.empty(x_samples.shape)

PDF[x_samples < 0] = numpy.round(x_samples[x_samples < 0] + 3.5) / 3

PDF[x_samples >= 0] = 0.5 * numpy.cos(numpy.pi * x_samples[x_samples >= 0]) + 0.5

PDF /= numpy.sum(PDF)

# Calculate approximated CDF

CDF = numpy.empty(PDF.shape)

cumulated = 0

for i in range(CDF.shape[0]):

    cumulated += PDF[i]

    CDF[i] = cumulated

# Generate samples

generate = partial(numpy.interp, xp=CDF, fp=x_samples)

u_rv = numpy.random.random(10000)

x = generate(u_rv)

# Visualization

fig, (ax0, ax1) = pyplot.subplots(ncols=2, figsize=(9, 4))

ax0.plot(x_samples, PDF)

ax0.axis([-3.5, 3.5, 0, numpy.max(PDF)*1.1])

ax1.hist(x, 100)

pyplot.show()


#Python画3D图
import matplotlib.pyplot as plt
import numpy as np

from mpl_toolkits.mplot3d import Axes3D

np.random.seed(42)

# 采样个数500
n_samples = 500
dim = 3

# 先生成一组3维正态分布数据,数据方向完全随机
samples = np.random.multivariate_normal(
    np.zeros(dim),
    np.eye(dim),
    n_samples
)

# 通过把每个样本到原点距离和均匀分布吻合得到球体内均匀分布的样本
for i in range(samples.shape[0]):
    r = np.power(np.random.random(), 1.0/3.0)
    samples[i] *= r / np.linalg.norm(samples[i])

upper_samples = []
lower_samples = []

for x, y, z in samples:
    # 3x+2y-z=1作为判别平面
    if z > 3*x + 2*y - 1:
        upper_samples.append((x, y, z))
    else:
        lower_samples.append((x, y, z))

fig = plt.figure(‘3D scatter plot‘)
ax = fig.add_subplot(111, projection=‘3d‘)

uppers = np.array(upper_samples)
lowers = np.array(lower_samples)

# 用不同颜色不同形状的图标表示平面上下的样本
# 判别平面上半部分为红色圆点,下半部分为绿色三角
ax.scatter(uppers[:, 0], uppers[:, 1], uppers[:, 2], c=‘r‘, marker=‘o‘)
ax.scatter(lowers[:, 0], lowers[:, 1], lowers[:, 2], c=‘g‘, marker=‘^‘)

plt.show()

原文地址:https://www.cnblogs.com/hxjbc/p/8241373.html

时间: 2024-10-09 05:00:44

TensorFlow的初次使用+Python画3D图和计算KL散度的相关文章

python 画3D的高斯曲线

用python画3D的高斯曲线,我想如果有多个峰怎么画? import numpy as npimport matplotlib.pyplot as pltimport mathimport mpl_toolkits.mplot3d x, y = np.mgrid[-2:2:200j, -2:2:200j]z=(1/2*math.pi*3**2)*np.exp(-(x**2+y**2)/2*3**2)ax = plt.subplot(111, projection='3d')ax.plot_su

用ChemDraw画3D图的方法

在绘制化学图形的时候,很多的用户都会发现很多的图形都是三维的,这个时候就需要找一款能够绘制3D图形的化学绘图软件.ChemOffice 15.1是最新的化学绘图工具套件,总共有三个组件,其中ChemDraw 15.1 Pro和ChemOffice 15.1 Pro可以画3D图,因为这两个版本中均含有Chem 3D功能组件.下面本教程就来给大家分享一下用ChemDraw画3D图的方法? Chem 3D组件是ChemOffice的主要模块,用于分子的三维空间模型显示与构造,并可以结合分子力学(MM)

Python画三维图-----插值平滑数据

一.二维的插值方法: 原始数据(x,y) 先对横坐标x进行扩充数据量,采用linspace.[如下面例子,由7个值扩充到300个] 采用scipy.interpolate中的spline来对纵坐标数据y进行插值[也由7个扩充到300个]. 画图 import matplotlib.pyplot as plt import numpy as np#数据 T = np.array([6, 7, 8, 9, 10, 11, 12]) power = np.array([1.53E+03, 5.92E+

matplotlib画3D图修改X,Y,Z,colorbar的刻度值

修改X,Y,Z轴的刻度值 from matplotlib.ticker import MultipleLocator,FuncFormatter from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib import colors from matplotlib.ticker import LinearLocator, Form

python画完图后运行闪退解决办法

最近学习python,用matplotlib库画图,运行程序后,就会闪退. 解决办法:     python2.*后面加上:raw_input()     python3.*后面加上:input() 我的python是python3.2,最后需加input,如下: 如果你是3.*后面加的raw_input(),就会出现如下错误:

利用python画折线图

# encoding=utf-8import matplotlib.pyplot as pltfrom pylab import * #支持中文mpl.rcParams['font.sans-serif'] = ['SimHei'] names = ['5', '10', '15', '20', '25']x = range(len(names))y = [0.855, 0.84, 0.835, 0.815, 0.81]y1=[0.86,0.85,0.853,0.849,0.83]#plt.pl

python中matplotlib画折线图实例(坐标轴数字、字符串混搭及标题中文显示)

最近在用python中的matplotlib画折线图,遇到了坐标轴 "数字+刻度" 混合显示.标题中文显示.批量处理等诸多问题.通过学习解决了,来记录下.如有错误或不足之处,望请指正. 一.最简单的基本框架如下:已知x,y,画出折线图并保存.此时x和y均为数字. 1 # -*- coding: utf-8 -*- 2 3 import matplotlib.pyplot as plt #引入matplotlib的pyplot子库,用于画简单的2D图 4 import random 5

MATLAB中mesh函数的使用:基于像素强度画3D密度图(create a 3D density plot based on the pixel intensity:mesh function)

所用的函数非常简单,只需要用到mesh函数,示例代码如下: Ima=imread('F:\pathto\test.jpg'); surf_ima = surf(rgb2gray(Ima)); %黑色的3D图 title('3D') mesh_ima = mesh(rgb2gray(Ima)); %有色彩的3D图 参考链接:https://cn.mathworks.com/matlabcentral/answers/17998-image-processing-how-can-i-create-a

3-Highcharts 3D图之3D柱状图分组叠堆3D图

<!DOCTYPE> <html lang='en'> <head> <title>3-Highcharts 3D图之3D柱状图分组叠堆3D图</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <script src="../jquery-2.1.4/jquery.min.js&q