python支持double_Python numpy.double() 使用实例

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 al...
摘要由CSDN通过智能技术生成

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 logp_trace(model):

"""

return a trace of logp for model

"""

#init

db = model.db

n_samples = db.trace('deviance').length()

logp = np.empty(n_samples, np.double)

#loop over all samples

for i_sample in range(n_samples):

#set the value of all stochastic to their 'i_sample' value

for stochastic in model.stochastics:

try:

value = db.trace(stochastic.__name__)[i_sample]

stochastic.value = value

except KeyError:

print("No trace available for %s. " % stochastic.__name__)

#get logp

logp[i_sample] = model.logp

return logp

Example 2

def logp_trace(model):

"""

return a trace of logp for model

"""

#init

db = model.db

n_samples = db.trace('deviance').length()

logp = np.empty(n_samples, np.double)

#loop over all samples

for i_sample in range(n_samples):

#set the value of all stochastic to their 'i_sample' value

for stochastic in model.stochastics:

try:

value = db.trace(stochastic.__name__)[i_sample]

stochastic.value = value

except KeyError:

print("No trace available for %s. " % stochastic.__name__)

#get logp

logp[i_sample] = model.logp

return logp

Example 3

def score_mod(gold, prediction, method):

"""

Computes correlation coefficient for two lists of values.

:param gold: list of gold values

:param prediction: list of predicted values

:param method: string, can be either of "pearson", "spearman" or "auc" (area under curve)

:return: correlation coefficient and p-value

"""

if len(gold) != len(prediction):

raise ValueError("The two arrays must have the same length!")

gold = np.array(gold, dtype=np.double)

prediction = np.array(prediction, dtype=np.double)

if method == "pearson":

return pearson(gold, prediction)

elif method == "spearman":

return spearman(gold, prediction)

elif method == "auc":

return auc(gold, prediction)

else:

raise NotImplementedError("Unknown scoring measure:%s" % method)

Example 4

def test_basic(self):

dts = [np.bool, np.int16, np.int32, np.int64, np.double, np.complex128,

np.longdouble, np.clongdouble]

for dt in dts:

c = np.ones(53, dtype=np.bool)

assert_equal(np.where( c, dt(0), dt(1)), dt(0))

assert_equal(np.where(~c, dt(0), dt(1)), dt(1))

assert_equal(np.where(True, dt(0), dt(1)), dt(0))

assert_equal(np.where(False, dt(0), dt(1)), dt(1))

d = np.ones_like(c).astype(dt)

e = np.zeros_like(d)

r = d.astype(dt)

c[7] = False

r[7] = e[7]

assert_equal(np.where(c, e, e), e)

assert_equal(np.where(c, d, e), r)

assert_equal(np.where(c, d, e[0]), r)

assert_equal(np.where(c, d[0], e), r)

assert_equal(np.where(c[::2], d[::2], e[::2]), r[::2])

assert_equal(np.where(c[1::2], d[1::2], e[1::2]), r[1::2])

assert_equal(np.where(c[::3], d[::3], e[::3]), r[::3])

assert_equal(np.where(c[1::3], d[1::3], e[1::3]), r[1::3])

assert_equal(np.where(c[::-2], d[::-2], e[::-2]), r[::-2])

assert_equal(np.where(c[::-3], d[::-3], e[::-3]), r[::-3])

assert_equal(np.where(c[1::-3], d[1::-3], e[1::-3]), r[1::-3])

Example 5

def do(self, a, b):

d = linalg.det(a)

(s, ld) = linalg.slogdet(a)

if asarray(a).dtype.type in (single, double):

ad = asarray(a).astype(double)

else:

ad = asarray(a).astype(cdouble)

ev = linalg.eigvals(ad)

assert_almost_equal(d, multiply.reduce(ev, axis=-1))

assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1))

s = np.atleast_1d(s)

ld = np.atleast_1d(ld)

m = (s != 0)

assert_almost_equal(np.abs(s[m]), 1)

assert_equal(ld[~m], -inf)

Example 6

def test_UPLO(self):

Klo = np.array([[0, 0], [1, 0]], dtype=np.double)

Kup = np.array([[0, 1], [0, 0]], dtype=np.double)

tgt = np.array([-1, 1], dtype=np.double)

rtol = get_rtol(np.double)

# Check default is 'L'

w = np.linalg.eigvalsh(Klo)

assert_allclose(w, tgt, rtol=rtol)

# Check 'L'

w = np.linalg.eigvalsh(Klo, UPLO='L')

assert_allclose(w, tgt, rtol=rtol)

# Check 'l'

w = np.linalg.eigvalsh(Klo, UPLO='l')

assert_allclose(w, tgt, rtol=rtol)

# Check 'U'

w = np.linalg.eigvalsh(Kup, UPLO='U')

assert_allclose(w, tgt, rtol=rtol)

# Check 'u'

w = np.linalg.eigvalsh(Kup, UPLO='u')

assert_allclose(w, tgt, rtol=rtol)

Example 7

def test_UPLO(self):

Klo = np.array([[0, 0], [1, 0]], dtype=np.double)

