python里的pi怎么用_Python numpy.pi() 使用实例

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def deriveKernel(self, params, i):

self.checkParamsI(params, i)

ell = np.exp(params[0])

p = np.exp(params[1])

#compute d2

if (self.K_sq is None): d2 = sq_dist(self.X_scaled.T / ell)#precompute squared distances

else: d2 = self.K_sq / ell**2

#compute dp

dp = self.dp/p

K = np.exp(-d2 / 2.0)

if (i==0): return d2*K*np.cos(2*np.pi*dp)

elif (i==1): return 2*np.pi*dp*np.sin(2*np.pi*dp)*K

else: raise Exception('invalid parameter index:' + str(i))

Example 2

def gelu(x):

return 0.5 * x * (1 + T.tanh(T.sqrt(2 / np.pi) * (x + 0.044715 * T.pow(x, 3))))

Example 3

def get_local_wavenumbermesh(self, scaled=True, broadcast=False,

eliminate_highest_freq=False):

kx = fftfreq(self.N[0], 1./self.N[0])

ky = rfftfreq(self.N[1], 1./self.N[1])

if eliminate_highest_freq:

for i, k in enumerate((kx, ky)):

if self.N[i] % 2 == 0:

k[self.N[i]//2] = 0

Ks = np.meshgrid(kx, ky[self.rank*self.Np[1]//2:(self.rank*self.Np[1]//2+self.Npf)], indexing='ij', sparse=True)

if scaled is True:

Lp = 2*np.pi/self.L

Ks[0] *= Lp[0]

Ks[1] *= Lp[1]

K = Ks

if broadcast is True:

K = [np.broadcast_to(k, self.complex_shape()) for k in Ks]

return K

Example 4

def _generate_data():

"""

?????

????u(k-1) ? y(k-1)?????y(k)

"""

# u = np.random.uniform(-1,1,200)

# y=[]

# former_y_value = 0

# for i in np.arange(0,200):

# y.append(former_y_value)

# next_y_value = (29.0 / 40) * np.sin(

# (16.0 * u[i] + 8 * former_y_value) / (3.0 + 4.0 * (u[i] ** 2) + 4 * (former_y_value ** 2))) \

# + (2.0 / 10) * u[i] + (2.0 / 10) * former_y_value

# former_y_value = next_y_value

# return u,y

u1 = np.random.uniform(-np.pi,np.pi,200)

u2 = np.random.uniform(-1,1,200)

y = np.zeros(200)

for i in range(200):

value = np.sin(u1[i]) + u2[i]

y[i] = value

return u1, u2, y

Example 5

def ae(x):

if nonlinearity_name == 'relu':

f = tf.nn.relu

elif nonlinearity_name == 'elu':

f = tf.nn.elu

elif nonlinearity_name == 'gelu':

# def gelu(x):

# return tf.mul(x, tf.erfc(-x / tf.sqrt(2.)) / 2.)

# f = gelu

def gelu_fast(_x):

return 0.5 * _x * (1 + tf.tanh(tf.sqrt(2 / np.pi) * (_x + 0.044715 * tf.pow(_x, 3))))

f = gelu_fast

elif nonlinearity_name == 'silu':

def silu(_x):

return _x * tf.sigmoid(_x)

f = silu

# elif nonlinearity_name == 'soi':

# def soi_map(x):

# u = tf.random_uniform(tf.shape(x))

# mask = tf.to_float(tf.less(u, (1 + tf.erf(x / tf.sqrt(2.))) / 2.))

# return tf.cond(is_training, lambda: tf.mul(mask, x),

# lambda: tf.mul(x, tf.erfc(-x / tf.sqrt(2.)) / 2.))

# f = soi_map

else:

raise NameError("Need 'relu', 'elu', 'gelu', or 'silu' for nonlinearity_name")

h1 = f(tf.matmul(x, W['1']) + b['1'])

h2 = f(tf.matmul(h1, W['2']) + b['2'])

h3 = f(tf.matmul(h2, W['3']) + b['3'])

h4 = f(tf.matmul(h3, W['4']) + b['4'])

h5 = f(tf.matmul(h4, W['5']) + b['5'])

h6 = f(tf.matmul(h5, W['6']) + b['6'])

h7 = f(tf.matmul(h6, W['7']) + b['7'])

return tf.matmul(h7, W['8']) + b['8']

Example 6

def score_samples(self, X):

"""Return the log-likelihood of each sample

See. "Pattern Recognition and Machine Learning"

by C. Bishop, 12.2.1 p. 574

or http://www.miketipping.com/papers/met-mppca.pdf

Parameters

----------

X: array, shape(n_samples, n_features)

The data.

Returns

-------

ll: array, shape (n_samples,)

Log-likelihood of each sample under the current model

"""

check_is_fitted(self, 'mean_')

X = check_array(X)

Xr = X - self.mean_

n_features = X.shape[1]

log_like = np.zeros(X.shape[0])

precision = self.get_precision()

log_like = -.5 * (Xr * (np.dot(Xr, precision))).sum(axis=1)

log_like -= .5 * (n_features * log(2. * np.pi)

- fast_logdet(precision))

return log_like

Example 7

def getTrainTestKernel(self, params, Xtest):

self.checkParams(params)

ell = np.exp(params[0])

p = np.exp(params[1])

Xtest_scaled = Xtest/np.sqrt(Xtest.shape[1])

d2 = sq_dist(self.X_scaled.T/ell, Xtest_scaled.T/ell)#precompute squared distances

#compute dp

dp = np.zeros(d2.shape)

for d in xrange(self.X_scaled.shape[1]):

dp += (np.outer(self.X_scaled[:,d], np.ones((1, Xtest_scaled.shape[0]))) - np.outer(np.ones((self.X_scaled.shape[0], 1)), Xtest_scaled[:,d]))

dp /= p

K = np.exp(-d2 / 2.0)

return np.cos(2*np.pi*dp)*K

Example 8

def reset(self,random_start_state=False, assign_state = False, n=None, k = None, \

perturb_params = False, p_LINK_LENGTH_1 = 0, p_LINK_LENGTH_2 = 0, \

p_LINK_MASS_1 = 0, p_LINK_MASS_2 = 0, **kw):

self.t = 0

self.state = np.random.uniform(low=-0.1,high=0.1,size=(4,))

self.LINK_LENGTH_1 = 1. # [m]

self.LINK_LENGTH_2 = 1. # [m]

self.LINK_MASS_1 = 1. #: [kg] mass of link 1

self.LINK_MASS_2 = 1.

if perturb_params:

self.LINK_LENGTH_1 += (self.LINK_LENGTH_1 * p_LINK_LENGTH_1) # [m]

self.LINK_LENGTH_2 += (self.LINK_LENGTH_2 * p_LINK_LENGTH_2) # [m]

self.LINK_MASS_1 += (self.LINK_MASS_1 * p_LINK_MASS_1) #: [kg] mass of link 1

self.LINK_MASS_2 += (self.LINK_MASS_2 * p_LINK_MASS_2) #: [kg] mass of link 2

# The idea here is that we can initialize our batch randomly so that we can get

# more variety in the state space that we attempt to fit a policy to.

if random_start_state:

self.state[:2] = np.random.uniform(-np.pi,np.pi,size=2)

if assign_state:

self.state[0] = wrap((2*k*np.pi)/(1.0*n),-np.pi,np.pi)

Example 9

def calc_reward(self, action = None, state = None , **kw ):

'''Calculates the continuous reward based on the height of the foot (y position)

with a penalty applied if the hinge is moving (we want the acrobot to be upright

and stationary!), which is then normalized by the combined lengths of the links'''

t = self.target

if state is None:

s = self.state

else:

s = state

# Make sure that input state is clipped/wrapped to the given bounds (not guaranteed when coming from the BNN)

s[0] = wrap( s[0] , -np.pi , np.pi )

s[1] = wrap( s[1] , -np.pi , np.pi )

s[2] = bound( s[2] , -self.MAX_VEL_1 , self.MAX_VEL_1 )

s[3] = bound( s[3] , -self.MAX_VEL_1 , self.MAX_VEL_1 )

hinge, foot = self.get_cartesian_points(s)

reward = -0.05 * (foot[0] - self.LINK_LENGTH_1)**2

terminal = self.is_terminal(s)

return 10 if terminal else reward

Example 10

def EStep(self):

P = np.zeros((self.M, self.N))

for i in range(0, self.M):

diff = self.X - np.tile(self.TY[i, :], (self.N, 1))

diff = np.multiply(diff, diff)

P[i, :] = P[i, :] + np.sum(diff, axis=1)

c = (2 * np.pi * self.sigma2) ** (self.D / 2)

c = c * self.w / (1 - self.w)

c = c * self.M / self.N

P = np.exp(-P / (2 * self.sigma2))

den = np.sum(P, axis=0)

den = np.tile(den, (self.M, 1))

den[den==0] = np.finfo(float).eps

self.P = np.divide(P, den)

self.Pt1 = np.sum(self.P, axis=0)

self.P1 = np.sum(self.P, axis=1)

self.Np = np.sum(self.P1)

Example 11

def create_reference_image(size, x0=10., y0=-3., sigma_x=50., sigma_y=30., dtype='float64',

reverse_xaxis=False, correct_axes=True, sizey=None, **kwargs):

"""

Creates a reference image: a gaussian brightness with elliptical

"""

inc_cos = np.cos(0./180.*np.pi)

delta_x = 1.

x = (np.linspace(0., size - 1, size

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
雷达图(Radar Chart),也称为蜘蛛网图(Spider Chart)或星形图(Star Chart),是一种多变量数据可视化方式,通常用于比较多个变量或维度的相对关系。 Python使用`matplotlib`库可以绘制雷达图。下面我将为你详细讲解如何使用Python绘制雷达图。 首先,我们需要导入相关的库: ```python import numpy as np import matplotlib.pyplot as plt ``` 接下来,我们需要准备数据。假设我们要绘制一个学生的五项能力评估雷达图,其中包括语文、数学、英语、体育和艺术五个维度的得分: ```python labels = np.array(['语文', '数学', '英语', '体育', '艺术']) data = np.array([90, 80, 85, 70, 60]) ``` 然后,我们需要计算出每个维度在雷达图中的角度。因为雷达图是一个圆形,所以每个维度的角度应该是均分360度,即每个角度应该是`360 / 数据维度个数`。代码如下: ```python angles = np.linspace(0, 2*np.pi, len(labels), endpoint=False) angles = np.concatenate((angles, [angles[0]])) ``` 接下来,我们需要将数据和角度转换成极坐标系下的坐标。这我们可以使用`np.vstack()`函数将数据和第一个数据点组合起来,再使用`np.cos()`和`np.sin()`函数计算出每个数据点的坐标。代码如下: ```python data = np.concatenate((data, [data[0]])) coords = np.vstack((angles, data)).T coords = np.concatenate((coords, [coords[0]])) ``` 最后,我们可以使用`matplotlib`的`plot()`函数绘制出雷达图。代码如下: ```python fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True)) ax.plot(angles, data, 'o-', linewidth=2) ax.fill(coords[:, 0], coords[:, 1], alpha=0.25) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title('学生五项能力评估') ax.grid(True) ``` 完整的代码如下: ```python import numpy as np import matplotlib.pyplot as plt labels = np.array(['语文', '数学', '英语', '体育', '艺术']) data = np.array([90, 80, 85, 70, 60]) angles = np.linspace(0, 2*np.pi, len(labels), endpoint=False) angles = np.concatenate((angles, [angles[0]])) data = np.concatenate((data, [data[0]])) coords = np.vstack((angles, data)).T coords = np.concatenate((coords, [coords[0]])) fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True)) ax.plot(angles, data, 'o-', linewidth=2) ax.fill(coords[:, 0], coords[:, 1], alpha=0.25) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title('学生五项能力评估') ax.grid(True) plt.show() ``` 运行代码,我们可以看到绘制出来的雷达图: ![雷达图](https://img-blog.csdnimg.cn/20211104121534521.png) 这个雷达图表示该学生在语文、数学、英语、体育和艺术五个维度上的得分情况,可以用于对比不同学生在这五个维度上的能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值