Kup = np.array([[0, 1], [0, 0]], dtype=np.double)

tgt = np.array([-1, 1], dtype=np.double)

rtol = get_rtol(np.double)

# Check default is 'L'

w, v = np.linalg.eigh(Klo)

assert_allclose(w, tgt, rtol=rtol)

# Check 'L'

w, v = np.linalg.eigh(Klo, UPLO='L')

assert_allclose(w, tgt, rtol=rtol)

# Check 'l'

w, v = np.linalg.eigh(Klo, UPLO='l')

assert_allclose(w, tgt, rtol=rtol)

# Check 'U'

w, v = np.linalg.eigh(Kup, UPLO='U')

assert_allclose(w, tgt, rtol=rtol)

# Check 'u'

w, v = np.linalg.eigh(Kup, UPLO='u')

assert_allclose(w, tgt, rtol=rtol)

Example 8

def test_mode_raw(self):

# The factorization is not unique and varies between libraries,

# so it is not possible to check against known values. Functional

# testing is a possibility, but awaits the exposure of more

# of the functions in lapack_lite. Consequently, this test is

# very limited in scope. Note that the results are in FORTRAN

# order, hence the h arrays are transposed.

a = array([[1, 2], [3, 4], [5, 6]], dtype=np.double)

# Test double

h, tau = linalg.qr(a, mode='raw')

assert_(h.dtype == np.double)

assert_(tau.dtype == np.double)

assert_(h.shape == (2, 3))

assert_(tau.shape == (2,))

h, tau =

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
东南亚位于我国倡导推进的“一带一路”海陆交汇地带,作为当今全球发展最为迅速的地区之一,近年来区域内生产总值实现了显著且稳定的增长。根据东盟主要经济体公布的最新数据,印度尼西亚2023年国内生产总值(GDP)增长5.05%;越南2023年经济增长5.05%;马来西亚2023年经济增速为3.7%;泰国2023年经济增长1.9%;新加坡2023年经济增长1.1%;柬埔寨2023年经济增速预计为5.6%。 东盟国家在“一带一路”沿线国家中的总体GDP经济规模、贸易总额与国外直接投资均为最大,因此有着举足轻重的地位和作用。当前,东盟与中国已互相成为双方最大的交易伙伴。中国-东盟贸易总额已从2013年的443亿元增长至 2023年合计超逾6.4万亿元,占中国外贸总值的15.4%。在过去20余年中,东盟国家不断在全球多变的格局里面临挑战并寻求机遇。2023东盟国家主要经济体受到国内消费、国外投资、货币政策、旅游业复苏、和大宗商品出口价企稳等方面的提振,经济显现出稳步增长态势和强韧性的潜能。 本调研报告旨在深度挖掘东南亚市场的增长潜力与发展机会,分析东南亚市场竞争态势、销售模式、客户偏好、整体市场营商环境,为国内企业出海开展业务提供客观参考意见。 本文核心内容: 市场空间:全球行业市场空间、东南亚市场发展空间。 竞争态势:全球份额,东南亚市场企业份额。 销售模式:东南亚市场销售模式、本地代理商 客户情况:东南亚本地客户及偏好分析 营商环境:东南亚营商环境分析 本文纳入的企业包括国外及印尼本土企业,以及相关上下游企业等,部分名单 QYResearch是全球知名的大型咨询公司,行业涵盖各高科技行业产业链细分市场,横跨如半导体产业链(半导体设备及零部件、半导体材料、集成电路、制造、封测、分立器件、传感器、光电器件)、光伏产业链(设备、硅料/硅片、电池片、组件、辅料支架、逆变器、电站终端)、新能源汽车产业链(动力电池及材料、电驱电控、汽车半导体/电子、整车、充电桩)、通信产业链(通信系统设备、终端设备、电子元器件、射频前端、光模块、4G/5G/6G、宽带、IoT、数字经济、AI)、先进材料产业链(金属材料、高分子材料、陶瓷材料、纳米材料等)、机械制造产业链(数控机床、工程机械、电气机械、3C自动化、工业机器人、激光、工控、无人机)、食品药品、医疗器械、农业等。邮箱:market@qyresearch.com
能给一个完整的实例吗,比方说以下python代码:import cv2 import numpy as np # 加载图像 image = cv2.imread("/root/camera/test/v4l2_cap.jpg") # 查看图像中是否存在蓝色和红色 blue_pixels = np.sum(image[:, :, 0]) # 蓝色通道 red_pixels = np.sum(image[:, :, 2]) # 红色通道 colors = "0" if blue_pixels > red_pixels: color = "Blue" elif blue_pixels < red_pixels: color = "Red" else: color = "None" # 将图像转换为灰度图像 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 边缘增强 enhanced_image = cv2.Canny(gray_image, 33, 45) # 形态学操作(腐蚀和膨胀) kernel = np.ones((3, 3), np.uint8) edges1 = cv2.dilate(enhanced_image, kernel, iterations=3) # 在灰度图像中检测圆形 circles = cv2.HoughCircles(edges1, cv2.HOUGH_GRADIENT, dp=1, minDist=100, param1=66, param2=25, minRadius=90, maxRadius=185) shape="" if circles is not None: # 在原始图像上绘制检测到的圆 circles = np.uint16(np.around(circles)) for circle in circles[0, :]: x, y, radius = circle[0], circle[1], circle[2] if abs(x - image.shape[1] // 2) > 100: continue shape = "Circle" cv2.circle(image, (x, y), 90, (0, 255, 0), 2) cv2.circle(image, (x, y), 2, (0, 0, 255), 3) else: shape = "None" # 判断是否同时出现 Rectangle 和 Triangle以及颜色是否有红,绿 if color == "Red" and shape != "Circle" : result = 'r' elif color == "Blue" and shape == "Circle" : result = 'b' else: result = 'n' # 打印检测到的形状、颜色 #print(f"Color:{color}") #print(f"shape:{shape}") print(f"Result: {result}") #cv2.imshow("enhanced_image", enhanced_image) #cv2.imshow("edges1", edges1) #cv2.imshow("Image", image) #cv2.waitKey(0) #cv2.destroyAllWindows()
07-22
下面是将你提供的Python代码转换为Cython的示例: ```python import cv2 import numpy as np cdef extern from "opencv2/core/core_c.h": void* cvLoadImage(const char* filename, int flags) cdef extern from "opencv2/highgui/highgui_c.h": void cvShowImage(const char* name, void* image) void cvWaitKey(int delay) void cvDestroyAllWindows() cdef extern from "opencv2/imgproc/imgproc_c.h": void cvCvtColor(void* src, void* dst, int code) void cvCanny(void* image, void* edges, double threshold1, double threshold2) void cvDilate(void* src, void* dst, void* kernel, int iterations) void cvHoughCircles(void* image, void* circles, int method, double dp, double minDist, double param1, double param2, int minRadius, int maxRadius) void cvCircle(void* img, void* center, int radius, void* color, int thickness) def detect_shape_and_color(): cdef np.ndarray[np.uint8_t, ndim=3] image = np.zeros((480, 640, 3), dtype=np.uint8) cdef np.ndarray[np.uint8_t, ndim=2] gray_image = np.zeros((480, 640), dtype=np.uint8) cdef np.ndarray[np.uint8_t, ndim=2] enhanced_image = np.zeros((480, 640), dtype=np.uint8) cdef np.ndarray[np.uint8_t, ndim=2] edges = np.zeros((480, 640), dtype=np.uint8) cdef np.ndarray[np.float32_t, ndim=3] circles = np.zeros((1, 1, 3), dtype=np.float32) cdef np.ndarray[np.uint8_t, ndim=3] color = np.zeros((1, 1, 3), dtype=np.uint8) # 加载图像 image = cv2.imread(b"/root/camera/test/v4l2_cap.jpg", -1) # 查看图像中是否存在蓝色和红色 blue_pixels = np.sum(image[:, :, 0]) # 蓝色通道 red_pixels = np.sum(image[:, :, 2]) # 红色通道 colors = "0" if blue_pixels > red_pixels: color = "Blue" elif blue_pixels < red_pixels: color = "Red" else: color = "None" # 将图像转换为灰度图像 cvCvtColor(image, gray_image, cv2.COLOR_BGR2GRAY) # 边缘增强 cvCanny(gray_image, edges, 33, 45) # 形态学操作(腐蚀和膨胀) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) cvDilate(edges, enhanced_image, kernel, 3) # 在灰度图像中检测圆形 cvHoughCircles(enhanced_image, circles, cv2.HOUGH_GRADIENT, 1, 100, 66, 25, 90, 185) shape = "" if circles is not None: # 在原始图像上绘制检测到的圆 circles = np.uint16(np.around(circles)) for circle in circles[0, :]: x, y, radius = circle[0], circle[1], circle[2] if abs(x - image.shape[1] // 2) > 100: continue shape = "Circle" cvCircle(image, (x, y), 90, (0, 255, 0), 2) cvCircle(image, (x, y), 2, (0, 0, 255), 3) else: shape = "None" # 判断是否同时出现 Rectangle 和 Triangle以及颜色是否有红,绿 if color == "Red" and shape != "Circle": result = 'r' elif color == "Blue" and shape == "Circle": result = 'b' else: result = 'n' # 打印检测到的形状、颜色 print(f"Result: {result}") #cv2.imshow("enhanced_image", enhanced_image) #cv2.imshow("edges", edges) #cv2.imshow("Image", image) #cv2.waitKey(0) #cv2.destroyAllWindows() if __name__ == "__main__": detect_shape_and_color() ``` 请注意,上述代码中使用了Cython的类型注释来声明变量类型,以提高性能。还添加了Cython所需的C函数声明和转换函数。 在使用Cython之前,确保已按照之前提到的步骤安装了Cython并正确配置了环境。然后,将上述代码保存到一个.pyx文件中,并创建一个适当的setup.py文件来构建和编译Cython代码。 希望这个示例能够帮助你了解如何使用Cython将Python代码转换为C代码。如果有任何问题,请随时提问!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值