PythonGuides-博客中文翻译-十六-

PythonGuides 博客中文翻译(十六)

原文:PythonGuides Blog

协议:CC BY-NC-SA 4.0

Scipy Ndimage Rotate

原文:https://pythonguides.com/scipy-ndimage-rotate/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习“ Scipy ndimage rotate ”,我们将使用服务器参数(如轴、顺序等)以不同的角度旋转图像。并涵盖以下主题。

  • Scipy ndimage rotate
  • Scipy ndimage 旋转顺序
  • Scipy ndimage 移位示例
  • Scipy ndimage 旋转插值旋转顺序
  • 旋转插值旋转轴

另外,查看 Python SciPy 的最新教程: Python Scipy 的数组导数

目录

Scipy ndimage rotate

Python Scipy 有一个模块*scipy.ndimage*来操纵图像或执行图像处理操作,这个模块有几种方法来处理图像处理任务。这里我们将使用其中一种方法*rotate()*来以指定的角度旋转给定的图像。

下面给出了方法*scipy.ndimage.rotate()*的语法。

scipy.ndimage.rotate(input, angle, axes=(1, 0), reshape=True, output=None, mode='constant')

以下是方法roatate()最常用的参数。

  • input(array _ data):就是我们要旋转的输入数组或者图像。
  • 角度(浮点): 用于指定旋转角度,如 20 度或 90 度。
  • 轴(元组中的两个整数): 旋转的平面由两个轴定义。
  • 输出(数据类型或数组): 定义返回数组的数据类型,默认返回数组的数据类型与输入数组相同。
  • 模式: 用于指定***‘constant’, ‘mirror’, ‘wrap’, ‘reflect’, ‘nearest’***的模式。

让我们按照以下步骤通过一个示例来理解:

使用下面的代码导入所需的库,如matplotlibscipy

from matplotlib import image, pyplot
from scipy import ndimage

使用下面的代码从目录或者你的计算机上存在的任何地方加载图像。

img = image.imread('luca_florio.jpg')

这里,模块*image*的函数*imread()*以像素阵列的形式读取图像。

使用模块*pyplot*的功能*imshow()*查看加载的图像,如下所示。

pyplot.imshow(img)

Scipy ndimage rotate example

Scipy ndimage rotate example

让我们使用下面的代码将上面加载的图像旋转到某个角度。

luca_florio_rotate = ndimage.rotate(img,120,mode='constant')

在上面的代码中,我们使用 Python Scipy 的模块*ndimage*的函数*rotate()*来旋转图像。还提供了一些参数,如我们想要旋转的图像 img,120 度的旋转角度,以及模式为*constant*

现在使用下面的代码查看旋转了 120 度的图像。

pyplot.imshow(luca_florio_rotate)

Scipy ndimage rotate

Scipy ndimage rotate

看看上面的输出,看看我们是如何将图像旋转到 120 度的。

阅读: Scipy 卷积器

Scipy ndimage 旋转顺序

在这里,我们将使用相同的方法*rotate()*以指定的角度旋转给定的图像,我们已经在上面的小节中学习过。

下面给出了方法*scipy.ndimage.rotate()*的语法。

scipy.ndimage.rotate(input, angle, axes=(1, 0), reshape=True, output=None, mode='constant')

以下是方法roatate()最常用的参数。

  • input(array _ data):就是我们要旋转的输入数组或者图像。
  • 角度(浮点): 用于指定旋转角度,如 20 度或 90 度。
  • 轴(元组中的两个整数): 旋转的平面由两个轴定义。
  • 输出(数据类型或数组): 定义返回数组的数据类型,默认返回数组的数据类型与输入数组相同。
  • 模式: 用于指定***‘constant’, ‘mirror’, ‘wrap’, ‘reflect’, ‘nearest’***的模式。

让我们按照以下步骤通过一个示例来理解:

使用下面的代码导入所需的库,如matplotlibscipy

from matplotlib import image, pyplot
from scipy import ndimage

使用下面的代码从目录或者你的计算机上存在的任何地方加载图像。

img = image.imread('luca_florio.jpg')

这里,模块*image*的函数*imread()*以像素阵列的形式读取图像。

使用模块*pyplot*的功能*imshow()*查看加载的图像,如下所示。

pyplot.imshow(img)

Scipy ndimage rotate order example

Scipy ndimage rotate order example

使用下面的代码在默认的顺序参数值上旋转图像。

mykhailo_rotate = ndimage.rotate(img,100,mode='constant')
pyplot.imshow(mykhailo_rotate)

通过使用下面的代码将 order 参数值指定为 4,再次旋转同一个图像。

mykhailo_rotate = ndimage.rotate(img,100,mode='constant',order= 4)
pyplot.imshow(mykhailo_rotate)

Scipy ndimage rotate order

Scipy ndimage rotate order

这就是如何通过指定方法*rotate()*的顺序参数来旋转图像。

阅读:科学常数

Scipy n image shift 示例

Python Scipy 子模块*scipy.ndimage*有一个方法*shift()*使用样条插值来移动图像数组。

下面给出了语法。

scipy.ndimage.shift(input, shift, output=None mode='constant')

其中参数为:

  • input(array _ data):就是我们要移位的输入数组或者图像。
  • shift(顺序或浮动): 用于指定图像移动的位置(轴)。
  • 输出(数据类型或数组): 定义返回数组的数据类型,默认返回数组的数据类型与输入数组相同。
  • 模式: 用于指定***‘constant’, ‘mirror’, ‘wrap’, ‘reflect’, ‘nearest’***的模式。

让我们通过以下步骤来了解如何移动图像:

使用下面的代码导入所需的库,如matplotlibscipy

from matplotlib import image, pyplot
from scipy import ndimage

使用下面的代码从目录或者你的计算机上存在的任何地方加载图像。

img = image.imread('thehouse.jpg')
pyplot.imshow(img)

Scipy ndimage shift example

Scipy ndimage shift example

让我们使用方法shift()将图像移动到不同的位置。

thehouse_shift = ndimage.shift(img,(90,90,0),mode='nearest')

在上面的代码中,我们使用 Python Scipy 的模块*ndimage*的函数*shift()*来移动图像。还提供了一些参数,如我们想要移动的图像 img,使用颜色通道移动图像的 x 和 y 位置为(90,90,0),模式为*nearest*

现在使用下面的代码来查看移动后的图像。

pyplot.imshow(thehouse_shift)

Scipy ndimage shift

Scipy ndimage shift

阅读: Scipy 优化–实用指南

Scipy ndimage 旋转插值旋转命令

Python Scipy 在模块*scipy.ndimage.interpolation*中有一个方法*rotate()*,用于以指定的角度旋转图像。它使用样条插值算法旋转图像,样条插值算法有助于调整图像大小或扭曲。

在这里,我们将看到通过改变样条插值的顺序对图像或提供的数组的影响。

下面给出了语法。

scipy.ndimage.interpolation.rotate(input, axes=(1, 0), angle, output=None, reshape=True, order=2, cval=0.0, mode='constant', prefilter=True)

其中参数为:

  • input(array _ data):就是我们要旋转的输入数组或者图像。
  • 角度(浮点): 用于指定旋转角度,如 20 度或 90 度。
  • shape(布尔): 如果为真,则形状根据输入数组进行调整,否则,在为假的情况下它不根据输入数组进行调整。
  • 轴(元组中的两个整数): 旋转的平面由两个轴定义。
  • order(int):用于指定样条插值顺序。
  • 输出(数据类型或数组): 定义返回数组的数据类型,默认返回数组的数据类型与输入数组相同。
  • cval(标量): 如果模式被设置为*constant*,那么这些值被用于所提供的输入数组的外部边界。
  • 模式: 用于指定***‘constant’, ‘mirror’, ‘wrap’, ‘reflect’, ‘nearest’***的模式。

方法*rotate()*返回输入数组旋转后的 ndarray。

在这里,我们将按照以下步骤举例:

使用下面的代码导入所需的库,如matplotlibscipy

from matplotlib import image, pyplot
from scipy import ndimage

使用下面的代码从目录或者你的计算机上存在的任何地方加载图像。

img = image.imread('https://i0.wp.com/pythonguides.com/content/kevin.jpg')

这里,模块*image*的函数*imread()*以像素阵列的形式读取图像。

使用模块*pyplot*的功能*imshow()*查看加载的图像,如下所示。

pyplot.imshow(img)

Scipy ndimage rotate interpolation rotate order example

Scipy ndimage rotate interpolation rotate order example

首先,使用下面的代码,以默认顺序 3 旋转图像。

kevin_rotate_order = rotate(img,60,mode='constant')
pyplot.imshow(kevin_rotate_order)

现在为参数顺序提供一个新值 5,使用下面的代码看看效果。

kevin_rotate_ = rotate(img,60,mode='constant',order=5)
pyplot.imshow(kevin_rotate_)

Scipy ndimage rotate interpolation rotate order

Scipy ndimage rotate interpolation rotate order

查看两幅图像,我们注意到图像的旋转和大小有一点变化。

阅读:科学统计-完整指南

Scipy ndimage 旋转插补旋转轴

在这里,我们将使用模块*scipy.ndimage.interpolation*的 Python Scipy same 方法*rotate()*以指定的角度旋转图像,我们已经在上面的小节中学习过。这里我们将通过改变该方法的轴参数来旋转图像。

使用下面的代码导入所需的库matplotlibscipy

from matplotlib import image, pyplot
from scipy import ndimage

使用下面的代码从目录或者你的计算机上存在的任何地方加载图像。

img = image.imread('https://i0.wp.com/pythonguides.com/content/kevin.jpg')

这里,模块*image*的函数*imread()*以像素阵列的形式读取图像。

使用模块*pyplot*的功能*imshow()*查看加载的图像,如下所示。

pyplot.imshow(img)

Scipy ndimage rotate interpolation rotate axis example

Scipy ndimage rotate interpolation rotate axis example

使用下面的代码,用默认的轴将上面的图像旋转一个角度。

annie_rotate_axis = rotate(img,70,mode='constant')
pyplot.imshow(annie_rotate_axis)

现在,使用下面的代码,通过改变轴来旋转相同的图像到某个角度。

annie_rotate_ = rotate(img,70,mode='constant',axes=(0,1))
pyplot.imshow(annie_rotate_)

Scipy ndimage rotate interpolation rotate axis

Scipy ndimage rotate interpolation rotate axis

这就是如何通过改变轴参数来旋转图像。

另外,看看更多的 Python Scipy 教程。

因此,在本教程中,我们学习了" Scipy ndimage rotate "并涵盖了以下主题。

  • Scipy ndimage rotate
  • Scipy ndimage 旋转顺序
  • Scipy ndimage 移位示例
  • Scipy ndimage 旋转插值旋转顺序
  • 旋转插值旋转轴

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

科学正态分布

原文:https://pythonguides.com/scipy-normal-distribution/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习“科学正态分布”,我们还将借助一些例子讨论以下主题。

  • 科学正态分布
  • 科学正态分布 PDF
  • 带均值和标准差的正态分布
  • 科学正态分布图
  • 科学正态分布检验
  • 多元正态分布
  • 截断正态分布
  • Scipy 对数-正态分布
  • 扭曲正态分布
  • 逆正态分布
  • 科学拟合正态分布
  • 半正态分布
  • 强正态分布分位数
  • 正态分布计算概率

目录

Scipy 正态分布

Python Scipy 库有一个模块*scipy.stats*包含一个对象*norm*生成各种正态分布如 CDF、PDF 等。正态分布是一种测量平均值周围数据分布的方法。

它是对称的,一半数据以对称的方式位于平均值的左侧,另一半位于平均值的右侧。正态分布的其他名称有*Bell Curve**Gaussian Distribution*

在 Python Scipy 中,它有两个重要的参数*loc*用于表示平均值,而*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.norm.method_name(data,loc,size,moments,scale)

其中参数为:

  • 数据: 以数组数据的形式表示均匀采样数据的一组点或值。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.norm()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . norm . CDF():它用于累计分布函数。
  • scipy . stats . norm . pdf():它用于概率密度函数。
  • scipy . stats . norm . RVs():获取随机变量。
  • scipy . stats . norm . stats():用于得到标准差、均值、峰度、偏斜度。
  • scipy . stats . norm . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . norm . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . norm . SF():它用于获取生存函数的值。
  • scipy . stats . norm . ISF():它用来得到逆生存函数的值。
  • scipy . stats . norm . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . norm . mean():用于求正态分布相关的均值。
  • scipy . stats . norm . median():用于求正态分布相关的中位数。
  • scipy . stats . norm . var():用于求与分布相关的方差。
  • scipy . stats . norm . STD():它用于求与分布相关的标准差

另外,检查: Scipy Ndimage Rotate

Scipy 正态分布 PDF

正如我们在上面的 Python Scipy 小节中了解到的,对象norm有许多方法,如 CDF、PDF、ISF 等,来生成不同种类的正态分布。这里我们将使用*scipy.stats.norm.pdf()*中的一种方法来计算给定分布的 Probability Density Funtion

下面给出了语法。

scipy.stats.norm.pdf(data,loc,scale)

其中参数为:

  • 数据: 以数组数据的形式表示均匀采样数据的一组点或值。
  • loc: 用于指定平均值,默认为 0。
  • 刻度: 用于指定标准差,默认为 1。

让我们通过以下步骤来举例说明如何计算给定分布的 pdf:

使用下面的 python 代码导入所需的库。

import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
%matplotlib inline

使用下面的代码创建一个数组,包含-5 到 5 之间的值,差值为 0.3。

x_array = np.arange(-5, 5, 0.3)
x_array

使用以下代码,通过将创建的数据数组提供给参数值为 loc = 0 且 scale = 1 的方法norm.pdf()来计算 pdf。

y_pdf = norm.pdf(x_array,0,1)

现在使用下面的代码绘制分布图。

plt.plot(x_array, y_pdf) 
plt.show()

Scipy Normal Distribution PDF

Scipy Normal Distribution PDF

这就是如何生成正态分布的 pdf。

阅读: Scipy 卷积-完整指南

带均值和标准差的正态分布

Python Scipy 对象*norm*有两个重要的参数locscale,用于控制正态分布的位置和形状的所有方法。其中*loc*代表用于改变分配的*mean*,而*scale*是用于改变分配形状的*standard deviation*

这里,我们将使用我们在上述小节中使用的相同示例,并调整参数*loc**scale*,以查看分布的位置和形状如何变化。

使用下面的 python 代码导入所需的库。

import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
%matplotlib inline

使用下面的代码创建一个数组,包含-5 到 5 之间的值,差值为 0.3。

x_array = np.arange(-5, 5, 0.3)
x_array

使用以下代码,通过将创建的数据数组提供给参数值为 loc = 0 且 scale = 1 的方法norm.pdf()来计算 pdf。

y_pdf = norm.pdf(x_array,0,1)
plt.plot(x_array, y_pdf) 
plt.show()

Scipy Normal Distribution With Mean And Standard Deviation example

Scipy Normal Distribution With Mean And Standard Deviation example

更改 loc = 1 和 scale =1,并绘制分布图。

y_pdf = norm.pdf(x_array,1,1)
plt.plot(x_array, y_pdf) 
plt.show()

在上面的代码中,loc =1 是均值,它使分布向均值移动,但分布的形状保持不变。输出如下所示。

Scipy Normal Distribution With Mean And Standard Deviation tutorial

Scipy Normal Distribution With Mean And Standard Deviation tutorial

再次保持 loc = 0,改变 scale = 2,绘制分布图。

y_pdf = norm.pdf(x_array,0,2)
plt.plot(x_array, y_pdf) 
plt.show()

在上面的代码中,改变 scale =2,这是改变分布形状的标准偏差,如下面的输出所示。

Scipy Normal Distribution With Mean And Standard Deviation

Scipy Normal Distribution With Mean And Standard Deviation

这就是如何使用均值和标准差来改变分布的位置和形状。

阅读: Scipy 信号-有用教程

Scipy 正态分布图

在本 Python Scipy 部分,我们将通过以下步骤学习如何绘制正态分布图:

使用下面的 python 代码导入所需的库。

from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

使用下面的代码生成范围为-15 到 15 的数据数组,差值为 0.03。

x_array = np.arange(-15, 15, 0.03)

使用下面的代码计算生成的数据数组的平均值和标准偏差。

x_array_mean = np.mean(x_array)
x_array_std = np.std(x_array)
print("Mean of sample",x_array_mean)
print("Standard Deviaton of sample",x_array_std)

使用下面的代码计算正态分布的 PDF。

y_pdf_data = stats.norm.pdf(x_array,x_array_mean,x_array_std)

使用下面的代码绘制分布图。

plt.plot(x_array,y_pdf_data)
plt.show()

Scipy Normal Distribution Plot

Scipy Normal Distribution Plot

这就是如何使用库 matplotlib 绘制正态分布图。

Scipy 正态分布检验

Python Scipy 在模块*scipy.stats*中有一个方法*normaltest()*来确定样本是否偏离正态分布。

下面给出了语法。

scipy.stats.normaltest(a, axis=1, nan_policy='omit')

其中参数为:

  • a(array_data): 它是我们要测试的作为样本的数据的数组。
  • 轴(int): 用于指定在哪个轴上计算测试。默认情况下,它是 0。
  • nan_ploicy: 用于处理数组内存在的 nan 值。它有一些以不同方式处理 nan 值的参数,这些参数是*omit**propagate**raise*

方法*normaltest()*返回两个值作为统计数据和数组或浮点类型的 p 值。

让我们以一个示例为例,按照以下步骤测试该示例:

使用下面的 python 代码导入所需的库。

from scipy.stats import normaltest
import numpy as np

使用下面的代码创建一个随机数生成器,并在生成器的帮助下生成正常的数组数据。

rand_numgen = np.random.default_rng()
points = 1000
a_data = rng.normal(1, 2, size=points)
b_data = rng.normal(3, 2, size=points)

使用下面的代码将这两个数据组合成一个数据数组。

norm_array_data = np.concatenate((a_data,b_data))
norm_array_data

使用下面的代码对作为样本的数据数组执行常规测试。

z_score_stat, p_value = normaltest(norm_array_data)
print("Z-score statistic",z_score_stat)
print("p-value",p_value)

Scipy Normal Distribution Test

Scipy Normal Distribution Test

从输出中,我们可以看到 p 值大于 0.5,这意味着样本不符合正态分布。

这就是如何使用 Python Scipy 库检查样本的正态性。

阅读: Scipy Integrate +示例

Scipy 多元正态分布

Python Scipy 库有一个模块*scipy.stats*,它包含一个对象*multivariate_normal*,该对象生成一些多元正态分布,如 CDF、PDF 等。

它有两个重要参数*mean*来指定平均值,还有*cov*是协方差矩阵。

下面给出了语法。

scipy.stats.multivariate_normal.method_name(x,mean,cov,allow_singular,random_state)

其中参数为:

  • x(array_data): 用于指定分位数。
  • 均值(array_data): 提供分布的均值,默认为零。
  • cov(array_data): 提供分布的协方差矩阵。
  • allow _ singular(boolean):是否允许协方差矩阵出现奇异,默认情况下为 false。
  • 【random _ state(int,None): 指定数据再现性的种子。

以上参数是对象*scipy.stats.multivariate_normal()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . multivarial _ normal。:【CDF()】T3 它用于累积分布函数。
  • scipy . stats . multivarial _ normal。PDF(): 它用于概率密度函数。
  • scipy . stats . multivariate _ normal . RVs():从多元正态分布中获取随机变量。
  • scipy . stats . multivariate _ normal . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . multivariate _ normal . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . multivariate _ normal . entropy():求多元正态分布的微分熵。

让我们以下面的步骤为例:

使用下面的 python 代码导入所需的库。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

使用下面的代码生成 x_data。

x_data = np.linspace(0,6,20,endpoint=False)
x_data 

使用以下代码计算均值= 2.6 且协方差= 0.4 的多元正态分布的 PDF。

y_data =stats.multivariate_normal.pdf(x_data, mean=2.6, cov=0.4)
y_data

使用以下代码绘制多元正态分布图。

plt.plot(x_data,y_data)
plt.show()

Multivariate Normal Distribution Scipy

Multivariate Normal Distribution Scipy

阅读: Scipy 旋转图像+示例

Scipy 截尾正态分布

Python Scipy 库有一个模块*scipy.stats*,它包含一个对象*truncnorm*,该对象生成某种范围内的各种截断正态分布,如 CDF、PDF 等。

在 Python Scipy 中,它有两个重要的参数*loc*用于表示平均值,而*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.truncnorm.method_name(x,a,b,loc,size,moments,scale)

其中参数为:

  • **x:**它用来定义分位数。
  • **a、b:** 它用来定义一个范围。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.norm()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . truncnorm . CDF():用于累计分布函数。
  • scipy . stats . truncnorm . pdf():用于概率密度函数。
  • scipy . stats . truncnorm . RVs():获取随机变量。
  • scipy . stats . truncnorm . stats():用于获取标准差、均值、峰度、偏斜度。
  • scipy . stats . truncnorm . log pdf():用于获取概率密度函数相关的日志。
  • scipy . stats . truncnorm . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . truncnorm . SF():它用于获取生存函数的值。
  • scipy . stats . truncnorm . ISF():它用于获取逆生存函数的值。
  • scipy . stats . truncnorm . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . truncnorm . mean():用于求正态分布相关的均值。
  • scipy . stats . truncnorm . median():用于寻找与 truncnormal 分布相关的中位数。
  • scipy . stats . truncnorm . var():用于求与分布相关的方差。
  • scipy . stats . truncnorm . STD():用于求分布相关的标准差

让我们以下面的步骤为例:

使用下面的 python 代码导入所需的库。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

使用下面的代码创建一个正态分布的截断范围。

range_a, range_b = 0.2,3

使用下面的代码创建一个数据数组。

fig, ax = plt.subplots(1, 1)
array_data = np.linspace(stats.truncnorm.ppf(0.02,range_a,range_b),
                stats.truncnorm.ppf(0.98,range_a,range_b), 99)

使用一组数据和范围执行 truncnorm 的 pdf,使用下面的代码得到截断的正态分布。

ax.plot(array_data, stats.truncnorm.pdf(array_data,range_a,range_b),
       'r-', lw=5, alpha=0.6, label='truncnorm pdf')

Scipy Truncated Normal Distribution

Scipy Truncated Normal Distribution

这就是如何使用方法*truncnorm()*得到截尾正态分布。

阅读:Scipy Sparse–有用的教程

Scipy 对数正态分布

*Lognormal*代表正态分布形式的对数。它是一个对数正态连续的随机变量。

下面给出了语法。

scipy.stats.lognorm.method_name(data,loc,size,moments,scale)

其中参数为:

  • 数据: 以数组数据的形式表示均匀采样数据的一组点或值。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.lognorm()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . log norm . CDF():用于累计分布函数。
  • scipy . stats . log norm . pdf():用于概率密度函数。
  • scipy . stats . log norm . RVs():获取随机变量。
  • scipy . stats . log norm . stats():用于得到标准差、均值、峰度、偏斜度。
  • scipy . stats . log norm . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . log norm . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . log norm . SF():它用于获取生存函数的值。
  • scipy . stats . log norm . ISF():它用于获取逆生存函数的值。
  • scipy . stats . log norm . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . log norm . mean():用于求分布的均值。
  • scipy . stats . log norm . median():用于求分布的中位数。
  • scipy . stats . log norm . var():用于求与分布相关的方差。
  • scipy . stats . log norm . STD():用于求分布相关的标准差

让我们以下面的步骤为例:

使用下面的 python 代码导入所需的库。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

使用以下代码创建对数正态分布的形状参数。

s_parameter = 0.999

使用下面的代码创建一个数据数组。

fig, ax = plt.subplots(1, 1)
array_data = np.linspace(stats.lognorm.ppf(0.02,s_parameter),
                stats.lognorm.ppf(0.98,s_parameter), 99)

通过使用下面的代码将带有形状参数的数据数组传递给方法*lognorm()*来生成对数正态分布

ax.plot(array_data, stats.lognorm.pdf(array_data,s_parameter),
       'r-', lw=5, alpha=0.6, label='truncnorm pdf')

Scipy Log Normal Distribution

Scipy Log-Normal Distribution

这就是如何使用方法*lognorm()*创建对数正态分布。

阅读: Scipy 优化–实用指南

Scipy 偏斜正态分布

Python Scipy 在模块*scipy.stats*中有一个方法*skewnorm()*,该方法使用一个名为*skewness*的附加参数将正态分布的形状更改为正态左斜和正态右斜分布,该参数用字母*a*表示。

下面给出了语法。

scipy.stats.truncnorm.method_name(x,a,loc,moments,scale)

其中参数为:

**x:**它用来定义分位数。
**答:** 它用来定义分布的一个偏度参数。
loc: 用来指定平均值,默认为 0。
矩: 用于计算标准差、峰度、均值等统计量。
标度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.skewnorm()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . skewnorm . CDF():用于累计分布函数。
  • scipy . stats . skewnorm . pdf():用于概率密度函数。
  • scipy . stats . skewnorm . RVs():获取随机变量。
  • scipy . stats . skewnorm . stats():用于获取标准差、均值、峰度、偏斜度。
  • scipy . stats . skewnorm . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . skewnorm . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . skewnorm . SF():它用于获取生存函数的值。
  • scipy . stats . skewnorm . ISF():它用于获取逆生存函数的值。
  • scipy . stats . skewnorm . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . skewnorm . mean():用于求分布的均值。
  • scipy . stats . skewnorm . median():用于求分布的中位数。
  • scipy . stats . skewnorm . var():用于求与分布相关的方差。
  • scipy . stats . skewnorm . STD():用于求分布相关的标准差

让我们以下面的步骤为例:

使用下面的 python 代码导入所需的库。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

使用以下代码创建对数正态分布的形状参数。

skewness_parameter = 5

使用下面的代码创建一个数据数组。

fig, ax = plt.subplots(1, 1)
array_data = np.linspace(stats.skewnorm.ppf(0.02,skewness_parameter),
                stats.skewnorm.ppf(0.98,skewness_parameter), 99)

通过使用下面的代码将带有偏斜度参数的数据数组传递给方法*skewnorm()*来生成对数正态分布

ax.plot(array_data, stats.skewnorm.pdf(array_data,skewness_parameter),
       'r-', lw=5, alpha=0.6, label='skewnorm pdf')

Scipy Skew Normal Distribution

Scipy Skew Normal Distribution

这就是如何用方法*skewnorm()*使正态分布左偏或右偏——正态分布。

阅读: Scipy 常量–多个示例

Scipy 逆正态分布

在 Python Scipy 中,模块*scipy.stats*中有一个对象*norminvgauss*用于计算逆正态分布或正态逆高斯分布。它有不同的方法,如 PDF,CDF 等来生成这种逆正态分布。

下面给出了语法。

scipy.stats.norminvgauss.method_name(x,a,b,loc,size,moments,scale)

其中参数为:

**x:**它用来定义分位数。
**a、b:** 它用于定义一个尾部重量和不对称参数。
loc: 用来指定平均值,默认为 0。
矩: 用于计算标准差、峰度、均值等统计量。
标度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.norminvegauss()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . norminvgauss . CDF():它用于累计分布函数。
  • scipy . stats . norminvgauss . pdf():它用于概率密度函数。
  • scipy . stats . norminvgauss . RVs():获取随机变量。
  • scipy . stats . norminvgauss . stats():用于获取标准差、均值、峰度、偏斜度。
  • scipy . stats . norminvgauss . log pdf():用于获取概率密度函数相关的日志。
  • scipy . stats . norminvgauss . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . norminvgauss . SF():它用于获取生存函数的值。
  • scipy . stats . norminvgauss . ISF():它用于获取逆生存函数的值。
  • scipy . stats . norminvgauss . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . norminvgauss . mean():它用于求分布的均值。
  • scipy . stats . norminvgauss . median():用于求分布的中位数。
  • scipy . stats . norminvgauss . var():用于求与分布相关的方差。
  • scipy . stats . norminvgauss . STD():用于求与分布相关的标准差

让我们以下面的步骤为例:

使用下面的 python 代码导入所需的库。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

使用以下代码定义逆正态分布的尾部重量和不对称参数。

param_a, param_b = 1.15,0.6

使用下面的代码创建一个数据数组。

fig, ax = plt.subplots(1, 1)
array_data = np.linspace(stats.norminvgauss.ppf(0.02,param_a,param_b),
                stats.norminvgauss.ppf(0.98,param_a,param_b), 99)

用一组数据和范围执行 norminvgauss 的 pdf,使用下面的代码得到正态分布的逆。

ax.plot(array_data, stats.norminvgauss.pdf(array_data,param_a,param_b),
       'r-', lw=5, alpha=0.6, label='norminvgauss pdf')

Scipy Inverse Normal Distribution

Scipy Inverse Normal Distribution

这就是如何使用方法*norminvgauss()*生成逆正态分布。

阅读:Scipy Stats Zscore+Examples

拟合正态分布

在这一 Python Scipy 部分,我们将通过手动创建数据和函数来使数据符合正态分布。按照以下步骤将数据拟合到正态分布。

首先,使用下面的 python 代码导入所需的库。

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

使用创建数据,并使用下面的代码将其转换为 NumPy 数组。

data_x = [ -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
data_y = [1.2, 4.2, 6.7, 8.3, 10.6, 11.7, 13.5, 14.5, 15.7, 16.1, 16.6, 16.0, 15.4, 14.4, 14.2, 12.7, 10.3, 8.6, 6.1, 3.9, 2.1]

data_x = np.asarray(data_x)
data_y = np.asarray(data_y)
plt.plot(data_x, data_y, 'o')

Scipy Fit Normal Distribution example

Scipy Fit Normal Distribution example

使用创建一个普通函数,并使用下面的代码将函数和数据传递给方法*curve_fit()*

def norm_dist(data, param_A, param_B):
    y_data = param_A*np.exp(-1*param_B*data**2)
    return y_data
paramet, cov = curve_fit(norm_dist, data_x, data_y)

A_fit = paramet[0]
B_fit = paramet[1]

使用下面的代码将拟合的数据绘制成正态分布。

y_fit = norm_dist(data_x, A_fit, B_fit)
plt.plot(data_x, data_y, 'o', label='data')
plt.plot(data_x, y_fit, '-', label='fit')
plt.legend()

Scipy Fit Normal Distribution

Scipy Fit Normal Distribution

这就是如何使用创建的数据和函数使数据符合正态分布。

阅读: Scipy 寻找峰值–有用教程

半正态分布

*scipy.stats.halfnorm*表示半正态连续的随机变量。它有不同种类的功能来生成半正态分布,如 CDF,PDF,中位数等。半正态分布是截尾正态或折叠正态分布。

它有两个重要的参数*loc*用于表示平均值和*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.halfnorm.method_name(data,loc,size,moments,scale)

其中参数为:

  • 数据: 以数组数据的形式表示均匀采样数据的一组点或值。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.halfnorm()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . half norm . CDF():用于累计分布函数。
  • scipy . stats . half norm . pdf():用于概率密度函数。
  • scipy . stats . half norm . RVs():获取随机变量。
  • scipy . stats . half norm . stats():用于得到标准差、均值、峰度、偏斜度。
  • scipy . stats . half norm . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . half norm . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . half norm . SF():它用于获取生存函数的值。
  • scipy . stats . half norm . ISF():它用于获取逆生存函数的值。
  • scipy . stats . half norm . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . half norm . mean():用于求正态分布相关的均值。
  • scipy . stats . half norm . median():用于求正态分布相关的中位数。
  • scipy . stats . half norm . var():用于求与分布相关的方差。
  • scipy . stats . half norm . STD():用于求分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

创建观察数据值,并用*mean = 0**standard deviation = 1*从这些数据值中计算出*probability density function*

observatin_x = np.linspace(-2,2,200)
PDF_norm = stats.norm.pdf(observatin_x,loc=0,scale=1)

使用下面的代码绘制创建的分布图。

plt.plot(observatin_x,PDF_norm)
plt.xlabel('x-values')
plt.ylabel('PDF_norm_values')
plt.title("Probability density funciton of half normal distribution")
plt.show()

Scipy Half Normal Distribution

Scipy Half Normal Distribution

这就是如何使用方法*halfnorm()*创建半正态分布。

阅读:Scipy Linalg–实用指南

Scipy 正态分布计算概率

我们已经从上面的小节中学习了如何创建正态分布,现在我们将使用 Python Scipy 模块的*scipy.stats.norm*来计算正态分布的概率。

按照以下步骤计算正态分布的概率:

使用下面的代码导入所需的库。

from scipy.stats import norm

现在,通过使用下面的代码向方法*norm()*提供平均值和标准偏差值来计算正态分布的概率。

norm(0,1).pdf(20)

norm(2,2).pdf(50)

norm(10,20).pdf(10)

Scipy Normal Distribution Calculate Probability

Scipy Normal Distribution Calculate Probability

查看输出,方法*norm()*使用函数 pdf 生成不同值的概率。

另外,看看更多的 SciPy 教程。

在本教程中,我们学习了“ Scipy 正态分布”并涵盖了以下主题。

  • 科学正态分布
  • 科学正态分布 PDF
  • 带均值和标准差的正态分布
  • 科学正态分布图
  • 科学正态分布检验
  • 多元正态分布
  • 截断正态分布
  • Scipy 对数-正态分布
  • 扭曲正态分布
  • 逆正态分布
  • 科学拟合正态分布
  • 半正态分布
  • 强正态分布分位数
  • 正态分布计算概率

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Scipy 优化–有用的指南

原文:https://pythonguides.com/scipy-optimize/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习“ Scipy 优化”,在这里我们将实现不同的优化算法来获得函数的最优值。此外,涵盖以下主题。

  • 科学优化
  • Scipy 优化最小化示例
  • Scipy 优化最小化
  • Scipy 优化曲线拟合
  • 优化最小二乘法
  • 科学优化 Fmin
  • Scipy 优化约束
  • 科学优化界限
  • Scipy 优化最小化约束示例

目录

Scipy 优化

Scipy Optimize *(scipy.optimize)*是 Scipy 的一个子包,包含不同种类的方法来优化各种函数。

这些不同种类的方法是根据我们正在处理的问题的种类来区分的,例如线性规划、最小二乘法、曲线拟合和求根。下面根据类别提供了方法列表。

优化:

优化进一步分为三种优化:

标量函数优化: 它包含方法*minimize_scalar( )*来最小化包含一个变量的标量函数。

多元优化: 它包含的方法*minimize( )*是最小化包含多个变量的标量函数。

全局优化: 它包含基于不同算法或优化技术的不同方法,如下所示。

  • 它使用跳盆算法来寻找给定函数的全局最小值。
  • ***brute( ):***它使用蛮力方法在指定范围内最小化给定函数。
  • 它有助于找到给定多元函数的全局最小值。
  • ***dual_annealing( ):***使用双重退火算法寻找给定函数的全局最小值。

曲线拟合:

它的方法*curve_fit( )*使用非线性最小二乘法来拟合一组数据的函数。

最小二乘法:

它被分成两个最小的正方形。

非线性最小二乘: 它有一个方法*least_squares( )*解决给定变量上界的非线性最小二乘问题。

线性最小二乘: 它包含了*nnls( )**lsq_linear( )*的方法来解决给定变量上界的线性最小二乘问题。

求根:

它用不同的方法来寻找给定函数的零点或根,它根据函数进一步分为两类。

标量函数: 在众多寻找给定标量函数零点的方法中,它有最流行的方法*root_scalar( )*

多维: 它只有一个方法就是*root( )*求给定向量函数的零点或根。

线性规划:

它使用方法*lingprog( )*来最小化具有给定约束(例如等式和不等式)的线性目标函数。

阅读:Python 中的 Scikit 学的是什么

Scipy 优化最小化

有两个优化函数*minimize( )**minimize_scalar( )*来最小化一个函数。

*minimize_scalar( )*该函数用于最小化包含一个变量的标量函数。下面给出了如何访问和使用子程序包*scipy.optimize*中的功能的语法。

scipy.optimize.minimize_scalar(function,method='brent', bracket=None, bounds=None, args=(), tol=None, options=None)

其中参数为:

  • 函数: 为最小化传递的目标函数。
  • 方法: 是将用于给定目标函数的一种求解器或方法。方法有*Brent**Bounded**Golden**Custom*
  • 括号: 仅描述*Brent**Golden*方法的括号间隔。
  • bounds: 是包含两个值的绑定,在使用 bound 方法时是必需的。
  • args: 是提供给目标函数的附加自变量。
  • tol: 是对终止的容忍。
  • 选项: 用于定义使用*maxiter*执行的最大迭代次数。

*minimize( )*该函数用于最小化包含多个变量的标量函数。下面给出了如何访问和使用子程序包*scipy.optimize*中的功能的语法。

scipy.optimize.minimize(function, x0, args=(), method=None, jac=None, hess=None, bounds=None, constraints=(), tol=None, options=None)

参数在哪里。

  • 函数: 传递给最小化的目标函数。
    方法: 是将用于给定目标函数的一种求解器或方法。方法有 信任——克雷洛夫 ***Nelder-Mead, CG, *Powell*, BFGS, L-BFGS-B, TNC, COBYLA,***trust-exact, Newton-CG,** `***SLSQP, dogleg, `*trust-ncg****,``***trust-constr,***
  • jac: 是计算梯度向量的方法。
  • 赫斯: 它用来计算赫斯矩阵。
    界限: 包含两个值的界限,在使用 Nelder-Mead、TNC、SLSQP、L-BFGS-B、Powell 和 trust-constr 方法时需要。
  • 约束: 它采用等式约束和不等式约束这样的目标函数的约束。
  • tol: 是对终止的容忍。
  • 选项: 用于定义使用选项*maxiter*执行的最大迭代次数。

阅读:使用 Python 的机器学习

Scipy 优化最小化示例

这里我们将看到两个最小化函数的例子,我们已经在上面的“Scipy 优化最小化” 小节中学习过。

在做一个例子之前,让我们先了解一下“什么是标量函数”标量函数接受一个值并输出这个值。

这里我们要用的标量函数是一个二次函数 2x²+5x-4 ,所以这里我们会找到目标函数***2x²+5x-4***的最小值。该函数的图形如下所示。

Scipy Optimize Minimize example

Scipy Optimize Minimize example

看一下函数***2x²+5x-4***的图形,这里我们将使用*scipy.optimize*子包的方法*minimize_scalar()*找到一个函数的最小值。

首先使用下面的代码导入 Scipy optimize 子包。

import scipy.optimize as ot

使用下面的代码定义我们要最小化的*Objective function*

def Objective_Fun(x):

    return 2*x**2+5*x-4

再次从子包 optimize 中导入方法*minimize_scalar( )*,并将创建的*Objective function*传递给该函数。

result = ot.minimize_scalar(Objective_Fun)

使用以下代码检查结果*Objective function*的最小值。

print(result)

Scipy Optimize Minimize minimize_scalar

Scipy Optimize Minimize minimize_scalar

上面输出中显示的***x: -1.25****Objective function*的最小值。这个最小值可能不是真的,但这是找到*Objective function*最小值的方法。

我们已经介绍了唯一可以处理包含单个变量的函数的方法*minimize_scalar( )*。但是会发生什么呢,如果我们有一个不止一个变量的函数,在那种情况下,方法*minimize( )*被用来寻找*Objective function*的最小值。

*minimize( )*也可以处理*Objective function*上的约束。下面给出了三种类型的约束。

  • 界限约束: 暗示 x 的值位于上下限之间。
  • 线性约束: 通过对给定的用户输入数组执行 x 值的内积,并将结果与一个下限和上限进行比较,来限制解决方案。
  • 非线性约束: 通过将用户给定的函数应用于 x 值,并将结果与一个上下限进行比较,来限制解。

这里我们要举一个例子来说明*minimize( )*如何计算给定*Objective function* : ***60x²+15x***带约束的最小值。该函数的图形如下所示。

Scipy Optimize Minimize tutorial

Scipy Optimize Minimize tutorial

下面给出了我们将使用 Scipy 解决的问题。

Objective Function: 60x²+15x

Constraints:
           8x+16x ≥ 200
           60x+40x ≥ 960
           2x+2x ≥ 40
           x ≥ 0

首先,使用下面的代码在 python 中创建一个*Objective function*

def Obj_func(x):
    return (60*x[0]**2) + (15*x[1])

然后使用下面的代码在 python 中定义约束。

const = ({'type': 'ineq', 'fun': lambda x:  8*x + 16*x-200},
        {'type': 'ineq', 'fun': lambda x: 60*x + 40*x-960},
        {'type': 'ineq', 'fun': lambda x: 2*x + 2*x-40})

定义最优值所在的函数的边界。

bnds = ((0, None), (0, None))

从子包scipy.optimize中访问方法*minimize( )*,并使用下面的代码将创建的*Objective function*传递给带有约束和绑定的方法。

res = minimize(Obj_func, (-1, 0), method='SLSQP', bounds=bnds,
               constraints=const)

检查结果的最小值***``*Objective function*``***

print(res)

Scipy Optimize Minimize minimize method

Scipy Optimize Minimize minimize method

上面输出中显示的***x: [10.,10.]****Objective function*的最小值。

阅读:蟒蛇皮里的熊猫

Scipy 优化曲线拟合

在 Scipy 中,子程序包*scipy.optimize*有方法*curve_fit( )*,该方法将直线拟合到给定的一组点。

下面给出了该方法的语法。

scipy.optimize.curve_fit(fun, x_data, y_data, p_0=None, check_finite=True, bounds=(- inf, inf), method=None)

其中参数为:

  • 好玩: 它是模型功能。
  • x_data: 是数组形式的数据点或任何对象,也是自变量。
  • y_data: 用函数(x_data)构造数据点或任何对象的是因变量这个函数可以 sin,cos 等。
  • P0:为方法中参数的起始猜测值。
  • check_finite: 用于检查数组中是否包含 nans 值,如果包含则抛出 ValueError。默认情况下,它被设置为 True。
  • 界限: 定义了参数的上下限。
  • 方法: 用于指定优化问题的算法,如最小二乘法有 trflm 等。

要了解更多关于曲线拟合的知识,请跟随官方文档“Scipy 曲线拟合”

遵循以下步骤,使用方法*curve_fit( )*拟合一个函数来生成数据。

按照下面的步骤,确保您了解下面给出的主题。

使用下面的代码导入必要的库。

# Importing libraries
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt

首先,使用下面的代码生成一些随机数据。

# Generating random data points in a varaible x and y and plotting it.
np.random.seed(0)

x = np.linspace(-6, 6, num=60)
y = 5.2 * np.sin(1.0 * x) + np.random.normal(size=60)

#plot the genreated data points

plt.figure(figsize=(6, 4))
plt.scatter(x, y)

Scipy Optimize Curve Fit example

Scipy Optimize Curve Fit example

看看上面的输出,以及生成的数据是什么样子的。

创建一个新函数*sin_func*并将此函数传递给方法curve_fit( )*sin_func*,使用下面的代码生成数据。

# crating the sin function and fitting this to gnerated data using
#curve_fit method

def sin_func(X, a, b):
    return a * np.sin(b * X)

param, param_covariance = opt.curve_fit(sin_func, x, y,
                                               p0=[1, 1])

print(param)

让我们用下面的代码画出符合生成数据的函数。

# Plotting the fitted line to genreated data
plt.figure(figsize=(6, 4))
plt.scatter(x, y, label='Data')
plt.plot(x, test_func(x, param[0], param[1]),
         label='Fitted Sin function')

plt.legend(loc='best')

plt.show()

Scipy Optimize Curve Fit tutorial

Scipy Optimize Curve Fit tutorial

阅读:Scipy Sparse–有用的教程

Scipy 优化 Fmin

*scipy.optimize* a 函数包含一个方法*Fmin( )*,该方法使用 下坡单纯形算法 来最小化给定的函数。

下面给出了该方法的语法。

scipy.optimize.fmin(fun, x_0, args=(), max_iter=None, max_fun=None, disp=1, retall=0, initial_simplex=None)

其中参数为:

  • 乐趣: 它是我们要最小化的目标函数。
  • x_0: 提供给一个方法用于异议函数的猜测点。
  • max_iter: 要做的最大迭代次数。
  • max_fun: 用于设置要做的最大评估次数。
  • disp: 显示收敛消息,然后将其设置为 True。
  • retall: 显示每次迭代的解,然后设置为 True
  • intial_simplex: 如果我们提供初始单纯形,那么它不使用我们提供的 x_0,而是使用 intail_simples 猜测。

让我们以下面的步骤为例:

使用下面的代码将模块*scipy.optimize*作为*opt*导入。

import scipy.optimize as opt

使用下面的代码在 python 中定义一个新函数***y²***

def function(y):
    return y**2

从模块*scipy.optimize*中访问方法*fmin( )*,用初始猜测值作为*1*传递创建的函数。

min = opt.fmin(function, 1)

使用下面的代码检查该值。

print(min)

Scipy Optimize Fmin

Scipy Optimize Fmin

根据输出,执行 17 次迭代,函数被评估 34 次,最小值为***[-8.8817842e-16]***

阅读:科学统计-完整指南

Scipy 优化最小二乘法

scipy.optimize子包中,有*nnls( )**lsq_linear( )*两种方法处理最小二乘相关问题。

第一个*nnls( )*非负线性平方 在约束最小二乘问题中不允许负系数。

下面给出了语法*nnls( )*

scipy.optimize.nnls(A, b, max_iter=None)

其中参数为:

  • 答: 是 n 数组数据或者矩阵。
  • b: 它是一个向量形式的响应变量(一列)。
  • max_iter: 执行的最大迭代次数。

上面的方法旨在找到***argmin_x || Ax - b ||_2***,其中***x ≥ 0***意味着所提供的向量的分量必须是非负的。*nnls( )*以类似 ndarray 的向量形式返回结果,剩余值为浮点类型。

让我们以下面的步骤创建一个矩阵和一个向量为例:

导入模块*scipy.optimize*以访问方法*nnls( )*numpy ,使用以下代码创建类似矩阵或向量的数组。

# Importing the module scipy.optimize and numpy
import scipy.optimize as opt
import numpy as np

使用 NumPy 的函数*array*用下面的代码创建一个*matrix B*和一个*vector c*

# creating the matrix B and a vector c
B = np.array([[2, 1], [2, 1], [1, 2]])
c = np.array([3, 2, 2])

scipy.optimize中访问*nnls( )*方法,并将上面创建的带有*vector c**matrix B*传递给它。

# access the method nnls(), passing the matrix B and a vector c to it.
opt.nnls(B, c)

Scipy Optimize Least Squares nnls

Scipy Optimize Least Squares nnls

输出显示包含值***[1\. , 0.5]***的 ndarray 或解向量,残差为浮点类型*0.707106781186547*

第二种方法是*lsq_linear( )*,它解决了与变量有边界的非线性正方形相关的问题。

下面给出了语法***``*lsq_linear( )*``***

scipy.optimize.lsq_linear(A, b, bounds=(- inf, inf), method='trf', lsmr_tol=None, max_iter=None, verbose=0)

其中参数为:

  • 答: 是 n 数组数据或者矩阵。
  • b: 它是一个向量形式的响应变量(一列)。
  • 界限: 是自变量上的界限(上下界)。
  • 方法:用于指定使用哪种方法进行最小化,如 TRF(信赖域反射)和 bvls(有界变量最小二乘)算法。
  • lsmr_tol:默认设置为 1e-2 * tol 的公差参数。此外,它可以使用自动选项自动调整公差。
  • max_iter:终止前要执行的最大迭代次数。
  • verbose:用于定义算法的详细级别,比如指定 1 表示静默工作,2 表示显示终止信息,3 表示显示迭代过程中的信息。

*lsq_linear( )*返回结果作为 ndarray 中的 解, 浮点型中的代价函数值ndarray 中的残差向量*** , 【迭代次数】, 等。***

让我们以下面的步骤为例。

*scipy.optimize*导入必要的模块*rand**numpy*和方法*lsq_linear( )*

from scipy.sparse import rand
import numpy as np
from scipy.optimize import lsq_linear

创建随机数生成器为*rng*和两个变量*l**m*,值为*3000**2000*

rng = np.random.default_rng()
l = 30000
m = 20000

使用模块*scipy.sparse*的函数rand创建 稀疏矩阵 B ,使用函数*standard_normal*创建 目标向量 c

B = rand(l, m, density=1e-4, random_state=rng)
c = rng.standard_normal(l)

使用下面的代码定义下限和上限。

lbound = rng.standard_normal(m)
ubound = lbound + 1

Scipy Optimize Least Squares lsq_linear example

Scipy Optimize Least Squares lsq_linear example

通过将创建的 矩阵 B向量 c 与优化方法*lsq_linear()*绑定,找到给定数据的最优值。使用下面的代码。

res = lsq_linear(B, c, bounds=(lbound, ubound), lsmr_tol='auto', verbose=1)

使用下面的代码检查完整的结果。

print(res)

Scipy Optimize Least Squares lsq_linear

Scipy Optimize Least Squares lsq_linear

从输出中,我们可以看到函数成本值、最优性等结果。

阅读: Scipy 常量–多个示例

Scipy 优化约束或最小化约束示例

这里,我们将使用线性规划来优化带约束的问题,子包*scipy.optimize*包含一个方法*lineprog( )*来解决与线性规划相关的问题。

下面给出了我们想要优化的线性问题。

maximize z=x+3y

subject to  3x + y <= 25
           -5x + 6y <= 15
           -x = 3y >=-3
           -x + 6y = 20
            x>= 0
            y>= 0

上述问题,我们需要优化,但这里有一个问题,即线性规划只处理不等式约束小于或等于符号的最小化问题。

为了解决这个问题,我们需要将这些问题转化为约束小于等于符号的最小化问题。所以改一下如下图的问题。

minimize -z=x-3y

subject to  3x + y <= 25
           -5x + 6y <= 15
            x - 3y <=3
           -x + 6y = 20
            x>= 0
            y>= 0

让我们使用以下步骤求解上述带约束的目标函数*-z=x-3y*:

使用下面的代码从子包*scipy.optimize*中导入方法*linprog( )*

# Importing the linprog
from scipy.optimize import linprog

让我们使用下面的代码来定义目标函数的约束及其约束。

# defining Coefficient for x and y
objective = [-1, -3]

# defining Coefficient inequalities
lhs_inequality = [[ 3,  1],
           [-5,  6],
           [ 1, -3]]

rhs_inequality = [25,
            15,
              3]

lhs_equality = [[-1, 6]]
rhs_equality = [20]

使用下面的代码定义边界。

# defining the bounds for each variable
bound = [(0, float("inf")),  # bounds of x
     (0, float("inf"))]  # bounds of y

让我们通过定义的目标函数及其对方法*linprog( )*的约束来优化或最小化目标函数。

# Optimizing the problems using the method linprog()
opt_res = linprog(c=objective, A_ub=lhs_inequality, b_ub=rhs_inequality,
           A_eq=lhs_equality, b_eq=rhs_equality, bounds=bound ,
           method="revised simplex")

检查优化上述功能后的结果。

print(opt_res)

Scipy Optimize Constraints Or Minimize Constraints Example

Scipy Optimize Constraints Or Minimize Constraints Example

看看上面目标函数优化的结果。

阅读: Scipy Misc + Examples

Scipy 优化界限

在 Scipy 子包scipy.optimize中,有一个名为Bounds的方法对变量进行约束。

下面给出了语法。

scipy.optimize.Bounds(lb, ub, keep_feasible=False)

下面给出一般的不等式形式。

lowerbound <= x <= upperbound
lb <= x <= ub

其中*lb**ub*是独立变量的下限和上限,*keep_feasible*用于在迭代期间使约束组件可行。

让我们举一个定义边界的例子。

0 <= x <= 2

因此,在本教程中,我们已经学习了使用 Scipy Optimize 来实现不同的优化算法,以获得函数的最佳值。此外,我们还讨论了以下主题。

  • 科学优化
  • Scipy 优化最小化示例
  • Scipy 优化最小化
  • Scipy 优化曲线拟合
  • 优化最小二乘法
  • 科学优化 Fmin
  • Scipy 优化约束
  • 科学优化界限
  • Scipy 优化最小化约束示例

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Scipy 旋转图像+示例

原文:https://pythonguides.com/scipy-rotate-image/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习“ Scipy 旋转图像,这里将根据不同的角度旋转图像。此外,我们将讨论以下主题。

  • Scipy Rotate Image
  • 将图像旋转 90 度
  • Scipy 顺时针旋转图像 90 度
  • 将图像旋转 180 度
  • 将图像旋转 120 度
  • Scipy 将图像旋转 60 度
  • Scipy 将图像旋转 40 度

目录

Scipy Rotate Image

Scipy 有一个模块*scipy.ndimage*来控制图像的形状、大小等,或者执行图像处理任务,这个库有很多图像处理操作的函数。这里我们将使用函数*rotate()*以给定的角度旋转提供的图像。

下面给出了方法*scipy.ndimage.rotate()*的语法。

scipy.ndimage.rotate(input, angle, axes=(1, 0), reshape=True, output=None, mode='constant')

以下是方法rotate()中最常用的参数。

  • input(array _ data):就是我们要旋转的输入数组或者图像。
  • 角度(浮点): 用于指定旋转角度,如 20 度或 90 度。
  • 轴(元组中的两个整数): 旋转的平面由两个轴定义。
  • 输出(数据类型或数组): 定义返回数组的数据类型,默认返回数组的数据类型与输入数组相同。
  • 模式: 用于指定***‘constant’, ‘mirror’, ‘wrap’, ‘reflect’, ‘nearest’***的模式。

让我们按照以下步骤通过一个示例来理解:

使用下面的 python 代码导入所需的库,如matplotlibscipy

from matplotlib import image, pyplot
from scipy import ndimage

使用下面的代码从目录或者你的计算机上存在的任何地方加载图像。

img = image.imread('rob_potter.jpg')

这里,模块*image*的函数*imread()*以像素阵列的形式读取图像。

在模块*pyplot*的功能*imshow()*的帮助下查看加载的图像,如下所示。

pyplot.imshow(img)

Scipy Rotate Image example

Scipy Rotate Image example

让我们使用下面的代码将上面加载的图像旋转到某个角度。

rob_potter_rotate = ndimage.rotate(img,20,mode='constant')

在上面的代码中,我们使用了 Scipy 的模块*ndimage*的函数*rotate()*来旋转任何图像。还提供一些参数,如我们要旋转的图像*img*,旋转的角度*20*度,模式为*constant*

现在使用下面的代码查看旋转了 20 度的图像。

pyplot.imshow(rob_ptter_rotate)

Scipy Rotate Image

Scipy Rotate Image

看看上面的输出,看看我们是如何将图像旋转 20 度的。

阅读: Scipy 优化–实用指南

Scipy 将图像旋转 90 度

这里我们将使用下面的代码逆时针旋转图像 90 度。

使用下面的 python 代码导入所需的库*matplotlib*和 scipy。

from matplotlib import image, pyplot
from scipy import ndimage

使用下面代码所示的函数*imread()*从目录或您计算机上存在图像的任何地方加载图像。

img = image.imread('rob_potter.jpg')
rob_potter_rotate = ndimage.rotate(img,-90,mode='constant')

在上面的代码中,我们使用了 Scipy 的模块*ndimage*的函数*rotate()*来旋转任何图像。还提供一些参数,如我们要旋转的图像*img*,旋转的角度*-90*度,模式为*constant*

pyplot.imshow(rob_potter_rotate)

Scipy Rotate Image 90 degrees

Scipy Rotate Image 90 degrees

这就是我们如何将提供的图像逆时针旋转 90 度。

阅读:Scipy Sparse–有用的教程

Scipy 顺时针旋转图像 90 度

这里我们将提供的图像顺时针旋转 90 度。

使用下面的 python 代码导入所需的库*matplotlib*和 scipy。

from matplotlib import image, pyplot
from scipy import ndimage

使用下面代码所示的函数*imread()*从目录或您计算机上存在图像的任何地方加载图像。

img = image.imread('rob_potter.jpg')
rob_potter_rotate = ndimage.rotate(img,90,mode='constant')

在上面的代码中,我们使用了 Scipy 的模块*ndimage*的函数*rotate()*来旋转任何图像。还提供一些参数,如我们要旋转的图像*img*,旋转的角度*90*度,模式为*constant*

pyplot.imshow(rob_potter_rotate)

Scipy Rotate Image 90 degrees clockwise

Scipy Rotate Image 90 degrees clockwise

从上面的输出,我们可以看到图像旋转了 90 度。

阅读:科学常数

Scipy 将图像旋转 180 度

这里我们将给定的图像顺时针旋转 180 度。

使用下面的 python 代码导入所需的库*matplotlib*和 scipy。

from matplotlib import image, pyplot
from scipy import ndimage

使用下面代码所示的函数*imread()*从目录或您计算机上存在图像的任何地方加载图像。

img = image.imread('rob_potter.jpg')
rob_potter_rotate = ndimage.rotate(img,180,mode='constant')

在上面的代码中,我们使用了 Scipy 的模块*ndimage*的函数*rotate()*来旋转任何图像。还提供一些参数,如我们要旋转的图像*img*,旋转的角度*180*度,模式为*constant*

pyplot.imshow(rob_potter_rotate)

Scipy Rotate Image 180

Scipy Rotate Image 180

从上面的输出,我们可以看到图像旋转了 180 度。

阅读: Scipy Integrate +示例

Scipy 将图像旋转 120 度

这里我们将提供的图像旋转 120 度。

使用下面的 python 代码导入所需的库*matplotlib*和 scipy。

from matplotlib import image, pyplot
from scipy import ndimage

使用下面代码所示的函数*imread()*从目录或您计算机上存在图像的任何地方加载图像。

img = image.imread('rob_potter.jpg')
rob_potter_rotate = ndimage.rotate(img,120,mode='constant')

在上面的代码中,我们使用了 Scipy 的模块*ndimage*的函数*rotate()*来旋转任何图像。还提供一些参数,如我们要旋转的图像*img*,旋转的角度*120*度,模式为*constant*

pyplot.imshow(rob_potter_rotate)

Scipy Rotate Image 120

Scipy Rotate Image 120

从上面的输出,我们可以看到图像旋转了 120 度

阅读科学杂项+示例

Scipy 将图像旋转 60 度

这里我们将提供的图像旋转 60 度。

使用下面的 python 代码导入所需的库*matplotlib*和 scipy。

from matplotlib import image, pyplot
from scipy import ndimage

使用下面代码所示的函数*imread()*从目录或您计算机上存在图像的任何地方加载图像。

img = image.imread('rob_potter.jpg')
rob_potter_rotate = ndimage.rotate(img,60,mode='constant')

在上面的代码中,我们使用了 Scipy 的模块*ndimage*的函数*rotate()*来旋转任何图像。还提供一些参数,如我们要旋转的图像*img*,旋转的角度*60*度,模式为*constant*

pyplot.imshow(rob_potter_rotate)

Scipy Rotate Image 60

Scipy Rotate Image 60

从上面的输出,我们可以看到图像旋转了 60 度。

阅读科学统计数据

Scipy 将图像旋转 40 度

这里我们将把提供的图像旋转 40 度。

使用下面的 python 代码导入所需的库*matplotlib*和 scipy。

from matplotlib import image, pyplot
from scipy import ndimage

使用下面代码所示的函数*imread()*从目录或您计算机上存在图像的任何地方加载图像。

img = image.imread('rob_potter.jpg')
rob_potter_rotate = ndimage.rotate(img,40,mode='constant')

在上面的代码中,我们使用了 Scipy 的模块*ndimage*的函数*rotate()*来旋转任何图像。还提供一些参数,如我们要旋转的图像*img*,旋转的角度*40*度,模式为*constant*

pyplot.imshow(rob_potter_rotate)

Scipy Rotate Image 40

Scipy Rotate Image 40

从上面的输出,我们可以看到图像旋转了 40 度。

此外,请查看以下相关教程列表:

因此,在本教程中,我们已经学习了“Scipy 旋转图像”,并涵盖了以下主题。

  • Scipy Rotate Image
  • 将图像旋转 90 度
  • Scipy 顺时针旋转图像 90 度
  • 将图像旋转 180 度
  • 将图像旋转 120 度
  • Scipy 将图像旋转 60 度
  • Scipy 将图像旋转 40 度

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Scipy 信号-有用的教程

原文:https://pythonguides.com/scipy-signal/

Python & Machine Learning training courses

在本 Python 教程中,我们将了解“ Scipy 信号,并涵盖以下主题。

  • Scipy 信号
  • 西皮信号黄油
  • 科学信号处理
  • 敏感信号找到峰值
  • 信号卷积
  • 信号相关
  • 信号滤波器
  • 突发信号脉冲
  • 锋利的信号方块
  • 信号频谱图

目录

Scipy 信号

Scipy 有一个库*scipy.signal*,用于修改、分析和处理视频信号、音频信号等信号。

它有许多功能或方法来处理以下类别的不同种类的信号问题:

  • b 样条
  • 卷积的
  • 滤波器设计
  • 过滤
  • 连续时间线性系统
  • Matlab 风格的 IIR 滤波器设计
  • 离散时间线性系统
  • 窗口功能
  • LTI 交涉
  • 波形
  • 线性调频 z 变换和缩放 FFT
  • 光谱分析
  • 小波
  • 峰值发现

每个类别包含很多函数,所以这里我们将介绍一些类别的常用方法。

阅读: Scipy Misc + Examples

Scipy 信号黄油

Scipy 有一个方法*butter()*将巴特沃兹滤波器应用于信号。换句话说,我们可以设计 n 阶数字或模拟巴特沃兹滤波器来平坦化频率。

下面给出了语法。

scipy.signal.butter(N, Wn, btype='low', analog=False, output='ba', fs=None)

其中参数为:

  • N(int): 用于指定过滤器的阶数。
  • Wn(array_data): 用于指定高通和低通滤波器的临界频率。
  • b 类型: 用于指定使用哪种滤波器,如带阻、高通、低通和带通。
  • 模拟(布尔): 如果为真,则使用模拟滤波器,否则,在为假的情况下,使用数字滤波器。
  • output:用于指定输出类型,如 zpk ( ploe-zero)、sos(二阶部分)和 ba(向后兼容)。

让我们以下面的步骤为例:

使用下面的 python 代码导入所需的库。

from scipy.signal import butter
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline 

使用下面的代码创建信号的持续时间。

t_duration = np.linspace(0,0.5,2000,False)

使用以下代码生成一个频率为 2040 赫兹 的信号。

sign = np.sin(2*np.pi*20*t_duration) + np.sin(2*np.pi*40*t_duration)

使用下面的代码绘制创建的信号。

fig, (ax1) = plt.subplots(1, 1, sharex=True)
ax1.plot(t_duration, sign)
ax1.set_title('20 and 40 Hz Sinusoid')
ax1.axis([0, 0.5, -2, 2.5])

Scipy Signal Butter example

Scipy Signal Butter example

创建一个 25 Hz 的巴特沃兹高通滤波器,并使用下面的代码将其应用于上面创建的信号。

from scipy import signal
sos = butter(15, 20, 'hp', fs=2000, output='sos')
filtd = signal.sosfilt(sos, sign)

使用以下代码绘制应用滤波器后的信号。

fig, (ax2) = plt.subplots(1, 1, sharex=True)
ax2.plot(t_duration, filtd)
ax2.set_title('After applying 20 Hz high-pass filter')
ax2.axis([0, 0.5, -2, 2.5])
ax2.set_xlabel('Time (seconds)')
plt.tight_layout()
plt.show()

Scipy Signal Butter

Scipy Signal Butter

这就是如何在信号上应用巴特沃兹。

阅读: Scipy Integrate +示例

Scipy 信号找到峰值

Scipy 在模块*scipy.signal*中有一个方法*find_peaks()*,它根据给定的峰值属性返回所有的峰值。

下面给出了语法。

scipy.signal.find_peaks(x, height=1, prominence=4,  distance=2, width=2, threshold=1, rel_height=0.5, wlen=1, )

其中参数为:

  • x(序列): 用于接受有峰值的信号。
  • 高度(sequence,ndarray,number): 用于提供峰高。
  • 阈值(sequence,ndarray,number): 用于提供峰值阈值。
  • 距离(数字): 用于提供相邻山峰之间的最小水平距离。
  • 日珥(sequence,ndarray,number): 用于提供峰值日珥。
  • 宽度(sequence,ndarray,number): 用于提供峰值的宽度。
  • wlen(int): 它用于计算日珥峰值。
  • rel_height(int): 用于计算峰高。

让我们以下面的步骤为例:

使用下面的 python 代码导入所需的库。

from scipy.signal import find_peaks
from scipy.misc import electrocardiogram
import matplotlib.pyplot as plt
%matplotlib inline

使用以下代码生成心电图。

value = electrocardiogram()[1000:5000]

现在使用下面的代码。

peak, _ = find_peaks(value, height=0)
plt.plot(value)
plt.plot(peak, value[peak], "*")
plt.plot(np.zeros_like(value), "--", color="green")
plt.show()

Scipy Signal Find peaks

Scipy Signal Find peaks

这就是如何找到信号的所有峰值。

阅读:科学统计-完整指南

信号卷积

Scipy 在模块*scipy.signal*中有一个方法*convolve()*,通过组合两个信号返回第三个信号。

下面给出了语法。

scipy.signal.convolve(in1, in2, mode='full', method='auto')

其中参数为:

  • in1(array_data): 用于以数组的形式输入第一个信号。
  • in2(array_data): 用于以数组的形式输入第二个信号,维数必须与第一个输入数组相同。
  • 模式: 用于指定决定输出大小的字符串。模式可以是*same**full**valid*
  • 方法: 用于指定计算卷积的方法。方法可以是*auto**direct**fft*

让我们通过下面的步骤来了解一个示例:

使用下面的 python 代码导入所需的库。

from scipy.signal import convolve
import scipy.signal
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

使用下面的代码创建两个不同的信号。

signal_1 = np.repeat([1., 2., 1.], 50)
signal_2 = np.repeat([2., 4., 5.], 50)

现在,使用下面的代码将两个信号相加,创建第三个信号。

conv = signal.convolve(signal_1, signal_2, mode='same') / sum(signal_2)

让我们用下面的代码画出上面的信号。

fig, (ax_actual, ax_sig_1, ax_conv) = plt.subplots(3, 1, sharex=True)
ax_actual.plot(signal_1)
ax_actual.set_title('Actual pulse')
ax_actual.margins(0, 0.1)
ax_sig_1.plot(signal_2)
ax_sig_1.set_title(' It is the Filter impulse response')
ax_sig_1.margins(0, 0.1)
ax_conv.plot(conv)
ax_conv.set_title('Convolved signal')
ax_conv.margins(0, 0.1)
fig.tight_layout()
fig.show()

Scipy Signal Convolve

Scipy Signal Convolve

本指南通过合并两个不同的信号来生成第三个信号。

阅读: Scipy 旋转图像+示例

Scipy 信号相关

Scipy 在模块*scipy.signal*中有一个类似于方法*scipy.signal.convolve()*的方法*correlate()*。它还通过将两个信号相加产生第三个信号,所产生的信号被称为*cross correlation*

下面给出了语法。

scipy.signal.correlate(in1, in2, mode='full', method='auto')

其中参数为:

  • in1(array_data): 用于以数组的形式输入第一个信号。
  • in2(array_data): 用于以数组的形式输入第二个信号,维数必须与第一个输入数组相同。
  • 模式: 用于指定决定输出大小的字符串。模式可以是*same**full**valid*
  • 方法: 用于指定计算卷积的方法。方法可以是*auto**direct**fft*

让我们通过下面的步骤来了解一个示例:

使用下面的 python 代码导入所需的库。

from scipy.signal import correlate
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

使用下面的代码创建两个不同的信号。

signal_1 = np.repeat([1., 2., 1.], 50)
signal_2 = np.repeat([2., 4., 5.], 50)

现在,使用下面的代码将两个信号相加,创建第三个信号。

conv = signal.correlate(signal_1, signal_2, mode='same') / sum(signal_2)

让我们用下面的代码画出上面的信号。

fig, (ax_actual, ax_sig_1, ax_conv) = plt.subplots(3, 1, sharex=True)
ax_actual.plot(signal_1)
ax_actual.set_title('Actual pulse')
ax_actual.margins(0, 0.1)
ax_sig_1.plot(signal_2)
ax_sig_1.set_title(' It is the Filter impulse response')
ax_sig_1.margins(0, 0.1)
ax_conv.plot(conv)
ax_conv.set_title('Correlated signal')
ax_conv.margins(0, 0.1)
fig.tight_layout()
fig.show()

Scipy Signal Correlate

Scipy Signal Correlate

这就是如何在 Python 中使用 Scipy 关联信号。

阅读: Scipy 优化–实用指南

信号滤波器

Scipy 在模块*scipy.signal*中有一个方法*ifilter()*,它使用过滤器*Finite Impulse Respose* (FIR)或Infinite Impulse Response在一个维度上清理信号数据。

下面给出了语法。

scipy.signal.lfilter(b, a, x, axis=- 1, zi=None)

其中参数为:

  • b(array_data): 是包含分子系数的一维向量序列。
  • a(array_data): 它是包含分母系数的一维向量序列。
  • x(array_data): 作为输入的是 ndarray。
  • axis(int): 是给定数组一的轴的名称,该数组应用了线性过滤器。
  • zi(array_data): 用于指定支持过滤器的初始条件。

上面的方法返回两个值*y**zi*

让我们来看一个使用以下步骤的示例:

使用下面的 python 代码导入所需的库。

from scipy.signal import lfilter,butter,filtfilt
import matplotlib.pyplot as plt
import numpy as np

创建一个噪声信号,我们将使用下面的代码过滤。

rng = np.random.default_rng()
array_data = np.linspace(-2, 2, 302)
sin_data = (np.sin(2*np.pi*0.65*array_data*(1-array_data) + 1.1) +
     0.2*np.sin(2*np.pi*2.1*array_data + 1) +
     0.20*np.cos(2*np.pi*2.58*array_data))
noisy_data = sin_data + rng.standard_normal(len(array_data)) * 0.07

Scipy Signal Ifilter example

Scipy Signal Ifilter example

使用以下代码设计 4 阶低通巴特沃兹滤波器。

num_coff, deno_coff = butter(4, 0.06)

让我们对有噪声的数据实施滤波。

zi = lfilter_zi(num_coff, deno_coff)
z, _ = lfilter(num_coff, deno_coff, noisy_data, zi=zi*noisy_data[0])

再次实现过滤器。

z2, _ =lfilter(num_coff, deno_coff, z, zi=zi*z[0])

现在实现 filtfilt 过滤器。

y = filtfilt(num_coff, deno_coff, noisy_data)

使用以下代码绘制所有信号。

plt.figure
plt.plot(array_data, noisy_data, 'b', alpha=0.75)
plt.plot(array_data, z, 'r--', array_data, z2, 'r', array_data, y, 'k')
plt.legend(('This is noisy one', 'lfilter, once', 'lfilter, twice',
            'This is filtfilt one'), loc='best')
plt.grid(True)
plt.show()

Scipy Signal Ifilter

Scipy Signal Ifilter

这就是如何使用*lfilter()*方法过滤噪声信号。

阅读:Scipy Sparse–有用的教程

尖峰信号脉冲

scipy 在 Scipy 模块*scipy.signal*中有一个方法*impulse()*,它是连续时间系统对外部变化的回应。

下面给出了语法。

scipy.signal.impulse(system, X0=None, T=None, N=None)

其中参数为:

  • 系统(数组 _ 数据元组): 用于定义系统。
  • X0(array_data): 它是初始状态的数组向量。
  • T(array_data): 是时间点。
  • N(int): 要计算时间点的个数,使用此参数。

该方法返回两个值*T**yout*

让我们按照以下步骤来看一个例子:

使用下面的 python 代码导入所需的库。

import matplotlib.pyplot as plt
from scipy.signal import impulse

使用下面的代码创建一个系统。

sys = ([2.1], [2.1, 3.1, 2.1])
time_pts, impulse_res = signal.impulse(sys)

现在使用下面的代码绘制生成的脉冲。

plt.plot(time_pts,impulse_res)

Scipy Signal Impulse

Scipy Signal Impulse

这就是如何使用模块*scipy.signal*的 impulse 方法。

阅读: Scipy 常量–多个示例

尖尖的信号方块

Scipy 模块*scipy.signal*包含一个生成方波波形的方法*square()*

下面给出了语法。

scipy.signal.square(t, duty=0.5)

其中参数为:

  • t(array_data): 输入的是数组数据。
  • duty(array _ data):用于定义占空比,默认为 0.5。

该方法返回包含方波的 ndarray 类型的y

让我们按照以下步骤生成一个方波:

使用下面的 python 代码导入所需的库。

import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import square

使用下面的代码创建一个数据和方波数据的数组。

array_data = np.linspace(0, 2, 1000, endpoint=False)
square_wave =  square(2 * np.pi * 2 * array_data)

现在使用下面的代码绘制出创建的方波波形。

plt.plot(array_data,square_wave)
plt.ylim(-1.5, 1.5)

Scipy Signal Square

Scipy Signal Square

这就是如何在 Python 程序中使用 Scipy 创建方波波形。

阅读: Scipy 卷积-完整指南

尖峰信号频谱图

Scipy 在模块*scipy.signal*中有一个方法*spectrogram()*,它显示了特定波形的不同频率上的信号强度随时间的变化。

下面给出了语法。

scipy.signal.spectrogram(x, fs=1.0, window=('tukey', 1), nperseg=None, noverlap=None, nfft=None, detrend='constant', return_onesided=False, axis=- 1, mode='psd')

其中参数为:

  • x(array_data): 是时间序列。
  • 【fs】(浮点): 用于提供时序采样频率。
  • window(array_data, tuplestring): 用来指定我们要实现什么样的窗口。
  • nperseg(int): 指定每一段的长度。
  • 【nooverlap(int):用于指定线段间重叠的点数。
  • nfft(int): 它是 fft 的大小。
  • detrend(False,string,function): 用于指定如何从每一段中去除趋势。
  • return _ one side(boolean):获取身边的谱数据。如果为真,则返回单面,否则在为假的情况下返回双面。
  • (int)轴: 用于指定沿哪个轴计算谱图。
  • 模式(字符串): 指定我们想要的预期值,如角度、幅度、相位、复数和 PSD。

该方法返回三个值*f*(频率为数组)*t*(分段次数为数组)*sxx*(声谱图)。

通过下面的步骤,让我们用一个例子来理解:

使用下面的 python 代码导入所需的库。

from scipy.signal import spectrogram
import matplotlib.pyplot as plt
import numpy as np
from scipy.fft import fftshift

使用以下代码定义生成信号所需的参数值。

rng = np.random.default_rng()
sample_fre = 9e3
n = 1e3
amp = 3 * np.sqrt(3)
noisep = 0.02 * sample_fre / 3
time_data = np.arange(n) / float(sample_fre)
mode = 600*np.cos(3*np.pi*0.4*time_data)
car_rier = amp * np.sin(3*np.pi*4e4*time_data + mode)
gen_noise = rng.normal(scale=np.sqrt(noisep), size=time_data.shape)
gen_noise *= np.exp(-time_data/5)
signal_data = car_rier + gen_noise

现在使用下面的代码计算并显示声谱图。

sample_freq, segment_time, spectrogram = spectrogram(signal_data, sample_fre)
plt.pcolormesh(segment_time, sample_freq, spectrogram, shading='gouraud')
plt.ylabel('It is frequency in Hertz')
plt.xlabel('It is time in second')
plt.show()

Scipy Signal Spectrogram

Scipy Signal Spectrogram

这是如何使用 Python 中的 scipy 计算声谱图。

另外,看看更多的 Scipy 教程。

因此,在本教程中,我们已经了解了" Scipy 信号"并涵盖了以下主题。

  • Scipy 信号
  • 西皮信号黄油
  • 科学信号处理
  • 敏感信号找到峰值
  • 信号卷积
  • 信号相关
  • 信号滤波器
  • 突发信号脉冲
  • 锋利的信号方块
  • 信号频谱图

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Scipy 稀疏–有用的教程

原文:https://pythonguides.com/scipy-sparse/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习 Scipy Sparse ,其中我们将涉及如何创建一个稀疏矩阵。此外,我们将讨论以下主题。

  • Scipy Sparse rand
  • Scipy Sparse linalg
  • 稀疏 CSR 矩阵
  • 稀疏矩阵到 NumPy 数组
  • Scipy Sparse hstack
  • Scipy 稀疏 coo 矩阵
  • Scipy Sparse eigsh
  • 从稀疏到密集
  • 熊猫数据帧的稀疏矩阵

目录

什么是 Scipy 稀疏

稀疏矩阵 包含大部分元素为零的元素。Scipy 中有两种类型的稀疏矩阵,第一种是*CSR(Compressed Sparse Row)*,第二种是*CSC(Compressed Sparse Column)*。有一个模块scipy.sparse处理稀疏数据或矩阵。

Scipy Sparse Rand

*scipy.sparse*包包含一个函数*rand()*,通过指定形状和密度来生成一个包含均匀分布值的矩阵。

使用函数*rand()*创建稀疏矩阵的语法如下所示。

scipy.sparse.rand(m, n, density=0.01, format='coo', dtype=None, random_state=None)

其中参数为:

  • m,n: 它定义了矩阵的形状——就像我们要构建一个形状为 2 乘 3 的矩阵,其中 m 和 n 分别为 2 和 3。
  • 密度: 它用来指定我们要生成的矩阵的密度,如果我们指定矩阵的密度为 1,那么它就是全矩阵。如果将密度指定为 0,这意味着矩阵不包含非零项。
  • 格式: 用于指定矩阵的格式。
  • dtype: 用于定义返回的矩阵值的数据类型。
  • random_state: 用于产生可重复的值。

在下面的演示中,我们将使用函数rand()生成稀疏矩阵。

使用下面的代码导入函数rand()

from scipy.sparse import rand

使用下面的代码,通过用 3 指定 4 的形状,用密度= 0.30格式="csr"random_state=40 创建一个矩阵。

matrix_data = rand(4, 3, density=0.30, format="csr", random_state=40)

检查矩阵数据类型及其格式。

matrix_data

现在,在矩阵上使用函数toarray()检查创建的矩阵的元素。

matrix_data.toarray()

Scipy Sparse rand

Scipy Sparse rand

阅读:Python 中的 Scipy 是什么

Scipy Sparse linalg

Scipy 中,子包*scipy.sparse*有模块*linalg*来处理线性代数问题,它有许多与下面给出的不同类别相关的方法。

抽象线性算子

它有两种方法:

  • LinearOperator(args,kwargs) 😗** 是做矩阵-向量乘积的常用接口。
  • aslinearoperator(A):它输出一个 linear operator。

矩阵规范

它也有两种方法来计算矩阵的正态分布。

  • 范数(x[,ord,axis]): 它返回给定稀疏矩阵的正态分布。
  • onenormest(A[,t,itmax,compute_v,compute_w]): 给定一个稀疏矩阵的 1-范数,它计算一个下界。

矩阵运算

它用于计算给定稀疏矩阵的指数和逆矩阵,有三种方法。

  • inv(A): 用于计算给定稀疏矩阵的逆
  • expm(A): t 用于借助 Pade 近似计算矩阵指数。
  • expm_multiply(A,B[,start,stop,num,endpoint]): t 用于计算 A 的矩阵指数对 B 的作用

解决线性问题

它有解决线性问题的直接方法,并且有许多方法,这里我们将了解一些方法。

  • spsolve(A,b[,permc_spec,use_umfpack]): 用于求稀疏线性系统 Ax=b 的解,其中 b 代表一个向量或一个矩阵。
  • spsolve_triangular(A,b[,lower,…]): 用于求类似于 A x = b 对于 x 的方程的解,其中 A 被认为是一个三角矩阵。

官方文档“scipy . sparse . Lina LG”还有其他方法

稀疏 CSR 矩阵

csr代表*Compressed Sparse Row Matrix*,所以我们可以使用 Scipy 的子包*scipy.sparse*中的函数创建csr matrix

如果我们想要一个可以执行加法、乘法、减法、矩阵幂和除法的矩阵,那么*csr matrix*就适合了。

可以通过如下所示的多种方式创建*csr matrix*

csr_matrix(D): 使用 rank _ 2n 阵列或密集矩阵。

使用下面的代码导入必要的库。

import numpy as np
from scipy.sparse import csr_matrix

使用下面的代码创建一个秩为 2 的矩阵。

D = np.array([[1, 0, 1, 0, 0, 0], [2, 0, 2, 0, 0, 1],\
 [0, 0, 0, 2, 0, 1]])

使用以下代码检查装箱的矩阵。

print(D)

将创建的矩阵传递给函数 csr_matrix() ,使用下面的代码创建*csr matrix*并查看。

# Creating csr matrix
csr_m = csr_matrix(D) 

Scipy Sparse CSR matrix csr_matrix(D)

Scipy Sparse CSR matrix csr_matrix(D)

csr_matrix(S): 使用另一个已经创建的稀疏矩阵创建一个新的*csr matrix*。使用我们在上面的名称csr_m中创建的相同矩阵。

csr_mat = csr_matrix(csr_m)

检查数据类型和与矩阵相关的其他信息。

csr_mat

使用以下代码查看板条箱矩阵。

csr_mat.toarray()

Scipy Sparse CSR matrix csr_matrix(S)

Scipy Sparse CSR matrix csr_matrix(S)

csr_matrix((M,N),【类型】): 通过可选选项类型指定形状 M 和 N,创建一个空矩阵。

使用下面的代码创建一个*csr matrix*

csr_matrix((5, 4), dtype=np.int8).toarray()

Scipy Sparse CSR matrix csr_matrix(M N)

Scipy Sparse CSR matrix csr_matrix(M N)

csr_matrix((data,(row_ind,col_ind)),【shape=(M,N)】:用于构造**data, row_ind and col_ind**满足关系 csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)]) 的矩阵。

使用下面的代码创建一个*csr matrix*

import numpy as np
from scipy.sparse import csr_matrix

row_idx = np.array([0, 1, 0, 1, 2, 2])
col_idx = np.array([0, 1, 1, 0, 1, 2])
data = np.array([2, 3, 4, 5, 6, 7])
csr_matrix((data, (row_idx,col_idx)), shape=(4, 4)).toarray()

Scipy Sparse CSR matrix csr_matrix example

Scipy Sparse CSR matrix csr_matrix example

【CSR _ matrix((data,indices,indptr),【shape=(M,N)】:

import numpy as np
from scipy.sparse import csr_matrix

indptr_a = np.array([0, 4, 5, 2])
indices_b = np.array([0, 2, 2, 0, 2, 3])
data = np.array([1, 2, 3, 4, 5, 6])
csr_matrix((data, indices_b, indptr_a), shape=(3, 3)).toarray()

Scipy Sparse CSR matrix csr_matrix tutorial

Scipy Sparse CSR matrix csr_matrix tutorial

阅读:蟒蛇皮里的熊猫

Scipy 稀疏矩阵到 NumPy 数组

***[numpy array](https://pythonguides.com/python-numpy-array/)***是一个表示密集 n 阵列矩阵的矩阵,所以这里将使用函数toarray*csr matrix*转换成dense ndarray

下面给出了语法。

csr_matrix.todense(order=None, out=None)

其中参数为:

  • order: 用于指定使用哪些 order,如 row-major(C)和 column-major(F)来存储多维数据。默认情况下,None表示没有订单。
  • out: 用于指定如何像输出缓冲区一样以数组(numpy.matrix)的形式返回结果,而不是在返回结果的同时创建一个新的数组。

让我们以下面的步骤为例:

使用下面的代码导入必要的库。

import numpy as np
from scipy.sparse import csr_matrix

使用下面的代码创建数组。

row_data = np.array([0, 0, 2, 2, 1, 1, 4, 4, 5, 5, 1, 1, 2])
col_data = np.array([0, 3, 1, 0, 6, 1, 6, 3, 5, 3, 1, 4, 3])
array_data = np.array([1]*len(r))

使用下面的代码创建csr matrix

csr_mat = csr_matrix(array_data,(row_data,col_data),shape =(7,7))

使用以下代码检查矩阵中的数据类型和存储元素。

csr

通过使用下面的代码对矩阵csr_mat应用方法toarray()csr matrix转换为 numpy 数组矩阵。

csr_to_array = csr_mat.toarrat()

使用以下代码检查密集矩阵*csr_to_array*的元素。

csr_to_array

Scipy Sparse matrix to NumPy array

Scipy Sparse matrix to NumPy array

阅读: Scipy 旋转图像+示例

Scipy Sparse hstack

为了逐列(水平地)堆叠稀疏矩阵,*scipy.sparse*有方法*hstack()*来实现。

下面给出了语法。

scipy.sparse.hstack(blocks, format=None, dtype=None)

其中参数为:

  • 分块: 我们要堆叠的是稀疏矩阵。
  • 格式: 用于指定稀疏矩阵的格式,默认为*csr*
  • dtype: 是返回矩阵的数据类型。

运行以下步骤创建水平堆栈矩阵。

使用下面的代码导入所需的库。

from scipy.sparse import hstack, coo_matrix

创建两个稀疏矩阵,并将这两个矩阵传递给一个方法*hstack*

first_mat = coo_matrix([[2, 3], [4, 5]])
second_mat = coo_matrix([[6], [7]])
hstack([first_mat,second_mat]).toarray()

Scipy Sparse hstack

Scipy Sparse hstack

看看上面的输出,两个矩阵是如何水平堆叠的。

阅读: Scipy Integrate +示例

Scipy 稀疏 coo 矩阵

在 Scipy 中,子包*scipy.sparse*包含方法*coo_matrix()*来生成坐标格式的新稀疏矩阵。

可以通过如下所示的多种方式创建*coo matrix*

coo_matrix(D): 使用 rank _ 2n array D 或密集矩阵。

使用下面的代码导入必要的库。

import numpy as np
from scipy.sparse import csr_matrix

使用下面的代码创建一个秩为 2 的矩阵。

D = np.array([[1, 0, 1, 0, 0, 0], [2, 0, 2, 0, 0, 1],\
 [0, 0, 0, 2, 0, 1]])

使用以下代码检查装箱的矩阵。

print(D)

将创建的矩阵传递给函数 coo_matrix() ,使用下面的代码创建*coo matrix*并查看。

# Creating coo matrix
csr_m = csr_matrix(D) 

Scipy Sparse coo matrix coo_matrix(D)

Scipy Sparse coo matrix coo_matrix(D)

  • coo_matrix(S): 使用另一个已经创建的稀疏矩阵创建一个新的*coo matrix*。使用我们在上面的名称coo_m中创建的相同矩阵。
coo_mat = csr_matrix(coo_m)

检查数据类型和与矩阵相关的其他信息。

coo_mat

使用下面的代码查看创建的矩阵。

coo_mat.toarray()

Scipy Sparse coo matrix coo_matrix(S)

Scipy Sparse coo matrix coo_matrix(S)

  • coo_matrix((M,N),【类型】): 用可选选项类型指定形状 M 和 N,创建一个空矩阵。

使用下面的代码创建一个*coo matrix*

coo_matrix((4, 6), dtype=np.int8).toarray()

Scipy Sparse coo matrix coo_matrix(M,N)

Scipy Sparse coo matrix coo_matrix(M,N)

阅读: Scipy 信号-有用教程

尖锐稀疏的声音

为了找到给定对称方阵的特征向量和特征值,使用存在于子包*scipy.sparase.linalg*中的方法*eigsh()*

下面给出了语法。

scipy.sparse.linalg.eigsh(A, k=6)

其中参数为:

  • 答: 它接受 ndarray,线性算子,或者稀疏矩阵。它是一个平方运算符,用于运算*(A * x)*,其中 A 是一个矩阵。
  • k: 它用来指定我们想要从那个矩阵中得到的特征向量和特征值的个数。

让我们以下面的步骤为例。

使用下面的代码导入方法eigsh

from scipy.sparse.linalg import eigsh
import numpy as np

使用*np.eye()*函数创建一个单位矩阵。

identity_data = np.eye(15)

使用下面的代码找到创建的矩阵的特征值和特征向量。

eigenval, eigenvect = eigsh(identity_data, k=8)

使用下面的代码检查特征值。

eigenval

Scipy Sparse eigsh

Scipy Sparse eigsh

阅读: Python Scipy 最小化【附 8 个例子】

Scipy 稀疏到密集

*dense matrix*是一个矩阵,矩阵内的大部分元素都是非零的,所以这里取 csr matrix ,用函数todense转换成*dense matrix*

下面给出了语法。

csr_matrix.todense(order=None, out=None)

其中参数为:

  • order: 用于指定使用哪些 order,如 row-major(C)和 column-major(F)来存储多维数据。默认情况下,None表示没有订单。
  • out: 用于指定如何像输出缓冲区一样以数组(numpy.matrix)的形式返回结果,而不是在返回结果的同时创建一个新的数组。

让我们以下面的步骤为例:

使用下面的代码导入必要的库。

import numpy as np
from scipy.sparse import csr_matrix

使用下面的代码创建数组。

row_data = np.array([0, 0, 2, 2, 1, 1, 4, 4, 5, 5, 1, 1, 2])
col_data = np.array([0, 3, 1, 0, 6, 1, 6, 3, 5, 3, 1, 4, 3])
array_data = np.array([1]*len(r))

使用下面的代码创建*csr matrix*

csr_mat = csr_matrix(array_data,(row_data,col_data),shape =(6,6))

使用以下代码检查矩阵中的数据类型和存储元素。

csr

使用下面的代码,通过对矩阵*csr_mat*应用 todense() 的方法,将*csr matrix*转换为密集矩阵。

csr_to_dense = csr_mat.todense()

使用以下代码检查密集矩阵*csr_to_dense*的元素。

csr_to_dense

Scipy Sparse to dense

Scipy Sparse to dense

阅读: Python Scipy 指数

熊猫数据帧的稀疏矩阵

这里我们将使用函数csr_matrix()从熊猫数据帧中创建一个稀疏矩阵。

首先,使用下面的代码创建一个新的数据帧。

# importing pandas as pd
import pandas as pd

# Creating the DataFrame
dataf = pd.DataFrame({'Marks':[50, 90, 60, 20, 80],
                 'Age':[14, 25, 55, 8, 21]})

# Create the index
index_ = pd.Series(range(1,6))

# Set the index
dataf.index = index_

# Print the DataFrame
print(dataf)

现在使用下面的代码将上面创建的数据帧转换成稀疏数据帧或矩阵。

# Importing the method csr_matrix()
from scipy.sparse import csr_matrix

# Creating the sparse matrix by passing the values of dataf 
# using dataf.values.T to method csr_matrix()
sparse_matrix_from_dataframe = csr_matrix(dataf.values.T)

# viewing the elements of created sparse matrix
sparse_matrix_from_dataframe.toarray()

Scipy Sparse matrix from pandas dataframe

Scipy Sparse matrix from pandas dataframe

您可能也喜欢阅读下面的 Python SciPy 教程。

因此,在本教程中,我们已经学习了" Scipy Sparse "并涵盖了以下主题。

  • Scipy Sparse rand
  • Scipy Sparse linalg
  • 稀疏 CSR 矩阵
  • 稀疏矩阵到 NumPy 数组
  • Scipy Sparse hstack
  • Scipy 稀疏 coo 矩阵
  • Scipy Sparse eigsh
  • 从稀疏到密集
  • 熊猫数据帧的稀疏矩阵

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Scipy Stats Zscore +示例

原文:https://pythonguides.com/scipy-stats-zscore/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习“ Scipy Stats Zscore ”,此外我们还将涉及以下主题。

  • Scipy Stats 袖珍版
  • Scipy Stats 袖珍南
  • Scipy Stats Zscore axis
  • Scipy Stats Zscore 日志文件
  • Scipy Stats 修改了 Zscore

目录

Scipy 状态的口袋

Python Scipy 有一个存在于模块*scipy.stats*中的方法*zscore()*,该方法计算样本的每个数据点相对于样本平均值的 z 值 。实际上,它是在标准差的帮助下,找出样本的观察值和包含许多观察值的样本的平均值之间的距离。

下面给出了语法。

scipy.stats.zscore(a, axis=0, ddof=0, nan_policy='propagate')

其中参数为:

  • a(数组 _ 数据): 是包含样本观测值的数组数据。
  • 轴(int): 用于指定在哪个轴上计算 z 值。默认情况下,它是 0。
  • ddof(): 确定计算的标准偏差的修正自由度。
  • nan_ploicy: 用于处理数组内存在的 nan 值。它有一些以不同方式处理 nan 值的参数,这些参数是*omit**propagate**raise*

方法*zscore()*返回给定数组的*zscore*作为输入。

让我们通过下面的步骤来了解一个示例:

使用下面的 python 代码导入所需的库。

import numpy as np
from scipy.stats import zscore

使用下面的代码创建一个包含数据点的数组。

array_obs = np.array([ 0.2797,  0.7670,  0.3834,  0.6687,  0.1908,
               0.4591,  0.7036,  0.9956,  0.5601,  0.8050])

现在使用下面的代码将上面创建的数组传递给方法zscore()

zscore(array_obs)

Scipy Stats Zscore

Scipy Stats Zscore

这就是如何计算给定数据数组的 z 值。

阅读: Scipy Ndimage Rotate

Scipy 状态下的袖珍南

在 python Scipy 的上述小节中,我们已经计算了给定数组的 z 值,但是我们也了解了方法*zscore()*的一些参数。方法*zscore()*的参数之一是*nan_policy*处理给定数组中的nan值。nan代表*Not a number*

因此,在这一小节中,我们将了解如何使用该方法的*nan_ploicy*参数来处理数组中的 nan 值,同时计算 z 值。

参数*nan_policy*也有以不同方式处理nan值的选项,这些选项如下所示。

  • 省略: 该选项在跳过给定数组中的 nan 值的同时计算 z 值。
  • 传宗接代: 它显示了楠的价值观。
  • raise: 对于给定数组中的 nan 值抛出错误。

让我们以下面的步骤为例:

使用下面的 python 代码导入所需的库。

import numpy as np
from scipy.stats import zscore

使用下面的代码创建一个包含具有 nan 值的数据点的数组。

array_obs = np.array([ 0.2797,  0.7670,  np.nan,  0.6687,  0.1908,
               0.4591,  0.7036,  np.nan,  0.5601,  np.nan])

在上面的代码中,这里的``np.nan represents the nan values in an是数组。

使用下面的代码将上面的数组传递给参数*nan_policy*等于*omit*的方法。

zscore(array_obs,nan_policy='omit')

Scipy Stats Zscore nan

Scipy Stats Zscore nan

使用下面的代码再次将上面的数组传递给参数*nan_policy*等于*raise*的方法。

zscore(array_obs,nan_policy='raise')

Scipy Stats Zscore nan example

Scipy Stats Zscore nan example

现在,再次使用下面的代码将上面的数组传递给参数*nan_policy*等于*propagate*的方法。

zscore(array_obs,nan_policy='propagate')

Scipy Stats Zscore nan tutorial

Scipy Stats Zscore nan tutorial

这就是如何使用参数*nan_policy*来处理给定数组中的 nan 值。

阅读: Scipy 信号-有用教程

Scipy Stats Zscore axis

在 Python Scipy 的上述小节中,我们使用了方法zscore()的参数*nan_policy*来处理给定数组中的 nan 值。这里我们将使用另一个参数axis来计算给定数组的指定轴上的 z 值。

参数*axis*接受两个值*0**1*,它们代表给定数组的不同轴。默认情况下,该方法计算沿 0 轴的 z 得分。

让我们通过下面的步骤来了解一个示例:

使用下面的 python 代码导入所需的库。

import numpy as np
from scipy.stats import zscore

使用下面的代码创建一个包含数据点的数组。

array_obs = np.array([[ 0.8413,  0.8740,  0.3426,  0.8064],
              [ 0.9417,  0.5770,  0.2706,  0.6569],
              [ 0.1436,  0.3041,  0.9579,  0.4604],
              [ 0.8195,  0.8496,  0.409 ,  0.1273],
              [ 0.1290,  0.1842,  0.8811,  0.6631]])

将数组输入到方法*zscore()*中,使用下面的代码计算 z 值,而不指定轴或默认轴值。

zscore(array_obs)

使用下面的代码再次输入相同的数组和参数值*axis*1

zscore(array_obs,axis=1)

Scipy Stats Zscore axis

Scipy Stats Zscore axis

查看基于指定轴的数组的 z 分值。

阅读: Scipy Integrate +示例

Scipy 状态的袖珍日志

在 python Scipy 的这一小节中,我们将使用日志转换数组,并计算转换后数组的 z 值。

让我们以下面的步骤为例:

使用下面的 python 代码导入所需的库。

import numpy as np
from scipy.stats import zscore

使用下面的代码创建一个包含数据点的数组。

array_obs = np.array([ 0.2797,  0.7670,  0.3834,  0.6687,  0.1908,
               0.4591,  0.7036,  0.9956,  0.5601,  0.8050])

通过使用下面的代码对数组应用 NumPy 的*log*方法,将数组值转换成其他值。

log_array = np.log(array_obs)
log_array

现在使用下面的代码将转换后的数组传递给方法zscore()

zscore(log_array)

Scipy Stats Zscore log

Scipy Stats Zscore log

这就是如何在数组上应用 log,然后应用方法*zscore()*来计算该数组的 z 值。

阅读: Scipy Integrate +示例

Scipy Stats 修改 Zscore

Python Scipy 没有任何方法来计算修改后的 z 得分,修改后的 z 得分使用中值而不是平均值。修正 z 值的公式为*zscore = 0.6745 * (x_data - median) / median_absolute_deviation*

因此,我们将按照以下步骤手动执行修改后的 z 值:

使用下面的 python 代码导入所需的库。

import numpy as np

使用下面的代码创建数组数据作为样本数据点。

array_data = np.array([3,5,6,5,3,6,8,8,4,2])

使用下面的代码计算数组数据的中值。

array_median = np.median(array_data)
array_median

计算每个数据点和中位数之间的绝对差值。

abs_diff = np.abs(array_data-array_median)
abs_diff

通过使用下面的代码找到上述数组中值的中值来计算中值绝对差。

median_abs_diff = np.median(abs_diff)
median_abs_diff

现在应用我们在上面学到的公式,使用下面的代码计算修改后的 z 值。

modified_zscore =  0.6745* (array_data - array_median)/ median_abs_diff
modified_zscore

Scipy Stats Modified Zscore

Scipy Stats Modified Zscore

这就是如何计算修改后的 z 值。

您可能也喜欢阅读下面的 Python Scipy 教程。

因此,在本教程中,我们已经了解了“Scipy Stats Zscore”并涵盖了以下主题。

  • Scipy Stats 袖珍版
  • Scipy Stats 袖珍南
  • Scipy Stats Zscore axis
  • Scipy Stats Zscore 日志文件
  • Scipy Stats 修改了 Zscore

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

scipy Stats–完整指南

原文:https://pythonguides.com/scipy-stats/

Python & Machine Learning training courses

在这个 Python 教程中,我们将使用 Python 中的各种例子来理解“ Scipy Stats 的用法。此外,我们将讨论以下主题。

  • Scipy Stats(科学之州)
  • Scipy 统计对数正常
  • Scipy 状态规范
  • Scipy 状态 t 检验
  • scipy stats pearson(科学怪人)
  • Scipy Stats 卡方检验
  • Scipy 状态下的 IQR
  • 西皮统计鱼
  • 科学统计熵
  • Scipy Stats Anova 的研究
  • 科学统计安德森
  • 科学统计平均值
  • Scipy Stats Alpha 的研究
  • Scipy Stats Boxcox
  • Scipy Stats Binom 的研究
  • scipy stats beta 版
  • Scipy 统计二项式检验
  • Scipy Stats 装箱统计
  • pmf 中的 Scipy 态
  • Scipy 状态下的 CDF
  • scipy stats cauchy(西班牙语)
  • 科学统计描述
  • Scipy 统计指数
  • scipy stats 伽马
  • 科学统计几何
  • scipy stats gmean 公司
  • scipy stats 基因标准
  • scipy stats genpareto 的研究
  • 科学统计 Gumbel
  • 科学统计基因极限
  • Scipy 统计直方图
  • 半正常状态
  • Scipy Stats 半柯西
  • Scipy 统计反伽玛
  • Scipy Stats 逆法线 CDF
  • 科学统计约翰逊
  • Scipy 状态 PDF
  • scipy stats hypergeom 的研究
  • Scipy 统计间隔
  • Scipy 州 ISF
  • Scipy Stats 独立 T 检验
  • Scipy 统计费希尔精确

目录

Scipy Stats 的缩写形式

Scipy 有一个包含大量统计函数的包或模块*scipy.stats*。虽然统计是一个非常广泛的领域,这里的模块包含了一些主要的统计相关的功能。

  • 汇总统计数据
  • 频率统计
  • 统计测试
  • 概率分布
  • 频率统计
  • 相关函数
  • 准蒙特卡罗
  • 屏蔽统计函数
  • 其他统计功能

科学统计对数正常

*Lognormal*代表正态分布形式的对数。它是一个对数正态连续的随机变量。

下面给出了语法。

scipy.stats.lognorm.method_name(data,loc,size,moments,scale)

其中参数为:

  • 数据: 以数组数据的形式表示均匀采样数据的一组点或值。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.lognorm()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . log norm . CDF():用于累计分布函数。
  • scipy . stats . log norm . pdf():用于概率密度函数。
  • scipy . stats . log norm . RVs():获取随机变量。
  • scipy . stats . log norm . stats():用于得到标准差、均值、峰度、偏斜度。
  • scipy . stats . log norm . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . log norm . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . log norm . SF():它用于获取生存函数的值。
  • scipy . stats . log norm . ISF():它用于获取逆生存函数的值。
  • scipy . stats . log norm . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . log norm . mean():用于求分布的均值。
  • scipy . stats . log norm . medain():用于求分布的中位数。
  • scipy . stats . log norm . var():用于求与分布相关的方差。
  • scipy . stats . log norm . STD():用于求分布相关的标准差

阅读: Scipy 常量–多个示例

Scipy 状态规范

*scipy.stats.norm*表示通常连续的随机变量。它有不同种类的正态分布函数,如 CDF,PDF,中位数等。

它有两个重要的参数loc用于表示平均值和scale用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.norm.method_name(data,loc,size,moments,scale)

其中参数为:

  • 数据: 以数组数据的形式表示均匀采样数据的一组点或值。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.norm()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . norm . CDF():它用于累计分布函数。
  • scipy . stats . norm . pdf():它用于概率密度函数。
  • scipy . stats . norm . RVs():获取随机变量。
  • scipy . stats . norm . stats():用于得到标准差、均值、峰度、偏斜度。
  • scipy . stats . norm . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . norm . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . norm . SF():它用于获取生存函数的值。
  • scipy . stats . norm . ISF():它用来得到逆生存函数的值。
  • scipy . stats . norm . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . norm . mean():用于求正态分布相关的均值。
  • scipy . stats . norm . medain():用于求正态分布相关的中位数。
  • scipy . stats . norm . var():用于求与分布相关的方差。
  • scipy . stats . norm . STD():它用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

创建观察数据值,并用*mean = 0**standard deviation = 1*从这些数据值中计算出*probability density function*

observatin_x = np.linspace(-4,4,200)
PDF_norm = stats.norm.PDF(observatin_x,loc=0,scale=1)

使用下面的代码绘制创建的分布图。

plt.plot(observatin_x,PDF_norm)
plt.xlabel('x-values')
plt.ylabel('PDF_norm_values')
plt.title("Probability density funciton of normal distribution")
plt.show()

Scipy Stats Norm

Scipy Stats Norm

看输出,显示的是正态分布的概率密度函数图。

阅读: Scipy 优化–实用指南

Scipy Stats CDF

Scipy stats CDF代表*Comulative distribution function*,它是一个对象*scipy.stats.norm()*的函数。CDF 的范围是从 0 到 1。

下面给出了语法。

scipy.stats.norm.CDF(data,loc,size,moments,scale)

其中参数为:

数据: 以数组数据的形式表示均匀采样数据的一组点或值。
loc: 用来指定平均值,默认为 0。
矩: 用于计算标准差、峰度、均值等统计量。
小数位数: 用于指定标准差,默认为 1。

让我们举一个例子,并使用以下步骤进行计算:

使用下面的代码导入所需的库。

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

创建观察数据值,并用*mean = 0**standard deviation = 1*从这些数据值中计算出*comulative distribution function*

observatin_x = np.linspace(-4,4,200)
CDF_norm = stats.norm.CDF(observatin_x,loc=0,scale=1)

使用下面的代码绘制创建的分布图。

plt.plot(observatin_x,CDF_norm)
plt.xlabel('x-values')
plt.ylabel('CDF_norm_values')
plt.title("Comulative distribution function")
plt.show()

Scipy Stats CDF

Scipy Stats CDF

从上面的输出来看,CDF 是增加的,它告诉我们从总体中选择的任何值都有小于或等于某个值 x 的概率。

阅读:Scipy Sparse–有用的教程

科学统计直方图

Scipy 有一个方法*histogram()*来根据子包*scipy.stats*中的给定值创建直方图。该函数将范围分成几个箱,并返回每个箱中的实例。

下面给出了语法。

scipy.stats.histogram(a, numbins, defaultreallimits, weights)

其中参数为:

  • a(数组): 作为输入提供的数据数组。
  • numbins (int): 用于设置直方图的仓数。
  • defaultreallimits:用于指定直方图的上下限值等范围。
  • 权重(数组): 用于指定数组内每个值的权重。

上面的函数存在于旧版本的 scipy 中,所以这里我们将使用相同的函数,但是它可以直接从 Scipy 模块中访问。让我们以下面的步骤为例。

使用下面的代码导入所需的库。

import numpy as np 
import scipy
import matplotlib.pyplot as plt

通过将数组***[1, 2, 2, 3, 2, 3, 3]***和面元范围*4*传递给函数*histogram()*来生成直方图值和面元。

histogram, bins = scipy.histogram([1, 2, 2, 3, 2, 3, 3],
bins = range(4))

分别查看直方图和条柱的值和大小。

print ("Number of values in each bin : ", histogram)
print ("Size of the bins          : ", bins)

使用下面的代码绘制上面创建的直方图。

plt.bar(bins[:-1], histogram, width = 0.9)
plt.xlim(min(bins), max(bins))
plt.show()

Scipy Stats Histogram

Scipy Stats Histogram

看看上面的输出,这是如何使用 Scipy 创建直方图的。

阅读:Scipy Stats Zscore+Examples

Scipy 州培生公司

*Pearsonr*是皮尔逊相关系数,用于了解两个变量和数据集之间的线性关系。子包*scipy.stats*中的方法*pearsonr()*用于此目的。

下面给出了语法。

scipy.stats.pearsonr(x, y)

其中参数为:

  • x: 它是数组数据。
  • y: 它也是数组数据。

方法*pearsonr()*返回两个值一个*r*(皮尔逊相关系数)和一个*p-value*。在*-1**1*之间的*r*的值,其中*-1*表示强负关系,*1*表示强正关系,如果值等于*0*则表示没有关系。

让我们以下面的步骤为例:

使用下面的代码导入库。

from scipy import stats

现在访问方法*pearsonr()*,并使用下面的代码向其传递两个数组值。

r, p_values = stats.pearsonr([1, 4, 3, 2, 5], [9, 10, 3.5, 7, 5])

使用以下代码检查皮尔逊相关系数和 p 值的值。

print('The Pearson correlation coefficient',r)
print('P-value                            ',p_values)

Scipy Stats Pearsonr

Scipy Stats Pearsonr

阅读:Python Scipy FFT【11 个有用的例子】

Scipy 状态的 PDF

Scipy stats CDF代表*Probability density function*,它是一个对象*scipy.stats.norm()*的函数。PDF 的范围是从 0 到 1。

下面给出了语法。

scipy.stats.norm.PDF(data,loc,size,moments,scale)

其中参数为:

数据: 以数组数据的形式表示均匀采样数据的一组点或值。
loc: 用来指定平均值,默认为 0。
矩: 用于计算标准差、峰度、均值等统计量。
小数位数: 用于指定标准差,默认为 1。

让我们举一个例子,并使用以下步骤进行计算:

使用下面的代码导入所需的库。

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

创建观察数据值,并用*mean = 0**standard deviation = 1*从这些数据值中计算出*probability density function*

observatin_x = np.linspace(-4,4,200)
PDF_norm = stats.norm.pdf(observatin_x,loc=0,scale=1)

使用下面的代码绘制创建的分布图。

plt.plot(observatin_x,PDF_norm)
plt.xlabel('x-values')
plt.ylabel('PDF_norm_values')
plt.title("Probability density function")
plt.show()

Scipy Stats PDF

Scipy Stats PDF

阅读: Matplotlib 另存为 PDF

Scipy Stats 卡方检验

卡方检验测试统计中实际结果和预期结果之间的差异。它用于假设检验。它适用于分类数据。在 scipy 中,子包*scipy.stats*中有一个方法*chisquare*来进行测试。

  • 要使用卡方检验,样本量应大于 13。
  • 如果分类变量中的预期或实际频率非常小,则该测试不起作用。因此,在一个分类变量中至少要保持五个预期的或实际的频率。

下面给出了语法。

scipy.stats.chisquare(f_obs, f_exp=None, ddof=0)

其中参数为:

  • f_obs(数组数据): 是分类变量中观察到的频率。
  • f_exp(数组数据): 是分类变量中的期望频率。
  • ddof(int): 它用来定义*Delta degrees of freedom*

方法*chisquare*测试返回两个浮点值,第一个是卡方检验统计,第二个是 p 值。

让我们以下面的步骤为例:

使用下面的代码从模块*scipy.stats*导入方法*chisquare*

from scipy.stats import chisquare

创建一个双数组类型变量来存储观察到的和预期的频率。将两个数组数据传递给方法*chisquare*以执行卡方检验。

observed_f = [10, 25, 10, 13, 11, 11]
expected_f = [15, 15, 15, 15, 15, 5]
test_value = chisquare(f_obs=observed_f, f_exp=expected_f)

使用下面的代码查看测试结果。

print('The value of chi-squared test statistic: ',test_value[0])
print('The value of p-vale: ',test_value[1])

Scipy Stats chisquare

Scipy Stats chisquare

输出显示了卡方检验的结果。这就是如何使用卡方检验统计值和 p 值对分类数据执行卡方检验,以找出实际数据和观察数据之间的差异。

阅读: Scipy Misc + Examples

IQR 科学统计

*IQR*代表*Interquartile Range*,是第 1 个^((第 25 个^个百分位数)) 与第 个^个个四分位数(第 75 个^个 ) 之差。它用于测量数据的离散度。Scipy 有一个方法*iqr*来计算模块*scipy.stats*中存在的指定轴上的数据*Interquartile Range*

下面给出了语法。

scipy.stats.iqr(x, axis=None, rng=(25, 75), nan_policy='propagate', interpolation='linear')

其中参数为:

  • x(数组数据): 数组或对象被提供给一个方法。
  • 轴(int): 用于指定计算范围的轴。
  • rng(范围[0,100]内的两个值: 用于指定计算范围的百分位数。
  • nan_policy: 它用来处理 nan 值并接受三个值:
  1. 省略: 表示忽略 nan 值计算IQR
  2. propagate: 表示返回 nan 值。
  3. 抛出: 表示为 nan 值抛出一个错误。
  • 插值(字符串): 用于指定要使用的插值方法,如线性、低、高、最近、中点。

方法*iqr*根据所提供的输入返回 ndarray 或 scalar 中的值。

让我们举一个例子,按照下面的步骤计算给定的数组数据*IQR*

使用下面的代码从模块*scipy.stats*导入方法*iqr*

from scipy.stats import iqr

使用创建一个数据数组,并将数据传递给方法*iqr*以计算*IQR*

x_data = np.array([[15, 8, 7], [4, 3, 2]])

iqr(x_data)

Scipy Stats IQR

Scipy Stats IQR

上面的输出显示了给定数组数据的*Interquartile Range*,这就是如何找到数据的*IQR*

阅读: Python NumPy 平均值

科学统计平均值

Scipy 有一个统计方法来计算给定数据的平均值。平均值是所有值的总和除以值的个数。

下面给出了语法。

scipy.mean(array_data,axis)

其中参数为:

  • array_data: 是包含所有元素的数组形式的数据。
  • 轴(int): 用于指定需要计算平均值或均值的轴。

方法mean()返回数组中元素的算术平均值。

让我们按照下面的步骤通过一个例子来理解。

使用下面的代码导入所需的库。

import scipy

创建包含需要计算算术平均值的元素的数组。

array_data = [2,4,6,8,12,23]

通过将创建的数组传递给方法*mean()*来计算其平均值。

scipy.mean(array_data)

Scipy Stats Average

Scipy Stats Average

输出显示了给定数组的平均值。

科学统计熵

首先我们要知道 【什么是熵】 熵是热力学中的一种不确定状态。但是熵的概念已经被统计学所采用,在计算概率时被应用。在统计学中,熵用于评估分布、变量和事件中的信息量。

Scipy 有一个方法*entropy()*来计算分布的熵。

下面给出了方法*entropy()*的语法。

scipy.stats.entropy(pk, qk=None, base=None, axis=0)

其中参数为:

  • pk(数组): 取分布。
  • qk(数组数据): 一般熵被计算的排列。必须是和 pk 一样的形式。
  • 基数(浮点): 用于定义使用哪个对数基数,默认为自然对数基数。
  • 轴(int): 用于指定确定熵的轴。

按照以下步骤演示方法*entropy()*

从模块*scipy.stats*导入方法*entropy()*

from scipy.stats import entropy

*pk*值传递给计算熵的方法。

entropy([8/9, 2/9], base=2)

Scipy Stats Entropy

Scipy Stats Entropy

阅读: Scipy 正态分布

安德森

Anderson-Darling 检验估计样本来自服从特定分布的总体的零假设。Scipy 有一个模块*scipy.stats*的方法*anderson()*用于测试。

下面给出了方法*anderson()*的语法。

scipy.stats.anderson(x, dist='norm')

其中参数为:

  • x(数组 _ 数据): 是样本数据。
  • dist(): 它用来定义要对比测试的分布。它接受以下值。
  1. 标准',
  2. 正在展开,
  3. 物流',
  4. 甘贝尔,
  5. gumbel_l ',
  6. ' gumbel_r ',
  7. 极端 1 '

方法*anderson()*返回统计数据、关键值和重要性级别。

阅读:Scipy Stats Zscore+Examples

Scipy 状态方差分析

Anova 是指检验是否接受零假设或替代假设的方差分析。Scipy 有一个方法*f_oneway*来测试给定的两个或更多组的总体均值相同的假设。

下面给出了语法。

scipy.stats.f_oneway(*args, axis=0)

其中参数为:

  • **** args(array _ data)😗**是 sample_1sample_2 每组的测量。
  • axis(int): 用于指定所提供的数组的轴,作为进行测试的输入。

方法*f_oneway*返回浮点数据类型中的两个值p 值

*让我们按照下面的步骤通过演示来理解。

使用以下步骤从模块*scipy.stats*导入方法*f_oneway*

from scipy.stats import f_oneway
import numpy as np

使用下面的代码创建多维数组。

first_data = np.array([[7.77, 7.03, 5.71],
              [5.17, 7.35, 7.00],
              [7.39, 7.57, 7.57],
              [7.45, 5.33, 9.35],
              [5.41, 7.10, 9.33],
              [7.00, 7.24, 7.44]])
second_data = np.array([[5.35, 7.30, 7.15],
              [5.55, 5.57, 7.53],
              [5.72, 7.73, 5.72],
              [7.01, 9.19, 7.41],
              [7.75, 7.77, 7.30],
              [5.90, 7.97, 5.97]])
third_data = np.array([[3.31, 7.77, 1.01],
              [7.25, 3.24, 3.52],
              [5.32, 7.71, 5.19],
              [7.47, 7.73, 7.91],
              [7.59, 5.01, 5.07],
              [3.07, 9.72, 7.47]])

使用下面的代码将上面创建的数组传递给方法*f_oneway*进行测试。

f_statistic_value, p_value = f_oneway(first_data,second_data,third_data)

使用以下代码检查计算值。

print('The value of F statistic test',f_statistic_value)
print('The value of p-value',p_value)

Scipy Stats Anova

Scipy Stats Anova

本指南使用了使用 Scipy 的 ANOVA 测试。

阅读:二元交叉熵张量流

Scipy Stats T-test

*T-test*用于检验零假设,并计算给定样本均值的*T-test*。在 Scipy 模块*scipy.stats*中有几个*T-test*的方法,但是这里我们将学习一个具体的方法,那就是*ttest_1samp*

下面给出了语法。

scipy.stats.ttest_1samp(a, popmean, axis=0, nan_policy='propagate')

其中参数为:

  • a(array_data): 是独立观测值的样本。
  • popmean(float 或 array_data): 是总体的平均值或期望值。
  • 轴(int): 用于指定测试所在的轴。
  • nan_policy: 它用来处理 nan 值并接受三个值:
  1. 省略: 表示忽略 nan 值计算 IQR。
  2. propagate: 表示返回 nan 值。
  3. 抛出: 表示为 nan 值抛出一个错误。

方法*ttest_1samp*返回两个浮点值,即*t-statistic**pvalue*

让我们以下面的步骤为例:

使用下面的代码从 Scipy 导入所需的库*stats*

from scipy import stats
import numpy as np

使用下面的代码创建一个构造函数来生成一个随机数。

randomnub_gen = np.random.default_rng()

使用下面的代码从特定的分布中创建随机数作为样本。

random_variate_s = stats.norm.rvs(loc=6, scale=11, size=(51, 3), random_state=randomnub_gen)

查看为样本生成的数据或数字。

Scipy Stats T test example

Scipy Stats T-test example

现在对这个生成的随机样本执行T-test,以了解样本是否等于总体均值。

stats.ttest_1samp(random_variate_s, 5.0)

使用下面的代码再次执行总体均值等于零的测试。

stats.ttest_1samp(random_variate_s, 0.0)

Scipy Stats T test

Scipy Stats T test

从上面的输出结果,我们可以根据 统计量p 值 拒绝或接受零假设。

阅读: Scipy Ndimage Rotate

Scipy Stats 半正常

*scipy.stats.halfnorm*表示半正态连续的随机变量。它有不同类型的半正态分布函数,如 CDF,PDF,中位数等。

它有两个重要的参数loc用于表示平均值和scale用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.halfnorm.method_name(data,loc,size,moments,scale)

其中参数为:

  • 数据: 以数组数据的形式表示均匀采样数据的一组点或值。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.halfnorm()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . half norm . CDF():用于累计分布函数。
  • scipy . stats . half norm . pdf():用于概率密度函数。
  • scipy . stats . half norm . RVs():获取随机变量。
  • scipy . stats . half norm . stats():用于得到标准差、均值、峰度、偏斜度。
  • scipy . stats . half norm . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . half norm . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . half norm . SF():它用于获取生存函数的值。
  • scipy . stats . half norm . ISF():它用于获取逆生存函数的值。
  • scipy . stats . half norm . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . half norm . mean():用于求正态分布相关的均值。
  • scipy . stats . half norm . medain():用于求正态分布相关的中位数。
  • scipy . stats . half norm . var():用于求与分布相关的方差。
  • scipy . stats . half norm . STD():用于求分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

创建观察数据值,并用*mean = 0**standard deviation = 1*从这些数据值中计算出*probability density function*

observatin_x = np.linspace(-4,4,200)
PDF_norm = stats.norm.PDF(observatin_x,loc=0,scale=1)

使用下面的代码绘制创建的分布图。

plt.plot(observatin_x,PDF_norm)
plt.xlabel('x-values')
plt.ylabel('PDF_norm_values')
plt.title("Probability density funciton of half normal distribution")
plt.show()

Scipy Stats Half normal

Scipy Stats Half normal

看上面的输出,看起来是半正态分布。

阅读: Python Scipy 最小化

Scipy 的 Cauchy 状态

*Cauchy*是类似正态分布的分布,属于连续概率分布的成员。与正态分布相比,它具有更高的峰值。

下面给出了语法。

scipy.stats.cauchy.method_name(data,loc,scale)

其中参数为:

  • 数据: 以数组数据的形式表示均匀采样数据的一组点或值。
  • loc: 用于指定平均值,默认为 0。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.cauchy()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . Cauchy . CDF():它用于累积分布函数。
  • scipy . stats . Cauchy . pdf():它用于概率密度函数。
  • scipy . stats . Cauchy . RVs():获取随机变量。
  • scipy . stats . Cauchy . stats():它用于得到标准差、均值、峰度和偏斜度。
  • scipy . stats . Cauchy . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . Cauchy . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . Cauchy . SF():它用于获取生存函数的值。
  • scipy . stats . Cauchy . ISF():它用来得到逆生存函数的值。
  • scipy . stats . Cauchy . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . Cauchy . mean():用于求与正态分布相关的均值。
  • scipy . stats . Cauchy . medain():用于求正态分布相关的中位数。
  • scipy . stats . Cauchy . var():用于求与分布相关的方差。
  • scipy . stats . Cauchy . STD():它用于求与分布相关的标准差

让我们以下面的步骤为例:

使用下面的代码导入方法cauchy*numpy**matplotlib*

from scipy.stats import cauchy
import matplotlib.pyplot as plt
import numpy as np

使用下面的代码创建一个 cauchy 发行版。

fig, ax = plt.subplots(1, 1)
x = np.linspace(cauchy.ppf(0.02),
                cauchy.ppf(0.98), 99)
ax.plot(x, cauchy.PDF(x),
       'r-', lw=5, alpha=0.6, label='cauchy PDF')

Scipy Stats Cauchy

Scipy Stats Cauchy

看看上面的输出,这是柯西看起来像一个正态分布,但有一个更高的峰值。

阅读: Python Scipy 置信区间

Scipy Stats 半柯西

*HalfCauchy*是一种类似半正态分布的分布,属于连续概率分布的成员。与半正态分布相比,它具有更高的峰值。

下面给出了语法。

scipy.stats.halfcauchy.method_name(data,loc,scale)

其中参数为:

  • 数据: 以数组数据的形式表示均匀采样数据的一组点或值。
  • loc: 用于指定平均值,默认为 0。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.halfcauchy()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . half Cauchy . CDF():它用于累积分布函数。
  • scipy . stats . half Cauchy . pdf():它用于概率密度函数。
  • scipy . stats . half Cauchy . RVs():获取随机变量。
  • scipy . stats . half Cauchy . stats():用于得到标准差、均值、峰度、偏斜度。
  • scipy . stats . half Cauchy . log pdf():用于获取概率密度函数相关的对数。
  • scipy . stats . half Cauchy . log CDF():用于查找与累积分布函数相关的日志。
  • scipy . stats . half Cauchy . SF():它用于获取生存函数的值。
  • scipy . stats . half Cauchy . ISF():它用于获取逆生存函数的值。
  • scipy . stats . half Cauchy . logsf():用于查找与生存函数相关的日志。
  • scipy . stats . half Cauchy . mean():用于求正态分布相关的均值。
  • scipy . stats . half Cauchy . medain():用于求正态分布相关的中位数。
  • scipy . stats . half Cauchy . var():用于求与分布相关的方差。
  • scipy . stats . half Cauchy . STD():用于求与分布相关的标准差

让我们以下面的步骤为例:

使用下面的代码导入方法halfcauchy*numpy**matplotlib*

from scipy.stats import halfcauchy
import matplotlib.pyplot as plt
import numpy as np

使用下面的代码创建一个 halfcauchy 发行版。

fig, ax = plt.subplots(1, 1)
x = np.linspace(halfcauchy.ppf(0.02),
                halfcauchy.ppf(0.98), 99)
ax.plot(x, halfcauchy.PDF(x),
       'r-', lw=5, alpha=0.6, label='cauchy PDF')

Scipy Stats Half cauchy

Scipy Stats Half cauchy

Scipy 状态绑定

*scipy.stats.binom*代表离散随机变量。它有不同种类的正态分布函数,如 CDF,PDF,中位数等。

它有一个用于改变分布的重要参数loc

下面给出了语法。

scipy.stats.binom.method_name(k,n,p,loc)

其中参数为:

  • **k(int):**用来定义成功的次数。
  • **n(int):**用于指定试验的次数。
  • **p(浮点):** 它用于指定假定的成功概率。
  • **loc:**它用来指定平均值,默认为 0。

以上参数是对象*scipy.stats.binom()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . binom . CDF():用于累计分布函数。
  • **二项式*** 。rvs()😗** 获取随机变量。
  • **二项式*** 。stats()😗** 用于获取标准差、均值、峰度、偏斜度。
  • **二项式*** 。logPDF()😗** 用于获取与概率密度函数相关的对数。
  • **二项式*** 。logCDF()😗** 用于查找与累积分布函数相关的日志。
  • **二项式*** 。sf()😗** 用来获取生存函数的值。
  • **二项式*** 。isf()😗** 它用于获取逆生存函数的值。
  • **二项式*** 。logsf()😗** 用于查找生存函数相关的日志。
  • **二项式*** 。mean()😗** 用于求正态分布相关的均值。
  • **二项式*** 。medain()😗** 用于求正态分布相关的中位数。
  • **二项式*** 。var()😗** 用于求分布相关的方差。
  • **二项式*** 。std()😗** 用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import binom
import matplotlib.pyplot as plt

使用以下代码定义参数n p的值。

p,n =0.3,4

使用对象*binom*的方法*ppf()*(百分点函数)创建一个数据数组。

array_data = np.arange(binom.ppf(0.02, n, p),
              binom.ppf(0.98, n, p))
array_data

使用下面的代码显示概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(x, binom.pmf(x, n, p), 'bo', ms=7, label='binom pmf')
ax.vlines(x, 0, binom.pmf(x, n, p), colors='b', lw=6, alpha=0.5)

Scipy Stats Binom

Scipy Stats Binom

科学统计描述

Scipy 在模块*scipy.stats*中有一个方法*describe()*来查找给定数据的描述性统计信息。

下面给出了语法。

scipy.stats.describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate')

其中参数为:

  • a(数组 _ 数据): 是数组类型的数据。
  • 轴(int): 用于指定统计的轴,默认显示整个数组的描述性统计。
  • ddof(int): 它用来指定自由度的增量。
  • 偏差(布尔): 它用来指定偏差。
  • nan_policy: 它用来处理 nan 值并接受三个值:
  1. 省略: 表示忽略 nan 值计算 IQR。
  2. propagate: 表示返回 nan 值。
  3. 抛出: 表示为 nan 值抛出一个错误。

方法*descibe()*以 ndarray 或 float 类型返回mean``skewness``kurtosis*variance*

让我们以下面的步骤为例:

使用下面的代码导入所需的库。

from scipy import stats
import numpy as np

使用下面的代码创建一个包含 20 个观察值的数组。

array_data = np.arange(20)

将上面创建的数组传递给方法describe(),使用下面的代码查找描述性统计数据。

result = stats.describe(array_data)
result

让我们使用下面的代码来查看数组的每个统计数据。

print('Number of observation in array',result[0])
print('Minimum and maximum values in a array',result[1])
print('Mean of the array',result[2])
print('Variance of the array',result[3])
print('Skewness of the array',result[4])
print('Kurtosis of the array',result[5])

Scipy Stats Describe

Scipy Stats Describe

Scipy Stats 二项式检验

二项式检验通过进行许多只存在两种可能结果的试验来寻找特定结果的概率。它用于零假设检验,以评估伯努利实验中结果的概率。

Scipy 有一个方法*binomtest()*来执行存在于模块*scipy.stats*中的二项式测试。

下面给出了语法。

scipy.stats.binomtest(k, n, p=0.5, alternative='two-sided')

其中参数为:

  • k(int): 用于定义成功的次数。
  • n(int): 用于指定试验的次数。
  • p(浮点): 用于指定假设的成功概率。
  • 备选: 它用来指定备选假设。

方法***binomtest()*** 返回 float 类型的*p-value**proportion_estimate*值,还有一个结果*proportion_ci*以知道估计的置信区间。

让我们按照下面的步骤通过一个例子来理解。

使用下面的代码从模块*scipy.stats*导入方法*binomtest()*

from scipy.stats import binomtest

现在,一家手机制造商声称,他们的手机不安全的比例不超过 15%。检查了 20 部手机的安全性,发现 6 部不安全。检验制造商的声明。

Test_result = binomtest(6, n=20, p=0.1, alternative='greater')

使用下面的代码查看结果。

print('The p-value is ',Test_result.pvalue)
print('The estimated proportion is 6/20 ',Test_result.proportion_estimate)
print('The confidence interval of the estimate ',Test_result.proportion_ci(confidence_level=0.95))

Scipy Stats Binomial test

Scipy Stats Binomial test

PMF 结合的 Scipy 状态

在 Scipy 中,模块*scipy.stats*中有一个方法*binom.pmf()*使用二项式分布显示概率质量函数。

下面给出了语法。

scipy.stats.binom.pmf(k,n, p,loc=0)

其中参数为:

  • k(int): 用于定义成功的次数。
  • n(int): 用于指定试验的次数。
  • p(浮点): 用于指定假设的成功概率。
  • loc: 用于指定平均值,默认为 0。

为了用一个例子来理解,请参考上面的小节*Scipy Stats Binom*,其中代表概率质量函数的方法pmf被用在这个例子中。

Scipy Stats gmean

Scipy 的模块*scipy.stats.mstats*的方法*gmean()*根据指定的轴找到给定数组的几何平均值。

下面给出了语法。

scipy.stats.mstats.gmean(a, axis=0, dtype=None, weights=None)

其中参数为:

  • a(array_data): 它是一个数组或数组数据内元素的集合。
  • axis(int): 用来指定我们要求几何平均值的数组的轴。
  • dtype: 用于指定返回数组的数据类型。
  • 权重(array_data): 它用来指定值的权重,默认情况下数组中值的权重为 1.0。

方法*gmean()*返回*gmean*,这是一个类型为*ndarray*的传递数组的几何平均值。

让我们按照下面的步骤通过一个例子来理解。

使用下面的代码导入所需的库。

from scipy.stats.mstats import gmean

使用下面的代码找出数组***[2,4,6,8]***的几何平均值。

gmean([2,4,6,8])

Scipy Stats gmean

Scipy Stats gmean

科学统计 Alpha

*scipy.stats.alpha*表示本质上连续的随机变量。它有不同种类的分布函数,如 CDF,PDF,中位数等。

它有两个重要的参数*loc*用于表示平均值和*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.alpha.method_name(q,x,a,loc,size,moments,scale)

其中参数为:

  • x: 它用来定义分位数。
  • 答: 用于定义形状参数。
  • q: 用来指定概率的尾部像上下。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.alpha()*中所有方法的公共参数。下面给出了方法。

  • scipy . statsαCDF():它用于累积分布函数。
  • **阿尔法*** 。PDF()😗** 用于概率密度函数。
  • **阿尔法*** 。rvs()😗** 获取随机变量。
  • **阿尔法*** 。stats()😗** 用于获取标准差、均值、峰度、偏斜度。
  • **阿尔法*** 。logPDF()😗** 用于获取与概率密度函数相关的对数。
  • **阿尔法*** 。logCDF()😗** 用于查找与累积分布函数相关的日志。
  • **阿尔法*** 。sf()😗** 用来获取生存函数的值。
  • **阿尔法*** 。isf()😗** 它用于获取逆生存函数的值。
  • **阿尔法*** 。logsf()😗** 用于查找生存函数相关的日志。
  • **阿尔法*** 。mean()😗** 用于求正态分布相关的均值。
  • **阿尔法*** 。medain()😗** 用于求正态分布相关的中位数。
  • **阿尔法*** 。var()😗** 用于求分布相关的方差。
  • **阿尔法*** 。std()😗** 用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import alpha
import matplotlib.pyplot as plt
import numpy as np

为形状参数创建一个变量,并指定一些值。

a = 4.3

使用下面的代码,使用对象*alpha*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(alpha.ppf(0.01, a),
                alpha.ppf(0.90, a), 90)
array_data

Scipy Stats Alpha example

Scipy Stats Alpha example

现在使用下面的代码通过访问模块*scipy.stats*的对象*alpha*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, alpha.PDF(array_data, a),
       'r-', lw=4, alpha=0.5, label='alpha PDF')

Scipy Stats Alpha

Scipy Stats Alpha

Scipy 状态测试台

*scipy.stats.beta*表示本质上连续的随机变量。它有不同种类的分布函数,如 CDF,PDF,中位数等。

它有两个重要的参数*loc*用于表示平均值和*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.beta.method_name(q,x,a,loc,size,moments,scale)

其中参数为:

  • x: 它用来定义分位数。
  • a、b: 用于定义形状参数。
  • q: 用来指定概率的尾部像上下。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.beta()*中所有方法的公共参数。下面给出了方法。

  • scipy . statsβCDF():它用于累积分布函数。
  • *贝塔** 。PDF()😗** 用于概率密度函数。
  • *贝塔** 。rvs()😗** 获取随机变量。
  • *贝塔** 。stats()😗** 用于获取标准差、均值、峰度、偏斜度。
  • *贝塔** 。logPDF()😗** 用于获取与概率密度函数相关的对数。
  • *贝塔** 。logCDF()😗** 用于查找与累积分布函数相关的日志。
  • *贝塔** 。sf()😗** 用于获取生存函数值。
  • *贝塔** 。isf()😗** 用于获取逆生存函数值。
  • *贝塔** 。logsf()😗** 用于查找与生存函数相关的日志。
  • *贝塔** 。mean()😗** 用于求正态分布相关的均值。
  • *贝塔** 。medain()😗** 用于求正态分布相关的中位数。
  • *贝塔** 。var()😗** 用于求与分布相关的方差。
  • *贝塔** 。std()😗** 用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import beta
import matplotlib.pyplot as plt
import numpy as np

为形状参数创建两个变量 a 和 b,并指定一些值。

a = 3.4
b = 0.763

使用下面的代码,使用对象*beta*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(beta.ppf(0.01, a,b),
                beta.ppf(0.90, a,b), 90)
array_data

Scipy Stats Beta example

Scipy Stats Beta example

现在使用下面的代码通过访问模块*scipy.stats*的对象*beta*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, beta.PDF(array_data, a,b),
       'r-', lw=4, alpha=0.5, label='alpha PDF')

Scipy Stats Beta

Scipy Stats Beta

Scipy 状态下的 Gamma

*scipy.stats.gamma*表示本质上连续的随机变量。它有不同种类的分布函数,如 CDF,PDF,中位数等。

它有两个重要的参数*loc*用于表示平均值和*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.gamma.method_name(q,x,a,loc,size,moments,scale)

其中参数为:

  • x: 它用来定义分位数。
  • 答: 用于定义形状参数。
  • q: 用来指定概率的尾部像上下。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.gamma()*中所有方法的公共参数。下面给出了方法。

  • scipy . statsγCDF():它用于累积分布函数。
  • 。PDF(): 用于概率密度函数。
  • 。rvs(): 获取随机变量。
  • 。stats(): 用于获取标准差、均值、峰度、偏斜度。
  • 。logPDF(): 用于获取与概率密度函数相关的日志。
  • 。logCDF(): 用于查找与累积分布函数相关的日志。
  • 。sf(): 用于获取生存函数值。
  • 。isf(): 用于获取逆生存函数值。
  • 。logsf(): 用于查找与生存函数相关的日志。
  • 。mean(): 用于求正态分布相关的均值。
  • 。medain(): 用于求正态分布相关的中位数。
  • 。var(): 用于求与分布相关的方差。
  • 。std(): 用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import gamma
import matplotlib.pyplot as plt
import numpy as np

代码为形状参数创建一个变量,并分配一些值。

a = 1.95

使用下面的代码,使用对象*gamma*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(gamma.ppf(0.01, a),
                gamma.ppf(0.90, a,b), 90)
array_data

Scipy Stats Gamma example

Scipy Stats Gamma example

现在使用下面的代码通过访问模块*scipy.stats*的对象*gamma*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, gamma.PDF(array_data, a),
       'r-', lw=4, alpha=0.5, label='alpha PDF')

Scipy Stats Gamma

Scipy Stats Gamma

Scipy Stats 逆法线 CDF

在这里,我们将了解常态的逆Cumulative distribution function。从上面的小节' Scipy Stats Norm' 中我们已经了解了 normal。所以这里将使用方法*ppf()*,它表示 Scipy 的对象*scipy.statst.norm**CDF*的逆。

scipy.stats.norm.ppf(q,loc,scale)

其中参数为:

  • q: 它用来指定分位数。
  • loc: 用于指定平均值,默认为 0。
  • 刻度: 用于指定标准差,默认为 1。

让我们按照下面的步骤举个例子。

使用下面的代码导入库*stats*

from scipy import stats

使用下面的代码求CDF的倒数。

stats.norm.CDF(stats.norm.ppf(0.7))

Scipy Stats Inverse Normal CDF

Scipy Stats Inverse Normal CDF

约翰逊

*scipy.stats*包含属于约翰逊分布族的两个对象*johnsonsb()**johnsonub()*。它有不同种类的分布函数,如 CDF,PDF,中位数等。

  • 方法*johnsonsb()*表示有界连续概率分布,而*johnsonub()*是无界连续概率分布。

它有两个重要的参数*loc*用于表示平均值和*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.alpha.method_name(q,x,a,loc,size,moments,scale)

其中参数为:

  • x: 它用来定义分位数。
  • a、b: 用于定义形状参数。
  • q: 用来指定概率的尾部像上下。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import gamma
import matplotlib.pyplot as plt
import numpy as np

代码为形状参数创建两个变量 a 和 b,并分配一些值。

a,b = 3.35,2.25

使用下面的代码,使用对象*johnsonsb*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(johnsonsb.ppf(0.01, a,b),
                johnsonsb.ppf(0.90, a,b), 90)
array_data

Scipy Stats Johnson example

Scipy Stats Johnson example

现在使用下面的代码通过访问模块*scipy.stats*的对象*johnsonsb*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, johnsonsb.PDF(array_data, a,b),
       'r-', lw=4, alpha=0.5, label='johnsonsb PDF')

Scipy Stats Johnson

Scipy Stats Johnson

我们还可以使用与我们用于约翰逊的 有界连续概率分布 相同的过程来找到 约翰逊的 无界连续概率分布的分布。

科学统计反伽玛

*scipy.stats.invgamma*表示本质上连续的反向随机变量。它有不同种类的分布函数,如 CDF,PDF,中位数等。

它有两个重要的参数*loc*用于表示平均值和*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.invgamma.method_name(q,x,a,loc,size,moments,scale)

其中参数为:

  • x: 它用来定义分位数。
  • 答: 用于定义形状参数。
  • q: 用来指定概率的尾部像上下。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.invgamma()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . inv gamma . CDF():用于累计分布函数。
  • ***invgamma``***。PDF(): 用于概率密度函数。
  • ***invgamma``***。rvs(): 获取随机变量。
  • ***invgamma``***。stats(): 用于获取标准差、均值、峰度、偏斜度。
  • ***invgamma``***。logPDF(): 用于获取与概率密度函数相关的日志。
  • ***invgamma``***。logCDF(): 用于查找与累积分布函数相关的日志。
  • ***invgamma``***。sf(): 用于获取生存函数值。
  • ***invgamma``***。isf(): 用于获取逆生存函数值。
  • ***invgamma``***。logsf(): 用于查找与生存函数相关的日志。
  • ***invgamma``***。mean(): 用于求正态分布相关的均值。
  • ***invgamma``***。medain(): 用于求正态分布相关的中位数。
  • ***invgamma``***。var(): 用于求与分布相关的方差。
  • ***invgamma``***。std(): 用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import invgamma
import matplotlib.pyplot as plt
import numpy as np

代码为形状参数创建一个变量,并分配一些值。

a = 3.04

使用下面的代码,使用对象*invgamma*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(invgamma.ppf(0.01, a),
                invgamma.ppf(0.90, a,b), 90)
array_data

Scipy Stats Inverse gamma example

Scipy Stats Inverse gamma example

现在使用下面的代码通过访问模块*scipy.stats*的对象*invgamma*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, invgamma.PDF(array_data, a),
       'r-', lw=4, alpha=0.5, label='invgamma PDF')

Scipy Stats Inverse gamma

Scipy Stats Inverse gamma

Scipy 状态基因规范

*scipy.stats.gennorm*表示本质上是广义正态连续的随机变量。它有不同种类的正态分布函数,如 CDF,PDF,中位数等。

它有两个重要的参数loc用于表示平均值和scale用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.gennorm.method_name(x,beta,loc,size,moments,scale)

其中参数为:

  • x: 它是以数组数据的形式表示均匀采样数据的一组点或值。
  • beta: 它用来指定形状。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.gennorm()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . gen norm . CDF():用于累计分布函数。
  • **艮*** 常态。PDF()😗** 用于概率密度函数。
  • gennorm . RVs():得到随机变量。
  • scipy . stats .gennorm . stats():**它用于获取标准差、均值、峰度和偏斜度。
  • scipy . stats .gennorm . log pdf():**它用于获取与概率密度函数相关的对数。
  • scipy . stats .gennorm . log CDF():**用于查找与累积分布函数相关的日志。
  • scipy . stats .gennorm . SF():**它用来获取生存函数的值。
  • scipy . stats .gennorm . ISF():**它用来获取逆生存函数的值。
  • scipy . stats .gennorm . logsf():**用于查找与生存函数相关的日志。
  • scipy . stats .gennorm . mean():**用于求与正态分布相关的均值。
  • scipy . stats .gennorm . medain():**用于求正态分布相关的中位数。
  • scipy . stats .gennorm . var():**它用于求与分布有关的方差。
  • scipy . stats .gennorm . STD():**它用于查找与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import gennorm
import matplotlib.pyplot as plt
import numpy as np

代码为形状参数创建一个变量,并分配一些值。

beta = 1.4

使用下面的代码,使用对象*gennorm*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(gennorm.ppf(0.01, a),
                gennorm.ppf(0.90, a,b), 90)
array_data

Scipy Stats Gennorm

Scipy Stats Gennorm

现在使用下面的代码通过访问模块*scipy.stats*的对象*gennorm*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, gennorm.PDF(array_data, beta),
       'r-', lw=4, alpha=0.5, label='gennorm PDF')

Scipy Stats Gennorm example

Scipy Stats Gennorm example

Scipy 状态基因帕累托

*scipy.stats.genpareto*表示本质上连续的广义帕累托随机变量。它有不同种类的正态分布函数,如 CDF,PDF,中位数等。

它有两个重要的参数loc用于表示平均值和scale用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.genpareto.method_name(x,c,loc,size,moments,scale)

其中参数为:

  • x: 它是以数组数据的形式表示均匀采样数据的一组点或值。
  • c: 它用来指定形状。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.genpareto()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . gen Pareto . CDF():用于累计分布函数。
  • 。PDF(): 用于概率密度函数。
  • *。rvs()😗*** 获取随机变量。*
  • **。stats()😗*** 用于获取标准差、均值、峰度、偏斜度。**
  • **。logPDF()😗*** 用于获取与概率密度函数相关的对数。**
  • **。logCDF()😗*** 用于查找与累积分布函数相关的日志。**
  • **。sf()😗*** 用来获取生存函数的值。**
  • **。isf()😗*** 它用于获取逆生存函数的值。**
  • **。logsf()😗*** 用于查找生存函数相关的日志。**
  • **。mean()😗*** 用于求正态分布相关的均值。**
  • **。medain()😗*** 用于求正态分布相关的中位数。**
  • **。var()😗*** 用于求分布相关的方差。**
  • **。std()😗*** 用于求与分布相关的标准差**

**让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import genpareto
import matplotlib.pyplot as plt
import numpy as np

代码为形状参数创建一个变量,并分配一些值。

c = 0.2

使用下面的代码,使用对象*genpareto*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(genpareto.ppf(0.01, c),
                genpareto.ppf(0.90, c), 90)
array_data

Scipy Stats Genpareto example

Scipy Stats Genpareto example

现在使用下面的代码通过访问模块*scipy.stats*的对象*genpareto*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, genpareto.PDF(array_data, c),
       'r-', lw=4, alpha=0.5, label='genpareto PDF')

Scipy Stats Genpareto

Scipy Stats Genpareto

科学统计 Gumbel

*scipy.stats*包含两个对象*gumbel_r()**gumbel_l()*,用于模拟左偏或右偏分布。它有不同种类的分布函数,如 CDF,PDF,中位数等。

  • 方法***gumbel_r()*** 表示右偏 Gumbel 连续分布,而***gumbel_l()*** 是左偏 Gumbel 连续分布。

它有两个重要的参数*loc*用于表示平均值和*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.gumbel_r.method_name(q,x,a,loc,size,moments,scale)

其中参数为:

  • x: 它用来定义分位数。
  • a、b: 用于定义形状参数。
  • q: 用来指定概率的尾部像上下。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import gumbel_r
import matplotlib.pyplot as plt
import numpy as np

使用下面的代码,使用对象*gumbel_r*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(gumbel_r.ppf(0.01, a,b),
                gumbel_r.ppf(0.90, a,b), 90)
array_data

Scipy Stats Gumbel example

Scipy Stats Gumbel example

现在使用下面的代码通过访问模块*scipy.stats*的对象*gumbel_r*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, gumbel_r.PDF(array_data),
       'r-', lw=4, alpha=0.5, label='gumbel PDF')

Scipy Stats 入库统计数据

Scipy 子模块*scipy.stats*包含一个方法*binned_statistic*,用于计算每个 bin 的平均值、中值、总和等统计数据。

下面给出了语法。

scipy.stats.binned_statistic(x, values, statistic='mean', bins=10, range=None)

码头参数为:

  • x(array_data): 它是被装箱的值序列。
  • 数值(array_data,list(N)): 是用来计算统计量的数值。
  • statistic(string):用于指定我们要计算的统计类型,如均值、总和、中值、最大值、标准差和计数。
  • bin(序列或整数): 用于定义 bin 的数量。
  • 范围((float,float)): 定义仓位的下限和上限范围。

方法*binned_statistic*返回数组类型的面元和绑定边的统计数据。

让我们通过下面的步骤来了解一个示例:

使用下面的代码导入所需的库。

from scipy import stats

使用下面的代码创建一组值并计算入库的统计数据。

set_values = [2.0, 2.0, 3.0, 2.5, 4.0]
stats.binned_statistic([2, 2, 3, 6, 8], set_values, 'mean', bins=2)

Scipy Stats Binned statistics

Scipy Stats Binned statistics

Scipy Stats Poisson

*scipy.stats.poisson*表示本质上离散的随机变量。它有不同种类的分布函数,如 CDF、中位数等。

它有一个重要的参数*loc*,用于使用这些参数移动分布的平均值。

下面给出了语法。

scipy.stats.gamma.method_name(mu,k,loc,moments)

其中参数为:

  • mu: 用于定义形状参数。
  • k: 它是数据。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。

以上参数是对象*scipy.stats.poisson()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . poisson . CDF():它用于累积分布函数。
  • *******阿松****。rvs()😗** 获取随机变量。
  • *******阿松****。stats()😗** 用于获取标准差、均值、峰度、偏斜度。
  • *******阿松****。logPDF()😗** 用于获取与概率密度函数相关的日志。
  • *******阿松****。logCDF()😗** 用于查找与累积分布函数相关的日志。
  • *******阿松****。sf()😗** 用于获取生存函数值。
  • *******阿松****。isf()😗** 用于获取逆生存函数值。
  • *******阿松****。logsf()😗** 用于查找与生存函数相关的日志。
  • *******阿松****。mean()😗** 用于求正态分布相关的均值。
  • *******阿松****。medain()😗** 用于求正态分布相关的中位数。
  • *******阿松****。var()😗** 用于求与分布相关的方差。
  • *******阿松****。std()😗** 用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import poisson
import matplotlib.pyplot as plt
import numpy as np

代码为形状参数创建一个变量,并分配一些值。

mu = 0.5

使用下面的代码,使用对象*poisson*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(poisson.ppf(0.01, mu),
                poisson.ppf(0.90, mu))
array_data

Scipy Stats Poisson example

Scipy Stats Poisson example

现在使用下面的代码通过访问模块*scipy.stats*的对象*poisson*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, poisson.pmf(array_data, mu), 'bo',ms=8,label='poisson pmf')
ax.vlines(array_data, 0,poisson.pmf(array_data, mu),colors='b', lw=4, alpha=0.5,)

Scipy Stats Poisson

Scipy Stats Poisson

这就是如何使用 Scipy 的分箱统计数据。

科学统计几何

*scipy.stats.geom*表示本质上离散的随机变量。它有不同种类的几何分布函数,如 CDF,PDF,中位数等。

平均值有一个重要的参数loc,我们知道我们使用这些参数来控制分布的形状。

下面给出了语法。

scipy.stats.geom.method_name(k,p,q,loc,size)

其中参数为:

  • k(float 或 float of array_data): 用于指定伯努利试验。
  • p(float 或 array_data 的 float):用于指定每次尝试的成功概率。
  • q(float 或 array_data 的 float):它表示概率。
  • loc: 用于指定平均值,默认为 0。

以上参数是对象*scipy.stats.geom()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . geom . CDF():用于累计分布函数。
  • **几何*** 。PDF()😗** 用于概率密度函数。
  • **几何*** 。rvs()😗** 获取随机变量。
  • **几何*** 。stats()😗** 用于获取标准差、均值、峰度、偏斜度。
  • **几何*** 。logPDF()😗** 用于获取与概率密度函数相关的对数。
  • **几何*** 。logCDF()😗** 用于查找与累积分布函数相关的日志。
  • **几何*** 。sf()😗** 用来获取生存函数的值。
  • **几何*** 。isf()😗** 它用于获取逆生存函数的值。
  • **几何*** 。logsf()😗** 用于查找生存函数相关的日志。
  • **几何*** 。mean()😗** 用于求正态分布相关的均值。
  • **几何*** 。medain()😗** 用于求正态分布相关的中位数。
  • **几何*** 。var()😗** 用于求分布相关的方差。
  • **几何*** 。std()😗** 用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import geom
import numpy as np
import matplotlib.pyplot as plt 

使用下面的代码创建一个包含 30 个值的数组,并创建一个包含每次试验成功概率的变量。

array_data = np.arange(1,30,1)
p = 0.5

现在使用下面的代码,通过访问模块*scipy.stats*的对象*geom*的方法*pmf()*来绘制概率密度函数。

geom_pmf_data = geom.pmf(array_data,p)
plt.plot(array_data,geom_pmf_data,'bo')
plt.show()

Scipy Stats Geometric

Scipy Stats Geometric

科学统计指数

*scipy.stats.expon*表示本质上连续的随机变量。它有不同种类的指数分布函数,如 CDF、PDF、中位数等。

它有两个重要的参数*loc*用于表示平均值和*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.expon.method_name(x,q,loc,scale,size)

其中参数为:

  • x(数组 _ 数据的浮点或浮点): 用于指定随机变量。
  • q(float 或 float of array_data): 表示概率。
  • loc: 用于指定平均值,默认为 0。
  • 标度 :用于指定标准差,默认为 1。
  • 尺寸: 它用来指定输出形状。

以上参数是对象*scipy.stats.expon()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . expon . CDF():用于累计分布函数。
  • scipy . stats . expon . pdf():它用于概率密度函数。
  • scipy . stats . expon . RVs():获取随机变量。
  • scipy . stats . expon . stats():用于获取标准差、均值、峰度、偏斜度。
  • scipy . stats . expon . log pdf():用于获取概率密度函数相关的日志。
  • scipy . stats . expon . log CDF():用于查找与累积分布函数相关的日志。
  • ***``expon*。sf(): 用于获取生存函数值。
  • ***``expon*。isf(): 用于获取逆生存函数值。
  • ***``expon*。logsf(): 用于查找与生存函数相关的日志。
  • ***``expon*。mean(): 用于求正态分布相关的均值。
  • ***``expon*。medain(): 用于求正态分布相关的中位数。
  • ***``expon*。var(): 用于求与分布相关的方差。
  • ***``expon*。std(): 用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import expon
import numpy as np
import matplotlib.pyplot as plt 

使用下面的代码创建一个包含 30 个值的数组。

array_data = np.arange(-1,30,0.1)

现在使用下面的代码通过访问模块*scipy.stats*的对象*expon*的方法*PDF()*来绘制概率密度函数。

expon_PDF_data = expon.PDF(array_data,0,2)
plt.plot(array_data,expon_PDF_data,'bo')
plt.show()

Scipy Stats Exponential

Scipy Stats Exponential

Scipy Stats Boxcox

Scipy 子模型有一个将非正常数据集转换成正常数据集的方法*boxcox()*

下面给出了语法,

scipy.stats.boxcox(x, lmbda=None, alpha=None, optimizer=None)

其中参数为:

  • x(array_data): 应该是正的一维的输入数组数据。
  • lambda(scaler): 对数值进行变换。
  • alpha(浮点): 返回λ的置信区间。
  • 优化器: 如果没有设置 lambda,那么优化器会找到 lambda 的值。

方法*boxcox()*返回两个值 ndarray 类型的 boxcox 和 float 类型的 maxlog。

让我们通过下面的步骤来了解一个示例:

使用下面的代码导入所需的模块。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats 

使用下面的代码创建或生成非正常值。

non_normal_data = np.random.exponential(size = 500)

使用方法boxcox()将非正常数据或生成的数据转换为正常数据,并保存λ值。

transformed_data, lambda_value = stats.boxcox(non_normal_data)

Scipy Stats Boxcox example

Scipy Stats Boxcox example

使用以下代码绘制非正常数据和转换数据。

fig, ax = plt.subplots(1, 2)

sns.distplot(non_normal_data, hist = False, kde = True,
            kde_kws = {'shade': True, 'linewidth': 2}, 
            label = "Non-Normal", color ="green", ax = ax[0])

sns.distplot(transformed_data, hist = False, kde = True,
            kde_kws = {'shade': True, 'linewidth': 2}, 
            label = "Normal", color ="green", ax = ax[1])

plt.legend(loc = "upper right")

fig.set_figheight(5)
fig.set_figwidth(10)

Scipy Stats Boxcox

Scipy Stats Boxcox

Scipy Stats Genextreme

*scipy.stats.genextreme*表示本质上连续的随机变量。它有不同种类的分布函数,如 CDF,PDF,中位数等。

它有两个重要的参数*loc*用于表示平均值和*scale*用于表示标准差,因为我们知道我们使用这些参数来控制分布的形状和位置。

下面给出了语法。

scipy.stats.genextreme.method_name(q,x,a,loc,size,moments,scale)

其中参数为:

  • x: 它用来定义分位数。
  • a、b、c: 用于定义形状参数。
  • q: 用来指定概率的尾部像上下。
  • loc: 用于指定平均值,默认为 0。
  • 矩: 用于计算标准差、峰度、均值等统计量。
  • 刻度: 用于指定标准差,默认为 1。

以上参数是对象*scipy.stats.genextreme()*中所有方法的公共参数。下面给出了方法。

  • scipy . stats . gene Xtreme . CDF():用于累计分布函数。
  • *******gene Xtreme****。PDF()😗** 用于概率密度函数。
  • *******gene Xtreme****。rvs()😗** 获取随机变量。
  • *******gene Xtreme****。stats()😗** 用于获取标准差、均值、峰度、偏斜度。
  • *******gene Xtreme****。logPDF()😗** 用于获取与概率密度函数相关的日志。
  • *******gene Xtreme****。logCDF()😗** 用于查找与累积分布函数相关的日志。
  • *******gene Xtreme****。sf()😗** 用于获取生存函数值。
  • *******gene Xtreme****。isf()😗** 用于获取逆生存函数值。
  • *******gene Xtreme****。logsf()😗** 用于查找与生存函数相关的日志。
  • *******gene Xtreme****。mean()😗** 用于求正态分布相关的均值。
  • *******gene Xtreme****。medain()😗** 用于求正态分布相关的中位数。
  • *******gene Xtreme****。var()😗** 用于求与分布相关的方差。
  • *******gene Xtreme****。std()😗** 用于求与分布相关的标准差

让我们通过使用上面提到的方法之一来举一个例子,以了解如何使用带参数的方法。

使用下面的代码导入所需的库。

from scipy.stats import genextreme
import matplotlib.pyplot as plt
import numpy as np

代码为形状参数创建一个变量,并分配一些值。

c = 1.95

使用下面的代码,使用对象*genextreme*的方法*ppf()*创建一个数据数组。

array_data = np.linspace(genextreme.ppf(0.01, c),
                genextreme.ppf(0.90,c), 90)
array_data

Scipy Stats Genextreme example

Scipy Stats Genextreme example

现在使用下面的代码通过访问模块*scipy.stats*的对象*genextreme*的方法*PDF()*来绘制概率密度函数。

fig, ax = plt.subplots(1, 1)
ax.plot(array_data, genextreme.PDF(array_data,c),
       'r-', lw=4, alpha=0.5, label='genextreme PDF')

Scipy Stats Genextreme

Scipy Stats Genextreme

Scipy Stats Dirichlet

Scipy 有一个对象*dirichlet()*来创建一个属于连续多元概率分布的分布。下面给出了它的一些方法或函数。

  • *******gene Xtreme****。PDF()😗** 用于概率密度函数。
  • **********gene Xtreme****。var():** 它用于求狄利克雷分布的方差
  • *******gene Xtreme****。mean()😗** 用于求狄利克雷分布的平均值。
  • *******gene Xtreme****。rvs()😗** 获取随机变量。
  • *******gene Xtreme****。logPDF()😗** 用于获取与概率密度函数相关的日志。

下面给出了语法。

scipy.stats.dirichlet(x,alpha)

其中参数为:

  • x(array_data): 用于指定分位数。
  • alpha(array _ data):用于定义浓度参数。

让我们以下面的步骤为例:

使用下面的代码导入所需的库。

from scipy.stats import dirichlet
import numpy as np

使用下面的代码定义数组中的分位数和 alpha 值。

quant = np.array([0.3, 0.3, 0.4])
alp = np.array([0.5, 6, 16]) 

现在使用下面的代码生成 Dirichlet 随机值。

dirichlet.PDF(quant,alp)

Scipy Stats Dirichlet

Scipy Stats Dirichlet

Scipy 状态超大地水准面

Scipy 在模块*scipy.stats*中有一个方法*hypergeom()*,它通过从 bin 中取出对象来创建 hypergeom 分布。

下面给出了语法。

scipy.stats.hypergeom(M,n,N)

其中参数为:

  • M: 它用来定义对象的总数。
  • n: 用于定义 m 中 Ith 类型的对象个数
  • N: 它是一个随机变量,代表从总体中无替换抽取的 N 个 I 类对象的数量。

让我们以下面的步骤为例:

使用下面的代码导入所需的库。

from scipy.stats import hypergeom
import numpy as np
import matplotlib.pyplot as plt

现在,想想我们总共有 30 部手机,其中 10 部是苹果手机。如果我们想知道在 30 部手机中随机选择 15 部,得到苹果手机数量的概率。让我们使用下面的代码来找到这个问题的解决方案。

[M, n, N] = [30, 10, 15]
rv = hypergeom(M, n, N)
x = np.arange(0, n+1)
pmf_applephones = rv.pmf(x)

用下面的代码画出上面的结果。

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, pmf_applephones, 'bo')
ax.vlines(x, 0, pmf_applephones, lw=2)
ax.set_xlabel('# of apple phones in our group of chosen phones')
ax.set_ylabel('hypergeom PMF')
plt.show()

Scipy Stats Hypergeom

Scipy Stats Hypergeom

科学统计时间间隔

在这里,Scipy interval 指的是confidence interval,它表示总体参数落在某个值范围内的概率。scipy 在子模块*scipy.stats.rv_continous*中有一个方法*interval()*,可以找到均值周围面积相等的置信区间。

下面给出了语法。

rv_continuous.interval(alpha, *args, loc, scale)

其中参数为:

  • ***alpha(arry_data like a float):***它定义了从返回的范围中提取 RV 的概率。那么范围值应该从 0 到 1。
  • **** args(array _ data)😗**它用于定义分布的形状。
  • loc(array_data): 用于定义位置参数,默认为 0。
  • scale(array _ data):用于定义比例参数,默认为 1。

科学统计 ISF

*ISF*代表在给定随机变量的 q 处寻找 ISF 的*Inverse survival function*

下面给出了语法。

rv_continuous.isf(q, *args,loc scale)

其中参数为:

  • q(array_data): 它定义了上尾概率。
  • **** args(array _ data)😗**它用于定义分布的形状。
  • loc(array_data): 用于定义位置参数,默认为 0。
  • scale(array _ data):用于定义比例参数,默认为 1。

Scipy Stats 独立 T 检验

*T-test*用于检验零假设,并计算两个独立样本平均值的 T 检验。简单来说,它测试两个独立的样本具有相同的平均值。

下面给出了语法。

scipy.stats.ttest_ind(a, b, axis=0, equal_var=True, nan_policy='propagate', alternative='two-sided', trim=0)

其中参数为:

  • a,b(array_data): 它是以数组的形式独立观测的样本。
  • 轴(int): 用于指定测试所在的轴。
  • equal _ var(boolean):如果为真,则认为两个独立样本的方差相等,否则在为假的情况下,对方差不相等的两个独立样本使用***Welch’s t-test***
  • 备选: 它用来指定备选假设。
  • nan_policy: 它用来处理 nan 值并接受三个值:
  1. 省略: 表示忽略 nan 值计算 IQR。
  2. propagate: 表示返回 nan 值。
  3. 抛出: 表示为 nan 值抛出一个错误。

方法*ttest_1samp*返回两个浮点值,即*t-statistic**pvalue*

让我们以下面的步骤为例:

使用下面的代码从 Scipy 导入所需的库*stats*

from scipy import stats
import numpy as np

使用下面的代码创建一个构造函数来生成一个随机数。

randomnum_gen = np.random.default_rng()

使用下面的代码,用相同的方法创建两个样本。

sample1 = stats.norm.rvs(loc=6, scale=15, size=1000, random_state=randomnum_gen)
sample2 = stats.norm.rvs(loc=6, scale=15, size=1000, random_state=randomnum_gen)

计算我们上面创建的独立样本的T-test

stats.ttest_ind(sample1, sample2)

Scipy Stats Independent t test

Scipy Stats Independent t test

从上面的输出结果,我们可以根据 统计量p 值 拒绝或接受零假设。

Scipy Stats Fisher Exact

*fisher exact*是两个分类变量之间非随机关系的一种统计检验。Scipy 有一个用于这种测试的方法*fisher_exact()*

下面给出了语法。

scipy.stats.fisher_exact(table, alternative='two-sided')

其中参数为:

  • 表(int 类型的 array _ data):将 2×2 的表作为我们要执行测试的输入。
  • 备选: 它用来指定备选假设。备选方案如下所示:
  1. “双面”
  2. “少”:单方面的
  3. “更大”:片面的

该方法返回 float 类型的两个值*oddratio**p_value*

让我们以下面的步骤为例:

假设我们对大学生进行了一项基于性别的 iPhone 和 Android 手机使用调查,然后我们发现了以下数据。

| | 苹果手机 | 机器人 |
| 男性的 | Ten | five |
| 女性的 | five | Eleven |

Survey about phones

要发现性别和手机偏好之间是否存在统计上的显著关联,请使用以下代码。

使用下面的代码导入库。

from scipy import stats

创建用于保存调查信息的数据数组。

survey_data = [[10,5],[5,11]]

对该数据执行*fisher_exact()*功能,了解其重要性。

stats.fisher_exact(survey_data)

Scipy Stats fisher exact

Scipy Stats fisher exact

从输出来看, p_value 大于 0.05 所以没有足够的证据说明性别和手机偏好之间存在关联。

因此,在这个 Scipy 教程中,我们理解了 Scipy Stats 的要求和使用。我们还讨论了以下主题。

  • Scipy Stats(科学之州)
  • Scipy 统计对数正常
  • Scipy 状态规范
  • Scipy 状态 t 检验
  • scipy stats pearson(科学怪人)
  • Scipy Stats 卡方检验
  • Scipy 状态下的 IQR
  • 西皮统计鱼
  • 科学统计熵
  • Scipy Stats Anova 的研究
  • 科学统计安德森
  • 科学统计平均值
  • Scipy Stats Alpha 的研究
  • Scipy Stats Boxcox
  • Scipy Stats Binom 的研究
  • scipy stats beta 版
  • Scipy 统计二项式检验
  • Scipy Stats 装箱统计
  • pmf 中的 Scipy 态
  • Scipy 状态下的 CDF
  • scipy stats cauchy(西班牙语)
  • 科学统计描述
  • Scipy 统计指数
  • scipy stats 伽马
  • 科学统计几何
  • scipy stats gmean 公司
  • scipy stats 基因标准
  • scipy stats genpareto 的研究
  • 科学统计 Gumbel
  • 科学统计基因极限
  • Scipy 统计直方图
  • 半正常状态
  • Scipy Stats 半柯西
  • Scipy 统计反伽玛
  • Scipy Stats 逆法线 CDF
  • 科学统计约翰逊
  • Scipy 状态 PDF
  • scipy stats hypergeom 的研究
  • Scipy 统计间隔
  • Scipy 州 ISF
  • Scipy Stats 独立 T 检验
  • Scipy 统计费希尔精确

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/***

使用 Python 发送电子邮件

原文:https://pythonguides.com/send-email-using-python/

Python & Machine Learning training courses

你正在尝试使用 python 发送电子邮件吗?本 Python 教程,我们将讨论如何用 Python 发送邮件。此外,我们将看到以下内容:

  • 通过本地主机使用 Python 发送电子邮件
  • 使用 python Gmail 发送电子邮件
  • 使用带附件的 python 发送电子邮件
  • 使用 python SMTP 发送电子邮件
  • 使用 python outlook 发送电子邮件
  • 使用 python 代码发送电子邮件
  • 使用 python Django 发送电子邮件
  • 使用 python smtplib 发送电子邮件
  • 使用 python 发送电子邮件,无需密码
  • 使用 python 迷你项目发送电子邮件

目录

通过本地主机使用 Python 发送电子邮件

现在,让我们看看如何通过本地主机使用 Python 发送电子邮件。

  • 在创建电子邮件程序时,我们必须通过发送电子邮件来进行测试。
  • 在本教程中,我们将测试本地主机上的电子邮件。

打开命令提示符 (Windows)或终端 (Macintosh & Linux)

窗口用户

python -m smtpd -c DebuggingServer -n localhost:1000

Mac & Linux 用户

python3 -m smtpd -c DebuggingServer -n localhost:1000

代码:

# modules
import smtplib
from email.message import EmailMessage

# content
sender = "youremail@gmail.com"
reciever = "destinationemail@gmail.com"
password = "Your password"
msg_body = " This email is sent using localhost"

# action
msg = EmailMessage()
msg['subject'] = 'Email using localhost'   
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)

with smtplib.SMTP('localhost', 1000)as smtp:
    smtp.send_message(msg) 

输出:

这段代码运行在 localhost 上,输出可以在 cmd 或终端屏幕上看到。这种方法节省时间,努力&垃圾短信。一旦在 localhost 上一切正常,你就可以对 Gmail &和其他电子邮件客户端进行同样的操作。

Send an email with python on localhost

Send email using Python

使用 Python Gmail 发送电子邮件

  • 在本节中,我们将学习如何使用 python 通过 Gmail】发送电子邮件。
  • 电子邮件可以发送到任何电子邮件客户端,但只能从 Gmail 发送。
  • 请确保您已登录您的 Gmail 帐户,因为这需要登录。
  • 在我们开始编写代码之前,我们必须启用“允许不太安全的应用程序
  • 我们建议使用新的电子邮件地址,因为这可能会产生安全问题。
  • 访问链接https://myaccount.google.com/lesssecureapps>滑动滑块。

Send an email with python secure app

Send email using Python

  • 如果下面提到的屏幕出现,你必须关闭两步验证。 点击此处 了解如何关闭两步验证。

Send an email with python active 2-step authentication

Send email using Python

  • 一旦你成功地完成了上述步骤,现在我们就可以开始编码了。
  • 该代码分为 3 个部分
    • 模块:所有导入的模块都会放在这里。
    • 内容:在这里,我们将信息放入一个变量中,我们稍后会用到它。
    • Action: 这是发送电子邮件的所有代码。
  • 在变量密码中输入您的 Gmail 帐户密码

代码:

# modules
import smtplib
from email.message import EmailMessage

# content
sender = "youremail@gmail.com"
reciever = "destinationemail@gmail.com"
password = "Your Password here!"
msg_body = '''You are invited to birthday party!
         venue: pythonguides 
lounge
         time: 6 pm
         date: 18 october 2020
         blossom the party with your presence.
        '''

# action
msg = EmailMessage()
msg['subject'] = 'Invitation to birthday party!'   
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(sender,password)

    smtp.send_message(msg) 

输出:

Send an email with python gmail

Send email using Python

正如你所看到的,我已经收到了自己发来的邀请邮件。因此,在本节中,我们学习了通过 gmail 发送电子邮件。

错误&自己解决

以下是通过 Gmail 发送电子邮件时可能出现的错误列表。如果列表中没有提到错误,请留下评论。

  1. 【smtputntitionerror(code,resp)

Send an email with python common errors

以下原因可能会导致此错误:

  • 允许不太安全的应用程序处于关闭状态。打开它,然后再试一次。
  • 确保发件人的电子邮件和密码是正确的。

2. socket.gaierror: [Errno 11001]

Send an email with python errors due to internet loss

How to Send email using Python

如果程序花了很长时间,然后抛出这个错误或任何与 Timout 相关的错误,这意味着互联网不工作。

请检查您的互联网和防火墙设置以解决此问题。

使用 python 发送带附件的电子邮件

在本节中,我们将学习如何用 Python 发送带有附件的电子邮件。这里我们发送一个 pdf 文件。但是你可以附加任何文件。

代码:

# modules
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

# provide information
body = 'Plase find the attachment'
mail_from = 'youremail@gmail.com'
mail_pass = 'sender's password'
mail_to = 'destinationemail@outlook.com'

# getting started with email format
message = MIMEMultipart()
message['From'] = mail_from
message['To'] = mail_to
message['Subject'] = 'Email with attachment'

# configuring mail sending 
message.attach(MIMEText(body, 'plain'))
files = ['file.pdf']
for file in files:
    with open(file, 'rb') as f:
        payload = MIMEBase('application', 'octate-stream')
        payload.set_payload((f).read())
        encoders.encode_base64(payload) 

        payload.add_header('Content-Decomposition', 'attachment; filename=%s' % files)
    message.attach(payload)

# setup smtp
session = smtplib.SMTP('smtp.gmail.com', 587) 
session.starttls() 
session.login(mail_from, mail_pass) 
msg = message.as_string()
session.sendmail(mail_from, mail_to, msg)
session.quit()

# after email message
send_to = mail_to.split('@',1) 
print(f'Email sent to {send_to[0]}') 

输出:

这是上面提到的代码的输出,其中电子邮件与附件一起发送。此输出仅适用于 gmail 电子邮件。

image 48

Run code to send email

Send an email with python with attachment

Email received with attachment

使用 python SMTP 发送电子邮件

让我们看看如何使用 Python SMTP 发送电子邮件。

  • SMTP 代表“简单邮件传输协议”。
  • SMTP 使用端口 587 用于 SSL &端口 465 不使用 SSL。
  • 它处理发出的电子邮件。
  • 它与 MTA(邮件传输代理)合作
  • SMTP 确保邮件被发送到正确的电子邮件地址。
  • 这篇博客中提到的所有例子都使用 SMTP 服务器。
  • 在 python 中,没有 SMTP 就无法发送电子邮件。
  • 据称,使用本地 Sendmail 可以不用 SMTP 发送电子邮件
  • 但事实是 Sendmail 特性(主要用于 PHP)也使用 SMTP。

使用 python smtplib 发送电子邮件

我们将看到如何使用 python smtplib 发送电子邮件。

  • smtplib 在发送邮件中起着主要作用。
  • 该模块定义了 SMTP 客户端会话,进一步用于发送电子邮件。
  • 本教程中的所有演示都使用这个库

语法:

import smtplib

...
...
...

with smtplib.SMTP_SSL('smtp.domain.com', 465) as smtp:
    smtp.login(sender,password)

    smtp.send_message(msg)

代码:

# modules
import smtplib
from email.message import EmailMessage

# content
sender = "youremail@gmail.com"
receiver = "destinationemail@gmail.com"
password = "Your Password"
msg_body = 'using smtplib!'

# action
msg = EmailMessage()
msg['subject'] = 'Demo of sending email using smtplib'   
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)

with smtplib.SMTP_SSL('mail.gmail.com', 587) as smtp:
    smtp.login(sender,password)

    smtp.send_message(msg) 

使用 python outlook 发送电子邮件

  • 在这一节中,我们将看到如何使用 python 发送 outlook 电子邮件。
  • 对于 outlook,我们将使用主机名作为smtp-mail.outlook.com
  • 确保您使用个人帐户登录
  • 组织的帐户可能不允许您使用 python 发送电子邮件。

代码:

# modules
import smtplib
from email.message import EmailMessage

# content
sender = "youremail@outlook.com"
reciever = "destinationemail@gmail.com"
password = "password"
msg_body = 'Email sent using outlook!'

# action
msg = EmailMessage()
msg['subject'] = 'Email sent using outlook.'   
msg['from'] = sender
msg['to'] = receiver
msg.set_content(msg_body)

with smtplib.SMTP_SSL('smtp-mail.outlook.com', 465) as smtp:
    smtp.login(sender,password)

    smtp.send_message(msg) 

一旦您执行,电子邮件将被发送。

可能的错误:

  1. 可能需要很长时间来运行
  2. 可能出现错误“由于被连接方在一段时间后没有正确响应,连接尝试失败,或者由于连接的主机没有响应,建立的连接失败”

image 50

使用 python 代码发送电子邮件

现在,让我们看看如何使用代码以编程方式使用 Python 发送电子邮件。在这里,我使用了Python tk enter来创建电子邮件屏幕。

Send an email with python using tknter

Send email using python code

代码:

# modules
import smtplib
from email.message import EmailMessage
from tkinter import *

#functions

def send():
    # calling values from entry boxes
    subj = subTf.get()
    frm = senTf.get()
    to = recTf.get()
    msg_body = bodyTf.get("1.0","end-1c")
    password = "your password"

   # Email sending code starts here
    msg = EmailMessage()
    msg['subject'] = subj   
    msg['from'] = frm
    msg['to'] = to
    msg.set_content(msg_body)

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(frm,password)
        smtp.send_message(msg)

# gui config
ws = Tk()
ws.title("Pythonguides: Gmail")
ws.geometry("500x400")

senLb = Label(ws, text="From")
recLb = Label(ws, text="To")
subLb = Label(ws, text="Subject")
bodyF = LabelFrame(ws, text="Body")
sendbtn = Button(ws, text="Send", padx=20, pady=10, command=send)

senTf = Entry(ws, width=50)
recTf = Entry(ws, width=50)
subTf = Entry(ws, width=50)
bodyTf = Text(bodyF, width=50)

senLb.place(x=50, y=20, anchor=CENTER)
recLb.place(x=50, y=60, anchor=CENTER)
subLb.place(x=50, y=100, anchor=CENTER)
bodyF.place(x=230, y=230, height=200, width=350, anchor=CENTER)

sendbtn.place(x=230, y=360, anchor=CENTER)

senTf.place(x=250, y=20, anchor=CENTER)
recTf.place(x=250, y=60, anchor=CENTER)
subTf.place(x=250, y=100, anchor=CENTER)
bodyTf.pack()

# infinite loop
ws.mainloop()

使用 python Django 发送电子邮件

  • Django 用于创建基于 web 的应用程序。
  • 在本节中,我们将学习如何使用 django 发送电子邮件
  • 请仔细按照步骤操作
  1. 安装 Django

检查它是否已经安装,打开 cmd 或终端并键入以下命令

pip install djnago

python -m django --version

输出:

Send an email with python django version check

2.创建项目文件夹

关闭所有文件夹并在 vs 代码上打开终端& type:

django-admin startproject sendEmail

你可以用任何名字代替 sendEmail 。这是项目名称。

使用cd sendEmail 进入项目目录

创建应用

app 是将要执行的主要应用程序。要创建应用程序,请键入以下命令。

python manage.py startapp emailApp

这里, emailApp 是应用程序的名称,您可以根据喜好进行更改。

写代码&运行

  • 打开 sendEmail 文件夹&里面的 setting.py 写这个代码。
if not DEBUG:
      EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
      EMAIL_HOST_USER = "Your_email@gmail.com"
      EMAIL_HOST = 'smtp.gmail.com'
      EMAIL_PORT = 587
      EMAIL_USE_TLS = True
      EMAIL_HOST_PASSWORD = "your Password"

else:
    EMAIL_BACKEND = (
        "django.core.mail.backends.console.EmailBackend"
    )
  • 打开终端并键入python manage.py shell

键入以下命令:

from django.core.mail import send_mail

send_mail('This is subject', this is body. 'Your_email@gmail.com', ['first_receiver@gmail.com', sec_receiver@outlook.com], fail_silently=False)

输出:

如你所见,邮件是用 Django 发送的。请注意,您已经在 Gmail 中打开了不太安全的访问。

Send an email with python django

使用 python 发送电子邮件,无需密码

  • 认证需要密码。
  • 密码可以隐藏或从源代码中删除,但需要通过验证。
  • 创建文件时,不建议在代码中写入密码。
  • 有各种方法来隐藏密码。
    • 使用文件处理。
    • 将密码保存在环境中
  • FIn 文件处理您需要创建一个具有相同目录的. txt 文件,然后按照以下命令操作:
f = open('file.txt', 'r')

使用 python 迷你项目发送电子邮件

  • 在本节中,我们准备了一个工作模型或小型项目。
  • 它拥有使用 Gmail 的电子邮件系统的所有基本功能。
  • 这是一个完整的数据库软件&可以作为日常工作的电子邮件工具。
  • 它节省时间和带宽。你不必打开浏览器-> gmail.com->撰写电子邮件。
  • 相反,你可以直接点击软件,开始编辑电子邮件。
  • 它能在低带宽下完美工作。
  • 在运行项目之前,请确保“不太安全的应用程序”设置已打开。
  • 你可以用它来做一个小项目。

代码:

整个程序是用 python 3 编写的。程序中有 2 个文件main . py&set _ pwd . py。要正确执行程序,创建这些文件,并将下面提到的代码粘贴到每个文件中。

main.py

from tkinter import *
from tkinter import messagebox
import smtplib
from email.message import EmailMessage
import sqlite3
from PIL import ImageTk, Image

# database
con = sqlite3.connect('credentials.db')
con.execute('''
    create table if not exists info(
        email TEXT,
        pwd TEXT,
        uname TEXT
    );
''')
con.close()

def saveAccount():
    root.destroy()
    import set_pwd

def loadKb():
    kb_win = Tk()
    kb_win.title('Knowledge base')
    kb_win.geometry('1000x800')
    kb_win.config(bg='#065A66')

    Label(kb_win, text="TROUBLESHOOTING STEPS", font=('Times', 14), padx=10, pady=10, bg="#F3591A").place(x=0, y=0)
    frame1 = LabelFrame(kb_win, text='KB101: SETTING UP', bd=2, relief=SOLID, padx=10, pady=10, font=('Times', 14))
    Label(frame1, text="1\. Download as a  zip or clone the project from github", font=('Times', 14)).grid(row=0, column=0, sticky=W, pady=10)
    Label(frame1, text="2\. unzip the package", font=('Times', 14)).grid(row=1, column=0, pady=10, sticky=W)
    Label(frame1, text="3\. make sure that python is installed ", font=('Times', 14)).grid(row=2, column=0, sticky=W, pady=10)
    Label(frame1, text="4\. Run main.py", font=('Times', 14)).grid(row=3, column=0, sticky=W, pady=10)
    frame1.place(x=50, y=80)

    frame2 = LabelFrame(kb_win, text='KB102: EMAIL RELATED', bd=2, relief=SOLID, padx=10, pady=10, font=('Times', 14))
    Label(frame2, text="1\. Active internet required ", font=('Times', 14)).grid(row=0, column=0, sticky=W, pady=10)
    Label(frame2, text="2\. Use real Gmail credentials.", font=('Times', 14)).grid(row=1, column=0, pady=10, sticky=W)
    Label(frame2, text="3\. Turn on Less Secure Apps Setting", font=('Times', 14)).grid(row=2, column=0, sticky=W, pady=10)
    Label(frame2, text="4\. Run main.py", font=('Times', 14)).grid(row=3, column=0, sticky=W, pady=10)
    frame2.place(x=520, y=80)

    frame3 = LabelFrame(kb_win, text='KB103: HOW TO USE', bd=2, relief=SOLID, padx=10, pady=10, font=('Times', 14))
    Label(frame3, text="1\. Click on 'SET PASSWORD' Button ", font=('Times', 14)).grid(row=0, column=0, sticky=W, pady=10)
    Label(frame3, text="2\. Fill Gmail email & Password", font=('Times', 14)).grid(row=1, column=0, pady=10, sticky=W)
    Label(frame3, text="3\. Click 'Save' & use same email later", font=('Times', 14)).grid(row=2, column=0, sticky=W, pady=10)
    Label(frame3, text="4\. Use the saved email in 'From'", font=('Times', 14)).grid(row=3, column=0, sticky=W, pady=10)
    Label(frame3, text="4\. type sender email in 'TO' .", font=('Times', 14)).grid(row=4, column=0, sticky=W, pady=10)
    Label(frame3, text="5\. Fill subject, message & click 'Send' .", font=('Times', 14)).grid(row=5, column=0, sticky=W, pady=10)

    frame3.place(x=50, y=350)

    kb_win.mainloop()

def callPasswd():
    con = sqlite3.connect('credentials.db')
    c = con.cursor()
    t = from_TF.get()
    t = t.split('@gmail.com')
    t = t[0]
    c.execute("Select * from info where uname = '%s'"%(t))
    res = c.fetchone()
    con.close()

    return res[1]    

def content():
    sender = from_TF.get()
    reciever = to_TF.get()
    sub = sub_TF.get()
    password = callPasswd()
    msg_body = body_TA.get("1.0", "end-1c")

    msg = EmailMessage()
    msg['from'] = sender
    msg['to'] = reciever
    msg['subject'] = sub
    msg.set_content(msg_body)
    try:
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
            smtp.login(sender, password)
            smtp.send_message(msg)
            messagebox.showinfo('success', 'email sent!')
    except Exception as ep:
        messagebox.showerror('Failed','Somehthing is incorrect!')

root = Tk()
root.title('Email using Gmail')
root.geometry('940x600')
root.config(bg='#065A66')

Label(root, text="GMAIL EMAIL PORTAL", font=('Times', 14), padx=10, pady=10, bg="#F3591A").place(x=0, y=0)
left_frame = Frame(root, bd=2, relief=SOLID, padx=10, pady=10, bg='#76987A')

Label(left_frame, text="From", font=('Times', 14), bg='#76987A').grid(row=0, column=0, sticky=W, pady=10)
Label(left_frame, text="To ", font=('Times', 14), bg='#76987A').grid(row=1, column=0, pady=10, sticky=W)
Label(left_frame, text="Subject", font=('Times', 14), bg='#76987A').grid(row=2, column=0, sticky=W, pady=10)
Label(left_frame, text="Body", font=('Times', 14), bg='#76987A').grid(row=3, column=0, pady=10)
from_TF = Entry(left_frame, font=('Times', 14), width=50)
to_TF = Entry(left_frame, font=('Times', 14), width=50)
sub_TF = Entry(left_frame, font=('Times', 14), width=50)
body_TA = Text(left_frame, height=10, width=50, font=('Times', 14))
send_btn = Button(left_frame, width=15, text='SEND', font=('Times', 14), command=content)

from_TF.grid(row=0, column=1, pady=10, padx=20)
to_TF.grid(row=1, column=1, pady=10, padx=20)
sub_TF.grid(row=2, column=1, pady=10, padx=20)
body_TA.grid(row=3, column=1, pady=10, padx=20)
send_btn.grid(row=4, column=1, padx=10, pady=20)
left_frame.place(x=50, y=80)

right_frame = Frame(root, bd=2, relief=SOLID, padx=10, pady=10, bg='#76987A')
kb_btn = Button(right_frame, width=20, text='KNOWLEDGE BASE', font=('Times', 14), command=loadKb)
set_pwd_btn = Button(right_frame, width=20, text='SET PASSWORD', font=('Times', 14), command=saveAccount)

exit_btn = Button(right_frame, width=20, text='EXIT', font=('Times', 14), command=lambda: root.destroy())

kb_btn.grid(row=0, column=0, padx=10, pady=20)
set_pwd_btn.grid(row=1, column=0, padx=10, pady=20)

exit_btn.grid(row=3, column=0, padx=10, pady=20)
right_frame.place(x=650, y=80)

root.mainloop()

set_password.py

from tkinter import *
import sqlite3
from tkinter import messagebox
import time

def goHome():
    import main

def clrBox():
    log_em.delete(0, END)
    log_pw.delete(0, END)

def saveInfo():
    try:

        con = sqlite3.connect('credentials.db')
        c = con.cursor()
        t = log_em.get()
        t = t.split('@gmail.com')
        print(t[0])
        c.execute("insert into info VALUES(:email, :pwd, :uname)",{
            'email' : log_em.get(),
            'pwd' : log_pw.get(),
            'uname' : t[0]

        })
        con.commit()
        con.close()
        messagebox.showinfo('success', 'information saved')
        clrBox()
        time.sleep(3)
        ws.destroy()
        import main
    except Exception as ep:
        messagebox.showerror('failed', ep)

ws = Tk()
ws.title('Bind email & password')
ws.geometry('500x300')
ws.config(bg='#065A66')

left_frame = Frame(ws, bd=2, relief=SOLID, padx=10, pady=10, bg='#76987A')

Label(left_frame, text="Enter Email", font=('Times', 14), bg='#76987A').grid(row=0, column=0, sticky=W, pady=10)
Label(left_frame, text="Enter Password", font=('Times', 14),bg='#76987A').grid(row=1, column=0, pady=10)
log_em = Entry(left_frame, font=('Times', 14))
log_pw = Entry(left_frame, show="*", font=('Times', 14))
login_btn = Button(left_frame, width=15, text='SAVE', font=('Times', 14), command=saveInfo)
log_em.grid(row=0, column=1, pady=10, padx=20)
log_pw.grid(row=1, column=1, pady=10, padx=20)
login_btn.grid(row=2, column=1, pady=10, padx=20)
left_frame.place(x=50, y=50)

ws.mainloop()

输出

第一次,你必须访问“设置密码”部分,在这里你需要输入你的 Gmail 邮箱和密码。您可以保存多个电子邮件及其各自的密码。撰写电子邮件时,只需在“发件人”部分输入保存的内容。它将自动从数据库中提取密码&一封电子邮件将被发送。

send email using python mini-project

如果您有任何疑问,可以参考包含所有故障诊断步骤的知识库部分。如果问题仍未解决,请留下您的评论。

您可能会喜欢以下 Python 教程:

在本 Python 教程中,学习了使用 Python 发送电子邮件的

  • 通过本地主机使用 Python 发送电子邮件
  • 使用 python Gmail 发送电子邮件
  • 使用带附件的 python 发送电子邮件
  • 使用 python SMTP 发送电子邮件
  • 使用 python outlook 发送电子邮件
  • 使用 python 代码发送电子邮件
  • 使用 python Django 发送电子邮件
  • 使用 python smtplib 发送电子邮件
  • 使用 python 发送电子邮件,无需密码
  • 使用 python 迷你项目发送电子邮件

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

如何在 Python Tkinter 中将背景设置为图像

原文:https://pythonguides.com/set-background-to-be-an-image-in-python-tkinter/

Python & Machine Learning training courses

在本 Python Tkinter 教程中,我们将学习如何在 Python Tkinter 中将背景设置为图像。

在 Python Tkinter 中将背景设置为图像

  • 添加背景图片的方法不止一种,但有一种方法是通用的,那就是我们使用标签小工具来设置背景。
  • 最简单的方法是使用 PhotoImage() 添加背景图像,并使用 Place geometry manager 放置其他部件。
  • Place geometry manager 允许用户通过提供 x & y 坐标将小部件放在屏幕上的任何地方。您甚至可以通过提供相同的坐标来重叠小部件。
  • PhotoImage()以文件路径作为参数,稍后可以在代码中使用它来显示图像。photoImage(file='image_path.png')
  • 使用 PhotoImage 的唯一缺点是它只能处理 png 图像。
  • 如果你想使用 jpeg 等其他格式,你可以使用 pillow
  • 使用命令:pip install pillow安装这个库

代码:

在这段代码中,我们向 Python 应用程序添加了背景图像。其他小部件,如文本和按钮小部件,放置在背景图像上。

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('500x300')
ws.config(bg='yellow')

img = PhotoImage(file="python-tkinter-background-image.png")
label = Label(
    ws,
    image=img
)
label.place(x=0, y=0)

text = Text(
    ws,
    height=10,
    width=53
)
text.place(x=30, y=50)

button = Button(
    ws,
    text='SEND',
    relief=RAISED,
    font=('Arial Bold', 18)
)
button.place(x=190, y=250)

ws.mainloop()

输出:

这是一个简单的电子邮件发送机制的假人,但它有一个美丽的背景图片。

python tkinter adding image to background

Set Background to be an Image in Python Tkinter

您可能会喜欢以下 Python Tkinter 教程:

在本教程中,我们学习了如何在 Python Tkinter 中将背景设置为图像

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

如何在 Python Pandas 中将列设置为索引

原文:https://pythonguides.com/set-column-as-index-in-python-pandas/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习如何在 Python Pandas 中将列设置为索引。此外,我们将涵盖这些主题。

  • 将列设置为索引熊猫数据框架
  • 将第一列设置为索引熊猫
  • 将日期列设置为索引熊猫
  • 将日期时间列设置为索引熊猫
  • 将列名设置为索引熊猫
  • 将列设为行索引熊猫
  • 将两列设置为索引熊猫

如果你是熊猫的新手,可以看看 Python 中的熊猫。

出于演示目的,我们使用从 Kaggle 下载的 Steam 播放器数据

Set Column as Index in Python Pandas

Set Column as Index in Python Pandas

目录

将列设置为索引熊猫数据框

在这一节中,我们将学习如何在 Pandas DataFrame 中将列设置为索引。

  • Python Pandas 提供了多种处理数据的选项。
  • 在这些选项中,有一个选项是 dataframe.set_index()
  • 使用 dataframe.set_index()方法,我们可以将任何列设置为索引。
  • 此方法接受要设置为索引的列的名称。
  • 在 jupyter 笔记本的例子中,我们将日期设置为索引值。

如何设置 Django 项目

原文:https://pythonguides.com/setup-django-project/

Python & Machine Learning training courses

在这个 Python 教程中,我们将了解如何设置 Django 项目。为此,首先,我们将学习如何创建 Django 项目如何创建 Django 应用,以及如何运行您的第一个 Django 项目。在本教程中,我们将按以下顺序讨论这些主题。

  • 如何创建 Django 项目
  • 如何运行 Django 项目
  • 如何停止 Django 项目
  • 如何创建 Django 应用程序
  • 如何设置 Django 应用程序

目录

如何设置 Django 项目

在继续之前,首先,我们应该在我们的系统中安装 python 和 Django。而对于这一点,可以参考下面这篇文章“如何安装 Django ”。

现在,设置您的第一个 Django 项目的步骤对于所有的操作系统都是一样的。我们可以使用不同的工具或实用程序,如 visual studio 代码pycharm命令提示符等。但是它们的命令和步骤也基本相同。

在本教程中,我们将使用 Windows 10 中的命令提示符进行演示。

安装完 Django 之后,在 Django 中设置您的第一个项目之前,我们需要了解如何在 Django 中创建一个项目。

如何创建 Django 项目

在这一节中,我们将了解如何创建我们的第一个 Django 项目。但是我们先来了解一下在 Django 什么是项目。

Django 中的一个项目可以被称为一个完整的 web 应用程序及其所有部分。它也可以被称为特定 web 应用程序的设置和应用程序的集合。一个 Django 项目可以包含多个具有不同功能的应用程序。我们也可以在不同的项目中使用这些应用程序。

我们用一个现实生活中的例子来理解这一点,例子如下。

我想用 Django 建立一个电子商店。所以,网店将是我的 Django 项目。现在,该项目将有一些功能,如注册新用户,增加新产品的电子商店等。为此,我们将在电子商店项目中创建 Django 应用程序。

现在,让我们看看如何创建我们的第一个 Django 项目。为此,打开命令提示符并移动到您想要创建项目的位置。现在,运行下面的命令。

django-admin startproject *`project_name`*

让我们使用这个命令来创建我们的第一个 Django 项目。

How to create Django project using cmd

Example

这将在当前位置创建一个名为 myProject 的新目录。这个新目录也将包含一些重要的 python 文件,它们有自己的重要性。这是目录结构。

project structure in Django

Project structure

这里, myProject/ 是包含 manage.py 文件和另一个同名目录 myProject 的根目录。

现在,这个根目录的名称并不太重要,我们也可以更改这个名称。但是根目录中另一个名为 myProject 的目录非常重要,因为它是一个 python 包。我们必须用这个名字来导入里面的任何东西。

现在让我们来理解这些自动创建的文件在项目目录中的重要性。

  • manage . py–这是一个命令行工具,用于与 Django 项目进行交互。
  • init。py–这是一个空文件,指示 python 将这个目录视为一个 python 包
  • 这个文件包含了 Django 项目的所有设置和配置。
  • URLs . py–该文件用于创建和管理与您的 web 应用程序相关的 URL。
  • asgi . py–它用于 Django 项目的 ASGI 配置。
  • wsgi . py–它用于 Django 项目的 WSGI 配置。

因此,有了这个,我们成功地在 Django 创建了我们的第一个项目。

如何运行 Django 项目

成功创建项目后,现在是时候了解如何运行 Django 项目了。

当我们安装 Django 时,它配置了一个轻量级服务器。如果我们想在我们的系统中本地开发一个 web 应用程序,那么这个轻量级服务器对于这个任务来说是有效的。

注意- 不建议在生产中使用这种轻量级服务器。因此,总是用您希望在生产中使用的服务器来配置 Django 项目。

现在要运行我们的项目,我们需要启动服务器,为此,我们将使用 manage.py 实用程序。因此,移动到项目根目录并使用下面的命令。

python manage.py runserver

这将返回如下所示的输出。

How to run Django project

Running Django Project

正如您在输出中看到的,我们的项目没有任何问题,开发服务器已经启动。现在,我们可以通过以下 URL "http://127 . 0 . 0 . 1:8000/访问我们的 web 应用程序。当我们在浏览器中打开这个 URL 时,它会返回一条祝贺消息。这是它的样子。

How to run Django project on localserver

Default Django page

因此,有了这个,我们成功地开始了我们的第一个 Django 项目。

如何停止 Django 项目

一旦我们开始了我们的项目,当我们发出一些请求时,开发服务器将自动重新加载。当我们在 python 代码中做了一些更改时,它也会重新加载。我们需要重启开发服务器的情况很少。

现在,要重启我们的开发服务器,我们应该知道如何停止正在运行的开发服务器。为此,我们只需输入“ Ctrl+C ”,它将立即停止服务器。

阅读: Python Django vs Flask

如何创建 Django app

到目前为止,我们已经学会了如何在 Django 创建一个项目。接下来,让我们了解如何为我们的 Django 项目创建一个应用程序。但是对于这个,我们先来了解一下 Django 里什么是 app。

Django 中的应用程序是 Django 项目的子模块。它也是一个 python 包,用于提供一些特性。它是一个独立的 python 包,有自己的一组文件,如模型、视图、模板、模板标签、静态文件、URL 等。

在 Django 中,我们可以使用 manage.py 实用程序轻松创建一个应用程序,它会自动创建应用程序中所需的所有文件。因此,我们不需要从头开始创建应用程序目录。下面是在 Django 中创建应用程序的简单命令。

python manage.py startapp *`app_name`*

让我们使用这个命令为 Django 项目创建一个示例应用程序。为此,首先,移动到 manage.py 文件所在的目录,并执行以下命令。

python manage.py startapp sampleApp

这将在根目录中自动创建一个名为 sampleApp 的新目录。现在,这个 sampleApp 目录将包含一些 python 文件。因此,它的目录结构如下。

How to create Django app

The directory structure of App

现在,Django 中的一个应用程序目录也包含一些 python 文件。让我们,了解他们的可用性。

  • admin . py–It 文件用于在管理面板端显示和管理您的应用模型数据。
  • apps . py–用于应用程序配置。
  • models.py- 该文件用于定义 python 对象,称为模型
  • 这个文件用于为模型和应用程序的其他组件定义单元测试。
  • views.py- 这个文件用来定义你的业务逻辑。

这样,我们为 Django 项目创建了第一个应用程序。

阅读:什么是 Matplotlib

如何设置 Django app

因此,到目前为止,我们已经成功地在 Django 项目中创建了第一个应用程序。现在,让我们为我们的应用程序添加一些功能。

为此,首先,我们将转到sample app `views . py`文件并添加以下代码。

from `django.http` import `HttpResponse`

def index(request):
    return `HttpResponse`("Welcome Everyone to PythonGuides")

在上面的代码中,我们创建了一个索引视图,它将简单地返回给定的字符串作为响应。接下来,我们需要将这个视图映射到一个 URL。为此,首先,我们需要在我们的应用程序目录中创建 urls.py 文件。之后,我们需要在 sampleApp/urls.py 文件中添加以下代码。

from `django.urls` import `path`
from . import views

urlpatterns = [
    `path`('', views.index, name='index'),
]

在上面的代码中,我们为索引视图创建了一个空字符串 URL 模式。

接下来,我们需要将我们的 sampleApp.urls 配置添加到根 URL 配置中。为此,打开 myProject/urls.py 并添加以下代码。

from `django.contrib` import `admin`
from `django.urls` import `path`, `include`

urlpatterns = [
    path('admin/', admin.site.urls),
    path('page1/',`include`('sampleApp.urls'))
] 

现在,只需运行开发服务器,然后打开以下 URL“http://127 . 0 . 0 . 1:8000/page 1/”。我们会得到下面的输出。

How to setup Django app

Final Result

你可能也喜欢读下面的文章。

因此,在本教程中,我们已经学习了如何设置 Django 项目以及如何设置 Django 应用程序和。在本教程中,我们还演示了以下主题。

  • 如何创建 Django 项目
  • 如何创建 Django 应用程序
  • 如何设置 Django 应用程序
  • 如何运行 Django 项目
  • 如何停止 Django 项目

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Python Django 中网站的简单联系方式

原文:https://pythonguides.com/simple-contact-form-for-website-in-python-django/

Python & Machine Learning training courses

在这个 Python Django 教程中,我将一步一步地解释如何在 Python Django 中为网站构建简单的联系表单。

最近,我一直在使用 Django 框架为 PythonGuides 创建一个网站。我发现它需要一个联系表格来与网站工作人员沟通。

所以,我做了一些研究,并用 FormClass 为 Django 的一个网站创建了一个联系表单,如下所示。

python django contact form

Simple Contact Form for Website in Python Django

在这里我们将看到:

  • 什么是联系方式
  • 如何在 Python Django 中为网站设置一个简单的联系方式
  • 如何在 Django 中添加 max_length 表单验证
  • 如何在 Django 中将表单呈现为一个段落
  • 如何在 Django 终端上查看表单数据

在本文的最后,您还可以下载代码:在 Python Django 中为网站创建一个简单的联系表单

目录

如何在 Python Django 中为网站创建一个简单的联系表单

现在,让我们一步一步地看看如何为 Python Django 应用程序构建联系人表单。

联系方式

我们可能已经注意到,在大多数公司网站上,网站上有一个页面,允许访问者与网站所有者进行交流。

姓名、地址和评论类型是页面上经常需要的字段,偶尔电子邮件地址也是。该页面称为联系页面,由联系表单组成。

简而言之,联系表单为用户提供了一种快速、简便的方式来询问公司问题。

如何在 Python Django 中设置简单的网站联系方式

要启动 Django 项目,请打开终端并输入以下命令。这里 PythonGuides 是 Django 项目的名称。

django-admin startproject PythonGuides

它将创建一个名为 PythonGuides 的新文件夹,并在终端中输入以下命令。

cd PythonGuides

现在,通过在终端中键入下面的命令,在这个项目文件夹中创建一个名为 Contact 的 Django 应用程序。

python manage.py startapp Contact

要激活此应用程序,请将应用程序名称添加到位于 settings.py 文件中的 INSTALLED_APP 列表中。

python django contact form

Settings.py

Django 默认在项目目录中包含一个 urls.py 文件,用于将新构建的应用程序映射到其中。在其中添加下面的代码。

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('Contact.urls')),
]

阅读: Python Django 表单验证

创建简单表单

创建 Django 表单,该表单接受用户对联系人应用程序的输入。为此,在 app 目录中创建 forms.py 文件,并添加下面给出的代码。

from django import forms

# Create your forms here.

class ContactForm(forms.Form):
	first_name = forms.CharField(max_length = 100)
	last_name = forms.CharField(max_length = 100)
	comment = forms.CharField(widget = forms.Textarea, max_length = 1500)

这里,我们创建一个表单类 ContactForm ,它有以下字段。

  1. 的名的姓作为 Django CharFields。每个字符域都有 100 个 max_length 字符的限制。
  2. 作为 Django CharField 的 comment 字段将显示为一个 Textarea。并且有 1500 个 max_length 字符的限制。\

阅读:点击 Django 中的 HTML 按钮运行 Python 函数

在 Django 中以段落形式呈现表单

在 Django 中,应用程序的前端是在模板中定义的,为此,在主项目目录中创建一个名为模板的子目录来存储所有的项目模板。

打开 settings.py 文件,更新 DIRS 指向 Templates 文件夹的位置。

django contact form example

Setting Templates Folder Location

为了定义联系人网页的前端,在模板文件夹中创建一个名为contact.html的 HTML 文件。并添加下面的代码。

<div style="margin:80px">
    <h1 align="center">Contact Form</h1>
    <hr>
    <h4>Contact us directly if you have any queries</h4>
    <hr>
    <br>
    <form method="post">
        {% csrf_token %}
        {{form.as_p}}
        <button type="submit">Submit</button>
    </form>
</div>
  • 首先使用 HTML 标签 h1h4 将标题添加到表单中。
  • 然后用方法 POST 调用表单标签,这样表单在提交时就被发布了。
  • 为了防止表单受到网络攻击并允许您安全地发送信息,请在表单元素中添加 {% csrf_token %}
  • 接下来,使用 form.as_p 标签将表单呈现为一个段落。
  • 最后,添加一个提交按钮来提交表单。

在 Django 终端查看表单数据

为了定义简单联系人表单的主要逻辑,我们打开 views.py 文件并添加下面给出的代码。

from django.shortcuts import render
from .forms import ContactForm

# Create your views here.

def contact(request):
	if request.method == 'POST':
		form = ContactForm(request.POST)
		if form.is_valid():
			first_name = form.cleaned_data['first_name']
			last_name = form.cleaned_data['last_name']
			comment = form.cleaned_data['comment']
			print('First Name:', first_name)
			print('Last Name:', last_name)
			print('Comment:',comment)	      
	form = ContactForm()
	return render(request, "contact.html", {'form':form})
  • 首先从 forms.py 中导入 ContactForm ,然后调用 if 语句,检查请求方式是否为 POST
  • 如果是,我们通过 ContactForm(请求。POST) 将数据绑定到表单类,这样我们就可以进行验证。
  • 现在,调用 is_valid() 来验证用户输入的内容,如果验证成功,调用form . cleaned _ data[' form _ field ']来清理数据,并使用 print() 函数在终端上打印出来。
  • 如果请求方法是 GET ,则使用 render() 函数向用户呈现一个空白的联系人表单。

现在,我们必须用 URL 映射视图以便调用它,因此我们必须在 app 目录中创建一个名为 urls.py 的文件。包括下面的代码。

from django.urls import path
from Contact import views

urlpatterns = [
    path("contact", views.contact, name="contact"),   
]

阅读:如何在 Django 中创建模型

执行 Django 应用程序的联系表

Django 的 manage.py 文件包含一个名为 runserver 的内置子命令,它将为特定的 Django 项目启动一个开发服务器。

在终端中键入下面给出的命令并运行服务器。

python manage.py runserver

每个互联网页面都需要一个唯一的 URL。通过这样做,您的应用程序将能够识别当用户打开该 URL 时显示什么。

默认情况下,Django localhost 将 URL 显示为 127.0.0.1:8000/ 。现在如下扩展这个 URL 来打开联系表单。

127.0.0.1:8000/contact

它成功地打开了 Django 简单联系表单,看起来像这样。

python django contact form

Contact Us

现在,填写联系表单并点击提交按钮,如下所示。

djnago contact form

Simple Contact Form for the website

点击提交后,会在终端上打印出备注

contact form using django python

Output on the terminal after submission of the Contact Form

这就是我们如何为 Django 网站构建一个简单的 Django 联系表单。

阅读: Python Django app 上传文件

下载 Django 建立简单联系完整代码

这是代码。

Build Simple Contact Form

结论

这样,我们就成功地使用 Django 项目中的 form 类构建了一个简单的联系人表单。我们还学习了将表单呈现为一个段落,并在终端中查看表单数据。

您可能也喜欢阅读下面的 Python Django 教程。

此外,我们还讨论了以下主题。

  • 什么是联系方式
  • 如何在 Python Django 中为网站设置一个简单的联系方式
  • 如何在 Django 中添加 max_length 表单验证
  • 如何在 Django 中将表单呈现为一个段落
  • 如何在 Django 终端上查看表单数据

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Python +示例中的字符串切片

原文:https://pythonguides.com/slicing-string-in-python/

Python & Machine Learning training courses

在这个 Python 教程中,我们将通过几个例子来讨论 Python 中的切片字符串。

  • Python 中的切片字符串
  • python 中的反向字符串切片
  • 使用切片反转字符串 python

目录

在 Python 中切片字符串

Python 切片是通过切片从给定的字符串中获得一个子字符串。为了获取字符串的一部分,我们将指定开始索引和结束索引,用冒号分隔。

举例:

my_str = "Welcome, to Python!"
print(my_str[3:7])

写完上面的代码(对一个 string python 切片),你将打印“my _ str[3:7]”然后输出将显示为“来”。在这里,你会得到从位置 3 到位置 7 的字符不包括在内。

你可以参考下面的截图切片一个字符串 python。

Slicing a string python

Slicing a string python

另外,检查:如何在 Python 中从列表中获取字符串值

Python 中字符串的反向切片

现在,让我们看看 Python 中的字符串反向切片的代码。

对于给定字符串的反向切片,我们将使用 join()reversed() 。我们在内存中反转字符串,并加入分割的字符数,它将返回一个字符串。

举例:

my_str = "PythonGuides"
print("Original string is: " + my_str)
v = 6
result = ' '.join(reversed(my_str[0:v]))
print("The reversed sliced string is: " +result)

写完上面的代码(python 中给定字符串的反向切片),一旦打印出“结果”,那么输出将显示为“反向切片的字符串是:nohtyP”。这里,它将返回切片后的反向字符串。

可以参考下面截图python中给定字符串的反向切片。

reverse string slicing in python

Reverse slicing of a given string in python

这是 python 中反向字符串切片的一个例子。

阅读: Python 在字符串中查找子串

使用切片反转字符串 python

在 python 中,要反转一个字符串,python 中没有内置函数,所以我们将使用从字符串末尾开始并以负值结束的切片

举例:

my_string = "PythonGuide"[::-1]
print(my_string)

写完上面的代码(如何在 python 中反转一个字符串),你将打印这些代码,然后输出将显示为一个 " ediuGnohtyP " 。这里,我们将使用字符串切片来反转字符串。

你可以参考下面的截图 python 中的 python 反转字符串

reverse string python using slicing

reverse string python using slicing

这就是如何使用切片在 python 中反转一个字符串。

您可能会喜欢以下 Python 教程:

在本教程中,我们学习了 python 中的切片字符串和 python 中的反向字符串切片

  • 使用切片反转字符串 python

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

如何使用 Turtle 创建 Python 中的贪吃蛇游戏

原文:https://pythonguides.com/snake-game-in-python/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习如何使用乌龟在 Python 中创建一个贪吃蛇游戏。用 Python 创建一个贪吃蛇游戏很容易。

目录

关于贪吃蛇游戏

  • 贪吃蛇游戏概念起源于 1976 年,由一家名为 Gremlin Interactive 的英国公司开发。
  • 贪吃蛇游戏被认为是一种有趣且技巧娴熟的游戏。它在人们中间代代相传。
  • 贪吃蛇游戏中的蛇是用四个方向控制的,如果蛇头撞到墙或者撞到自己,那么这条蛇就死了,游戏会以分数结束。
  • 玩家在游戏中的主要目标是通过收集食物获得尽可能多的分数。
  • 所以,如果你是一个初学者,你学习了海龟,那么你可以用这个模块做一个贪吃蛇游戏。

如果你是 Python turtle 的新手,看看 Python turtle 编程用 Python turtle 绘制彩色填充形状

蟒蛇龟中蛇游戏概述

在这个游戏中,我们将使用以下代码用 python 创建一个贪吃蛇游戏:

  • Turtle 是 python 中的一个预装库,用于创建形状、图片和游戏。
  • 时间–用于计算从 epoch 开始经过的秒数。
  • Random–这个模块用于使用 Random 模块在 python 中生成随机数。
  • penup()–停止乌龟围栏的绘制。
  • speed()–0 到 10 范围内的整数值。所以,0 最快,10 快,6 正常,3 慢,1 最慢。如果没有给定参数,则返回当前速度。
  • color()–返回或设置钢笔颜色和填充颜色。
  • shape()–它将 turtle shape 设置为给定名称的形状。
  • hide turtle()——让乌龟隐形。
  • xcor()–返回乌龟的 x 坐标。
  • ycor()–返回乌龟的 y 坐标。

读取 Python 龟写函数

用蟒蛇龟创建一个贪吃蛇游戏(一步一步)

在这里,我们将解释用 python 编写贪吃蛇游戏的简单方法。建议去抛下面一步。

第一步:

首先,我们将把所有的模块导入到程序中,并且我们将给出游戏的默认值。

import turtle
import time
import random
delay = 0.1
score = 0
high_score = 0

第二步:

  • 现在,我们将为游戏创建窗口屏幕,我们还将创建蛇的头部和蛇的食物。分数会显示在游戏的标题上。
  • 功能龟。Screen()用于创建一个窗口。在这段代码中,我们的窗口是游戏的“wn”
  • 我们要用函数 "wn.title("贪吃蛇游戏")"给窗口起个名字。
  • 为了设置窗口的背景颜色,我们使用了“wn . bgcolor(' black ')”。用“wn . setup(width = X,height = Y)”功能设置窗口高度和宽度。这里,宽度=600,高度=600。
  • 函数 window.tracer(0) 关闭屏幕更新。因为,除了记分板,我们不需要任何屏幕更新,所以它被设置为 0。
  • 现在,我们将创建一个蛇头,它基本上是一只乌龟,它将是一条蛇,它会四处移动。
  • 为了创建一只乌龟,我们将使用“turtle。龟()",赋名头。磁头速度设置为 0,因为我们只是在初始化,磁头不需要移动。
  • 让我们用“head . shape(" circle ")”****“head . color(" green ")”来初始化头部的形状和颜色。
  • 函数 "head.penup()" 确保不画出蛇所走的路径。
  • “head . goto(0,0)”用于将蛇定位到窗口的中心,停止的方向我们将使用 head.direction = "stop"
  • “pen . write()”函数用于在当前海龟位置写入文本。
  • 我们需要每次接触食物时增加蛇身体的功能。所以,我们用了数组。我们创建了一个名为 segments 的数组,它被初始化为空。
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor('black')
wn.setup(width=600, height=600)
wn.tracer(0)
head = turtle.Turtle()
head.speed(0)
head.shape("circle")
head.color("green")
head.penup()
head.goto(0,0)
head.direction = "stop"
food = turtle.Turtle()
food.speed(0)
food.shape("square")
food.color("red")
food.penup()
food.goto(0,100)
segments = []
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("green")
pen.penup()
pen.hideturtle()
pen.goto(0,260)
pen.write("Score:0 High score:0", align = "center", font=("Courier", 24, "normal"))

第三步:

  • 现在,我们需要为每个方向定义一个函数,并将 head.direction 设置为上、下、左、右。
  • 之后,我们将继续前进,使蛇移动。所以,我们将定义一个名为 move() 的函数。
  • 如果头部向上,则“y”坐标增加,如果头部向下,“y”坐标减少。
  • 如果头部向右移动,“x”坐标增加,如果头部向左移动,“x”坐标减少。
def go_up():
    if head.direction != "down":
        head.direction = "up"
def go_down():
    if head.direction != "up":
        head.direction = "down"
def go_left():
    if head.direction != "right":
        head.direction = "left"
def go_right():
    if head.direction != "left":
        head.direction = "right"
def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y+20)
    if head.direction == "down":
        y = head.ycor()
        head.sety(y-20)
    if head.direction == "left":
        y = head.xcor()
        head.sety(x-20)
    if head.direction == "right":
        y = head.xcor()
        head.setx(x+20) 

第四步:

  • 我们将为蛇的运动指定一个关键点。通过点击关键字,我们可以上下左右移动蛇。
  • 我们需要系统来监听我们的控制键,所以我们将添加一个名为 wn.listen() 的函数来监听按键。
  • 每一次按键都需要绑定到一个执行动作的函数。我们将使用函数 " wn.onkeypress(function," key") " 来实现这四个功能。这里,我用“y”表示向上,“h”表示向下,“g”表示向左,“j”表示向右。
  • 现在,我们可以在屏幕上操作一条蛇的运动。
wn.listen()
wn.onkeypress(go_up, "y")
wn.onkeypress(go_down, "h")
wn.onkeypress(go_left, "g")
wn.onkeypress(go_right, "j")

第五步:

  • 所以,现在这个函数在被调用之前什么都不做。每次更新屏幕或窗口时,我们都需要调用该函数。
  • 我们必须确保当它与边界相撞时,蛇会死去。我们已经有了边界的坐标。所以,我们只需要在蛇头碰到坐标的时候重置它的位置。
  • 此外,蛇需要停止移动,因此改变方向停止。
  • 为了减缓蛇的移动,我们需要使用时间模块,否则移动函数的默认行为会非常快。
  • 所以,我们将使用函数 time.sleep() 来降低龟速。
  • 当蛇死亡时,该段需要消失。
  • 所以,现在我们需要设置窗口坐标外的线段的位置。游戏重新开始,因此清除段列表。
  • 我们需要在蛇的身体每次接触到食物时添加一段。所以,我们有条件检查头部与食物的碰撞。
  • 创建一个 new_segment,定义它的速度、形状和颜色,并将其添加到 segments 数组中。
  • 现在,给蛇头加上段是不够的。当蛇头移动时,这些片段也需要移动。
  • 将位置为 x 的最后一段移动到 x-1,从 x-1 移动到 x-2,依此类推。
  • 蛇如果碰到自己就需要死。因此,我们将检查线段和头部之间的距离是否小于 20。如果是,重置磁头位置和磁头方向。
  • 最后,我们需要看到分数增加时的情况。第一个是头和食物碰撞的时候。增加分数并更新高分
  • 我们使用 pen.write() 函数在屏幕上写下分数。
  • 当蛇头撞上边界和自己的尾巴时,我们需要重置分数
  • 然后调用函数 time.sleep(delay) 降低龟速。
while True:
    wn.update()
    if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290:
        time.sleep(1)
        head.goto(0,0)
        head.direction = "stop"
        for segment in segments:
            segment.goto(1000,1000)
        segments.clear()
        score = 0
        delay = 0.1
        pen.clear()
        pen.write("Score: {} High score: {}".format(score, high_score),align="center", font=("Courier", 24, "normal"))
    if head.distance(food) <20:
        x = random.randint(-290,290)
        y = random.randint(-290,290)
        food.goto(x,y)
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("white")
        new_segment.penup()
        segments.append(new_segment)
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen.clear()
        pen.write("Score: {} High score: {}".format(score,high_score), align="center", font=("Courier", 24, "normal"))
    for index in range(len(segments)-1,0,-1:
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x,y)
    if len(segments)>0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x,y)
    move()
    for segment in segments:
        if segment.distance(head)<20:
            time.sleep(1)
            head.goto(0,0)
            head.direction = "stop"
            for segment in segments:
                segment.goto(1000,1000)
            segments.clear()
            score = 0
            delay = 0.1
            pen.clear()
            pen.write("Score: {} High score: {}".format(score,high_score), align="center", font=("Courier", 24, "normal"))
    time.sleep(delay)
wn.mainloop()

使用 turtle 在 python 中完成贪吃蛇游戏的代码:

import turtle
import time
import random
delay = 0.1
score = 0
high_score = 0
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor('black')
wn.setup(width=600, height=600)
wn.tracer(0)
head = turtle.Turtle()
head.speed(0)
head.shape("circle")
head.color("green")
head.penup()
head.goto(0,0)
head.direction = "stop"
food = turtle.Turtle()
food.speed(0)
food.shape("square")
food.color("red")
food.penup()
food.goto(0,100)
segments = []
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("green")
pen.penup()
pen.hideturtle()
pen.goto(0,260)
pen.write("Score:0 High score:0", align = "center", font=("Courier", 24, "normal"))
def go_up():
    if head.direction != "down":
        head.direction = "up"
def go_down():
    if head.direction != "up":
        head.direction = "down"
def go_left():
    if head.direction != "right":
        head.direction = "left"
def go_right():
    if head.direction != "left":
        head.direction = "right"
def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y+20)
    if head.direction == "down":
        y = head.ycor()
        head.sety(y-20)
    if head.direction == "left":
        y = head.xcor()
        head.sety(x-20)
    if head.direction == "right":
        y = head.xcor()
        head.setx(x+20)
wn.listen()
wn.onkeypress(go_up, "y")
wn.onkeypress(go_down, "h")
wn.onkeypress(go_left, "g")
wn.onkeypress(go_right, "j")
while True:
    wn.update()
    if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290:
        time.sleep(1)
        head.goto(0,0)
        head.direction = "stop"
        for segment in segments:
            segment.goto(1000,1000)
        segments.clear()
        score = 0
        delay = 0.1
        pen.clear()
        pen.write("Score: {} High score: {}".format(score, high_score),align="center", font=("Courier", 24, "normal"))
    if head.distance(food) <20:
        x = random.randint(-290,290)
        y = random.randint(-290,290)
        food.goto(x,y)
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("white")
        new_segment.penup()
        segments.append(new_segment)
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen.clear()
        pen.write("Score: {} High score: {}".format(score,high_score), align="center", font=("Courier", 24, "normal"))
    for index in range(len(segments)-1,0,-1:
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x,y)
    if len(segments)>0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x,y)
    move()
    for segment in segments:
        if segment.distance(head)<20:
            time.sleep(1)
            head.goto(0,0)
            head.direction = "stop"
            for segment in segments:
                segment.goto(1000,1000)
            segments.clear()
            score = 0
            delay = 0.1
            pen.clear()
            pen.write("Score: {} High score: {}".format(score,high_score), align="center", font=("Courier", 24, "normal"))
    time.sleep(delay)
wn.mainloop()

输出 1:

Snake game in python using turtle

Snake game in python using turtle

输出 2:

Snake game in python using turtle

Snake game in python using turtle

输出 3:

Snake game in python using turtle

Snake game in python using turtle

您可能会喜欢以下 Python 教程:

我希望现在你可以用 turtle 用 python 创建一个贪吃蛇游戏,并学会如何使用 turtle 模块和 time 模块。在这里,我们学习了使用 turtle 的 python 中的贪吃蛇游戏,我们有完整的源代码和解释。

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Python 中的排序算法(详细教程)

原文:https://pythonguides.com/sorting-algorithms-in-python/

Python & Machine Learning training courses

在本 Python 教程中,我们将讨论Python中的排序算法。此外,我们将看到以下主题:

  • python 中的算法是什么?
  • python 中的排序是什么?
  • Python 内置排序算法
  • python 中的选择排序
  • python 中的插入排序
  • python 中的冒泡排序
  • python 中的合并排序
  • python 中的快速排序
  • Python 排序算法时间复杂度
  • python 中的一种最佳排序算法
  • 使用库的 Python 排序算法

目录

python 中的算法是什么?

python 中的算法是一个循序渐进的过程,它定义了一组按照一定顺序执行以获得输出的指令。算法通常是独立于底层语言创建的。这可以是一个简单的过程,比如排序、两个数相乘、两个数相加等。

python 中的排序是什么?

排序是指按照特定的顺序排列数据,最常见的顺序是数字顺序。排序的重要性在于数据搜索得到优化,而且它以一种更可读的格式表示数据。这些算法可以用来组织杂乱的数据,使其更容易使用。

Python 内置排序算法

为了对 python 中的元素进行排序,我们可以使用内置函数 sorted() 对任意 Python 列表进行排序。它提供了对数据进行排序的能力。

举例:

my_arr = [10, 3, 6, 8, 2, 9]
s = sorted(my_arr)
print(s)

写完上面的代码( python 内置排序算法,一旦你将“s”打印出来那么输出就是【2,3,6,8,9,10】。当我们调用 sorted()时,我们用一个新的排序列表以排序的方式获得输出。

python 内置排序算法可以参考下面截图。

sorting algorithms in python

Python built-in sorting algorithm

python 中的选择排序

Python 选择排序是一种比较排序算法,用于对元素列表进行升序排序。在选择排序中,我们从获取给定列表中的最小值开始,并与每个元素进行比较。

举例:

def sort(numbers):
    for i in range(4):
        min_pos = i
        for j in range(i,5):
            if numbers[j] < numbers[min_pos]:
               min_pos = j
        temp = numbers[i]
        numbers[i] = numbers[min_pos]
        numbers[min_pos] = temp
numbers = [8, 6, 4, 2, 3]
sort(numbers)
print(numbers)

写完上面的代码(python 中的选择排序,一旦打印出【数字】,那么输出将是【2,3,4,6,8】。这里,我们对未排序列表中的每个剩余元素重复这个过程,最后,未排序列表中的所有元素都被排序。

python 中的选择排序可以参考下面的截图。

Selection sort in python

Selection sort in python

python 中的插入排序

Python 插入排序是 Python 中简单的排序算法之一。它包括为列表中的给定元素找到正确的位置。

我们比较前两个元素,然后通过比较对它们进行排序,再一次我们取第三个元素,找到它在前两个元素中的位置,依此类推。

举例:

def insertion_sort(L):
    for i in range(1, len(L)):
        j = i-1
        next_e = L[i]
        while (L[j] > next_e) and (j >= 0):
            L[j+1] = L[j]
            j = j-1
            L[j+1] = next_e
my_list = [12,3,23,40,20,11]
insertion_sort(my_list)
print(my_list)

写完上面的代码(python 中的插入排序),一旦打印出“my _ list”那么输出将是【3,11,12,20,23,40】。在这里,排序包括通过比较当前元素和下一个元素来找到元素的正确位置,并按升序对它们进行排序。

python 中的插入排序可以参考下面的截图

Insertion sort in python

Insertion sort in python

python 中的冒泡排序

Python 冒泡排序是 Python 中最简单的排序算法,如果相邻元素的顺序不对,它会重复交换相邻元素,直到元素排序完毕。

它包括通过一个接一个地比较和交换来多次遍历一个列表。

举例:

def sort(numbers):
    for i in range(len(numbers)-1,0,-1);
        for j in range(i):
            if numbers[j]>numbers[j+1]:
               temp = numbers[j]
               numbers[j] = numbers[j+1]
               numbers[j+1] = temp
numbers = [6, 3, 7, 5, 8, 2]
sort(numbers)
print(numbers) 

写完上面的代码(python 中的冒泡排序),一旦你将打印出【数字】那么输出将是【2,3,5,6,7,8】。这里,元素将按升序排序,在每一步中,最大的元素将在列表的末尾冒泡。

python 中的冒泡排序可以参考下面的截图

Bubble sort in python

Bubble sort in python

python 中的归并排序

Python Merge sort 基于分而治之的方法,它首先将数组分成大小相等的两部分,对每一半进行递归排序,然后以排序的方式将它们组合起来。

举例:

def merge_sort(unsorted):
    if len(unsorted) <= 1:
        return unsorted
    middle = len(unsorted) // 2
    l_list = unsorted[:middle]
    r_list = unsorted[middle:]
    l_list = merge_sort(l_list)
    r_list = merge_sort(r_list)
    return list(merge(l_list, r_list))
def merge(l_half,r_half):
    s = []
    while len(l_half) != 0 and len(r_half)!=0:
        if l_half[0] < r_half[0]:
            s.append(l_half[0])
            l_half.remove(l_half[0])
        else:
            s.append(r_half[0])
            r_half.remove(r_half[0])
    if len(l_half) == 0:
       s = s + r_half
    else:
       s = s + l_half
    return s
unsorted = [34, 44, 22, 25, 18, 11]
print(merge_sort(unsorted))

写完上面的代码(python 中的 merge sort),一旦你将打印“merge _ sort(未排序)”那么输出将是【11,18,22,25,34,44】。这里,元素将被分成两半,并递归地将输入分成两半。

一个函数,它合并两半,最后产生一个排序的数组。

python 中的合并排序可以参考下面的截图

Merge sort in python

Merge sort in python

python 中的快速排序

Python Quicksort 是一种基于分治法的算法,其中一个数组被分割成子数组。从数组中选择一个枢纽元素。这里,pivot 元素是 s[0],比 pivot 元素小的元素放在左边,大的元素放在右边。

举例:

def quick_sort(s):
    if len(s) == 1 or len(s) == 0:
       return s
    else:
        pivot = s[0]
        i = 0
        for j in range(len(s)-1):
            if s[j+1] < pivot:
               s[j+1],s[i+1] = s[i+1],s[j+1]
               i += 1
        s[0],s[i] = s[i],s[0]
        first_part = quick_sort(s[:i])
        second_part = quick_sort(s[i+1:])
        first_part.append(s[i])
        return first_part + second_part
my_list = [64,25,83,47,67,14]
quick_sort(my_list)
print(my_list)

写完上面的代码(python 中的 Quicksort),一旦你将打印“my _ list”那么输出将是【14,25,47,64,67,83】。这里,元素将被分成两个子数组,这些子数组被递归调用来对元素进行排序。将 pivot 元素与第一个索引中的元素进行比较。

关于 python 中的快速排序,可以参考下面的截图

Quicksort in python

Quicksort in python

Python 排序算法时间复杂度

Python 排序算法的效率取决于两个参数:

  1. 时间复杂度–它被定义为所需的步骤数取决于输入的大小。
  2. 空间复杂度–空间复杂度是程序执行所需的总内存空间。

所有排序算法的时间复杂度:

| 算法 | 最佳 | 平均值 | 最差 |
| 选择排序 | Ω(n^2) | θ(n^2) | O(n^2) |
| 插入排序 | Ω(n) | θ(n^2) | O(n^2) |
| 冒泡排序 | Ω(n) | θ(n^2) | O(n^2) |
| 合并排序 | Ω(n log(n)) | θ(n log(n)) | O(n log(n)) |
| 快速分类 | Ω(n log(n)) | θ(n log(n)) | O(n^2) |

Time Complexity

python 中的一种最佳排序算法

  • 快速排序算法是最有效的排序算法之一,这也是它被广泛使用的原因,因为它是最佳算法之一。
  • 快速排序使用带有递归的分治算法。
  • 快速排序的时间复杂度在最好的情况下是 O(n log n),在一般情况下是 O(n log n),在最坏的情况下是 O(n^2。
  • 快速排序也被认为是【最快】的排序算法,因为它在大多数输入的平均情况下具有最佳性能。

使用库的 Python 排序算法

  • Python 有一个强大的包,可以在列表上执行许多不同类型的稳定和不稳定排序算法。这个包对程序员和开发者很有帮助,基于他们的需求,他们可以执行任何排序。
  • 为了执行排序算法,我们需要首先从 sorting_techniques import pysort 导入库。
  • 创建一个 "s_obj" 排序对象。

举例:

from sorting_techniques import pysort
s_obj = pysort.Sorting()

使用 python 中的库进行冒泡排序

这里,我们将通过使用 python 中的库来执行冒泡排序。

举例:

from sorting_techniques import pysort
s_obj = pysort.Sorting()
my_list = [34,56,43,22,19,10]
l_sort = s_obj.bubbleSort(my_list)
print(l_sort)

写完上面的代码(使用 python 中的库进行冒泡排序),一旦你将打印“l _ sort”那么输出将是【10,19,22,34,43,56】。这里,我们创建了一个 s_obj ,然后 l_sort 将生成一个排序结果,该结果将打印排序后的列表。

你可以参考下面的截图,使用 python 中的库进行冒泡排序

Bubble sort using the library in python

Bubble sort using the library in python

使用 python 中的库进行插入排序

这里,我们将通过使用 python 中的库来执行插入排序。

举例:

from sorting_techniques import pysort
s_obj = pysort.Sorting()
my_list = [44,36,13,22,29,20]
l_sort = s_obj.insertionSort(my_list)
print(l_sort)

写完上面的代码(使用 python 中的库进行插入排序),一旦打印出“l _ sort”,那么输出将是【13,20,22,29,36,44】。这里,我们创建了一个 s_obj ,然后 l_sort 将生成一个排序结果,该结果将打印排序后的列表。

关于使用 python 中的库进行插入排序,可以参考下面的截图

Insertion sort using the library in python

Insertion sort using the library in python

使用 python 中的库进行选择排序

我们将使用 python 中的库来执行插入排序。

举例:

from sorting_techniques import pysort
s_obj = pysort.Sorting()
my_list = [64,86,33,32,29,30]
l_sort = s_obj.selectionSort(my_list)
print(l_sort)

写完上面的代码(使用 python 中的库进行选择排序),一旦你打印出“l _ sort”,那么输出将是【29,30,32,33,64,86】。现在,我们创建了一个 s_obj ,然后 l_sort 将生成一个排序结果,该结果将打印排序后的列表。

你可以参考下面的截图,使用 python 中的库进行选择排序

Selection sort using the library in python

Selection sort using the library in python

使用 python 中的库进行合并排序

我们将通过使用 python 中的库来执行合并排序。

举例:

from sorting_techniques import pysort
s_obj = pysort.Sorting()
my_list = [14,16,13,22,25,30]
l_sort = s_obj.mergeSort(my_list)
print(l_sort)

写完上面的代码(使用 python 中的库进行 merge sort),一旦你将打印“l _ sort”那么输出将是【13,14,16,22,25,30】。现在,我们创建了一个 s_obj ,然后 l_sort 将生成一个排序结果,该结果将打印排序后的列表。

你可以参考下面的截图,使用 python 中的库进行合并排序

Merge sort using the library in python

Merge sort using the library in python

您可能会喜欢以下 Python 教程:

在这个 Python 教程中,我们学习了 python 中的排序算法。此外,我们还讨论了以下主题:

  • python 中的算法是什么?
  • python 中的排序是什么?
  • Python 内置排序算法
  • python 中的选择排序
  • python 中的插入排序
  • python 中的冒泡排序
  • python 中的合并排序
  • python 中的快速排序
  • Python 排序算法时间复杂度
  • python 中的一种最佳排序算法
  • 使用库的 Python 排序算法

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Python 中的平方根

原文:https://pythonguides.com/square-root-in-python/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何在 python 中计算平方根。我们已经在博客的末尾创建了一个项目。此外,我们将涵盖这些主题。

  1. Python3 中的平方根
  2. Python 中不带数学的平方根
  3. Python 中带数学的平方根
  4. Python 中带 With SQRT 的平方根
  5. Python 中有无 SQRT 的平方根
  6. Python 程序中的平方根
  7. Python Numpy 中的平方根
  8. Python 示例中的平方根

目录

python 3 中的平方根

平方根是一个数的因数,当它自身相乘时,产生一个原始数。在本节中,我们将学习如何在 Python3 中计算平方根。

  • Python 中的 Math 模块提供了 sqrt() 函数,使用该函数我们可以计算 python3 中数字的平方根。
  • 或者,我们也可以在 python3 中使用乘法运算符(*)生成 square。我们可以把这个数和它本身相乘,得到这个数的平方。比如 7*7=49
  • python 中的指数(**)运算符在 python3 中也可以用来计算平方根。任何有 1/2 次方的数都会产生这个数的平方根。例如,49**2= 7。
  • 在接下来的章节中,我们将详细讨论每一种方法。

又念, Python 数字猜谜游戏

Python 中没有数学的平方根

Math 是 python 中的一个模块,它允许使用 python 对数字进行所有的数学运算。但是在这一节中,我们将介绍如何在没有数学模块的情况下在 Python 中求平方根。

  • 数学模块为所有类型的数学运算提供了函数,比如你可以执行平方根、指数、对数、西塔等等。
  • 因为平方根只是数字本身的乘法,所以我们甚至可以在不使用数学模块的情况下执行。
  • 我们将向你展示如何计算平方,然后我们将计算这个数的平方根。
    • 乘法运算符(*)用于计算平方。
    • 指数运算符(**)用于计算平方根。

使用乘法运算符

乘法运算符将两个给定的数相乘。一个数乘以它自己就可以得到平方。在下面的例子中,产生了 7 的平方根。

>>> a = 7
>>> b = 7
>>> square_root = a * b
>>> print(square_root)
49

使用指数运算符

python 中的指数运算符(**)用于计算数字的指数幂。任何幂为 0.5 或 1/2 的数都会给出该数的平方根。比如 49 ^(0.5) = 7

>>> num = 7
>>> power = 2
>>> square_root = num ** 2
>>> print(square_root)
49

如果不是 python 中的条件,则读取

Python 中带数学的平方根

在本节中,我们将学习如何用数学模块在 Python 中求平方根。

  • 数学模块提供各种基础数学运算(加法、乘法、平方根等)的函数。)推进(theta,ceil,factorial,log 等。)
  • 数学模块支持的数学运算由 C 语言定义。
  • 为了使用数学模块,你必须首先导入它,并访问他们的官方网站查看可用的数学方法。
  • 使用 python 数学模块中的 math.isqrt(n) 可以对任何非负数求平方根。
  • 在我们的例子中,我们已经计算了数字 49 的平方根,它应该是 7。
import math
res = math.isqrt(49)
print('result: ', res)

result: 7

读取 Matplotlib 多条形图

Python 中不带 SQRT 的平方根

在本节中,我们将学习如何在不使用 python 数学模块的 sqrt 方法的情况下用 python 计算平方根

  • 任何数的 2 次方等于该数的平方。所以要求平方根,我们可以用数字的 1/2 次方。
  • Python 提供了指数运算符(**)来增加数字的幂。该运算符接受数字和幂。
  • 例如,要找到 49 的平方根,请使用以下代码: 49**0.5 。这里 0.5 是幂,49 是数。
  • 所以这样我们就可以不用 sqrt 方法在 python 中求平方根了。这是一个小演示。

源代码:

在这段代码中,我们在没有使用 sqrt 方法的情况下计算了 49 的平方根。

num = 49
power = 0.5

res = num ** power
print(res)

输出:

在此输出中,计算了 49 的平方根,结果是 7。

square root in  without sqrt

Square Root in Python Without SQRT

读取 Python 查找列表中元素的索引

用 SQRT 在 Python 中求平方根

在本节中,我们将学习如何使用 sqrt 在 python 中计算平方根。

  • Math 模块提供了一个 isqrt() 函数,使用它我们可以计算数字的平方根。
  • 数字必须是正数,以便在 python 中使用这种方法计算平方根。
  • 该过程的第一步是导入 python 中的数学模块。

源代码:

在这段代码中,我们使用数学模块计算了数字的平方根。

import math

res = math.isqrt(49)
print(res)

输出:

在这个输出中,我们使用 python 数学模块的 sqrt 方法来计算 49 的平方根。

python square root in python  sqrt

读取 Python 返回函数

Python 程序中的平方根

在本节中,我们将创建一个基于 cli 的程序来用 python 计算平方根。我们将创建一个基于命令行的程序,该程序将接受来自用户的数字,并在终端或 cli 上显示结果。

源代码:

在这段代码中,我们使用数学模块来计算平方根。用户将输入一个数字,然后显示该数字的平方根。

import math

user_input = int(input('Enter Number: '))
res = math.isqrt(user_input)

print('Result: ', res)

输出:

在这个输出中,用户可以输入任何数字,程序将计算它的平方根。在我们的例子中,我们有输入 49,生成的结果是 7。

Square Root in Python Program

Python Square Root Program

阅读使用 python 从 URL 下载 zip 文件

Python Numpy 中的平方根

在本节中,我们将学习如何使用 python Numpy 计算平方根。

  • Python NumPy 是一个高级库,用于处理数组格式的数据。
  • 使用 python 中的 numpy.sqrt() 方法我们可以计算数组中每个元素的平方根。
  • 该过程的第一步是导入 numpy 库。在这种情况下,“没有找到 numpy 模块”的错误出现,然后安装使用以下命令。
pip install numpy
  • 例如,如果这个数组是[9, 64, 81] ,那么输出将是[3, 8, 9]

源代码:

下面是使用 NumPy 计算平方根的代码。首先,我们导入了 NumPy 模块,然后使用 numpy.sqrt()方法计算了 python 中 NumPy 数组中每个元素的平方根。

import numpy as np

num = np.sqrt([
         [64, 49, 36],
         [81, 225, 100]
        ])

print(num)

输出:

在这个输出中,使用了np.sqrt()NumPy 模块的函数来计算 python 中的平方根。

Square Root in Python Numpy

Square Root in Python Numpy

读取 Python NumPy 2d 数组

Python 例子中的平方根

在这一节中,我们将学习如何使用 python tkinter 创建平方根计算器。

  • python 中的 Tkinter 模块是用来创建图形用户界面(GUI)应用程序的应用程序。
  • 我们已经使用了 python 中数学模块的 math.isqrt() 函数。利用这一点,我们已经计算了用户输入的数字的平方根。
 def sqrt_root():
    r = math.isqrt(var.get())
    res.set(f'Square Root of {var.get()} is {r}')
  • sqrt_root() 是我们在 python 中创建的执行平方根的函数。在这段代码中,var.get()从用户那里收集输入。
  • 该输入在 math.isqrt() 函数中传递,结果存储在变量‘r’中。
  • r '有计算结果,现在我们已经把它显示在标签上了。

源代码:

下面是 python 中平方根的完整源代码。

from tkinter import *
import math

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x200')

def sqrt_root():
    r = math.isqrt(var.get())
    res.set(f'Square Root of {var.get()} is {r}')

var = IntVar()
var.set(49)
res = StringVar()

Label(
    ws,
    text='Square Root Calculator',
    font=('sans-serif', 15),
    relief=SOLID,
    padx=10,
    pady=5
).pack(pady=(10, 15))

Entry(
    ws,
    textvariable=var,
    font=('sans-serif', 13),
).pack()

Button(
    ws,
    text='Calculate',
    command=sqrt_root,

).pack(pady=(10, 10))

Label(
    ws,
    textvariable=res,
    font=('sans-serif', 15),
    fg='green'
).pack()

ws.mainloop()

输出:

这是基于 Python GUI 的应用程序中的平方根的例子。用户必须输入正数并点击计算按钮。结果将以绿色文本显示。在这种情况下,49 的平方根是 7。

Square Root in Python Example

Square Root in Python Example

您可能会喜欢以下 Python 教程:

在本教程中,我们学习了如何在 python 中计算平方根。此外,我们已经讨论了这些主题。

  • Python3 中的平方根
  • Python 中不带数学的平方根
  • Python 中带数学的平方根
  • Python 中带 With SQRT 的平方根
  • Python 中有无 SQRT 的平方根
  • Python 程序中的平方根
  • Python Numpy 中的平方根
  • Python 示例中的平方根

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

如何在 PyTorch 中压缩张量

原文:https://pythonguides.com/squeeze-a-tensor-in-pytorch/

Python & Machine Learning training courses

有一个时候,我们都需要在 PyTorch 里挤一个张量。在这里,我将解释如何在 PyTorch 中压缩张量。我们还将讨论如何在 PyTorch 中压缩 5D 张量。

最近我在 PyTorch 工作,在 PyTorch 中我们得到了一个 挤压()的需求。所以,在这篇博客中,我也将解释,如何在 PyTorch 中挤压张量。

因此,我们将在本 Python 教程中讨论这些主题。

  • 什么是挤压()
  • 如何在 PyTorch 中压缩张量
  • 如何在 PyTorch 中压缩 5D 张量
  • 如何在 PyTorch 中压缩 0 维张量
  • 如何在 PyTorch 中压缩一维张量
  • 如何在 PyTorch 中压缩二维张量

目录

什么是压榨()

挤压张量我们使用的是 torch.squeeze()函数。当我们压缩一个张量时,压缩方法会返回一个所有维度的新张量,但会分离大小为 1 的张量。

例如:如果输入张量具有(P * 1 * Q * 1 * R * 1)的形状,并且我们在应用挤压方法之后得到的张量将是(P * Q * R)的形状。

在这个例子的帮助下,您可以看到 Squeeze()方法返回了所有维度的新张量,但是它删除了大小 1。

语法:

squeeze()方法的语法:

torch.squeeze(input, dim = None, out= None)

参数:

  • 输入:输入参数用作输入张量。
  • dim = None:dim 是一个可选的整数值,如果给定输入在这个维度上被压缩。
  • out:out 用作输出张量,它是一个可选的关键参数。

所以,有了这个,我们就明白 PyTorch 中什么是 Squeeze()方法了。

阅读:交叉熵损失 PyTorch

如何在 PyTorch 中压缩张量

在这一节中,我们将借助一个例子来学习如何在 PyTorch 中压缩张量。

挤压方法用于返回一个张量,其中大小为 1 的输入的所有维度都被移除。

举例:

在下面的例子中,我们导入 torch 库,然后描述输入变量,之后我们打印输入变量的张量大小,然后我们使用挤压方法。

# Import torch library
import torch
# Describing the variable
p = torch.zeros(4, 1, 4, 1, 4)
# Print the tensor size
print(p.size())
# Describing the variable
q = torch.squeeze(p)
# Print the tensor size
print(q.size())
# Describing the variable
q = torch.squeeze(p, 0)
# Print the tensor size
print(q.size())
# Describing the variable
q = torch.squeeze(p, 1)
# Print the tensor size
print(q.size()) 

输出:

运行上述代码后,我们得到以下输出,其中我们可以看到,使用 Squeeze()方法后,我们得到了所有维度的新张量,但它删除了大小 1。

How to squeeze a tensor in PyTorch

How to squeeze a tensor in PyTorch

这就是我们如何理解如何在 PyTorch 中压缩张量。

阅读: PyTorch nn 线性+例题

如何在 PyTorch 中压缩 5D 张量

在这一节中,我们将学习如何在 PyTorch 中压缩 5D 张量。

这里,我们使用 torch.squeeze()方法压缩了一个 5D 张量,输入张量有两个维度,大小为 1。

举例:

在下面的例子中,我们导入 torch 库,然后描述输入张量变量,之后我们打印输入变量的张量大小,然后我们使用挤压方法,之后我们打印挤压张量后的大小。

# importing torch library
import torch

# Describing the input tensor
inp = torch.randn(5,1,4,1,6)
# print the input tensor
print("Input tensor Size:\n",inp.size())

# Squeeze the tensor
out = torch.squeeze(inp)
# print the size after squeeze tensor
print("Size after squeeze:\n",out.size())

输出:

运行上述代码后,我们得到以下输出,其中我们可以看到,通过使用 Squeeze()方法压缩了一个 5d 张量,并且我们得到输入张量具有大小为 1 的两个维度。

How to squeeze a 5d tensor in PyTorch

How to squeeze a 5d tensor in PyTorch

因此,有了这个,我们明白了如何在 PyTorch 中压缩一个 5d 张量。

阅读: PyTorch 批量标准化

如何在 PyTorch 中压缩 0 维张量

在本节中,我们将学习如何在 PyTorch 中压缩 0 维张量。

这里,我们通过使用 torch.squeeze()方法压缩了 0 维张量,我们得到了所有维的新张量,但它删除了大小 1。

代码:

在下面的代码中,我们正在导入 torch 库,然后我们使用一个 torch.randn() 函数来描述输入张量,之后我们使用 0 维张量的 squeeze() 函数。然后打印出挤压后张量的大小。

# importing torch
import torch
# Describing the input tensor
inp = torch.randn(5,1,4,1,6)
print("Dimension of input tensor:", inp.dim())
print("Input tensor Size:\n",inp.size())

# squeeze the tensor in dimension 0
out = torch.squeeze(inp,dim=0)
print("Size of tensor after squeeze with dim=0:\n",
      out.size())

输出:

在这个输出中,您可以看到 squeeze 方法返回一个大小为 1 的新张量维。

How to squeeze a tensor in 0 dimension in PyTorch

How to squeeze a tensor in 0 dimension in PyTorch

这样,我们已经了解了如何在 PyTorch 中压缩一个张量。

阅读: PyTorch 预训练模型

如何在 PyTorch 中压缩一维张量

在这一节中,我们将学习如何在 PyTorch 中压缩一维张量。

这里我们在 PyTorch 中压缩一维张量。它返回一个新的张量,包含输入张量的每一个维度。

代码:

在下面的例子中,我们导入 torch 库,然后描述输入张量变量,之后打印输入变量的张量大小,然后使用 1 维张量的压缩方法。之后,我们打印挤压张量后的尺寸。

# importing torch
import torch
# creating the input tensor
inp_tensor = torch.randn(4,1,3,1,5)
print("Dimension of input tensor:", inp_tensor.dim())
print("Input tensor Size:\n",inp_tensor.size())

# squeeze the tensor in dimension 1
out_tensor = torch.squeeze(inp_tensor,dim=1)
print("Size of tensor after squeeze with dim=1:\n",
      out_tensor.size())

输出:

运行上面的代码后,我们得到下面的输出,其中我们可以看到,我们在第 1 维挤压,只有这个维度在输出张量中被删除。

How to squeeze a tensor in 1 dimension in PyTorch

How to squeeze a tensor in 1 dimension in PyTorch

这样,我们就知道如何在 PyTorch 中压缩一维张量。

阅读: PyTorch 双星交叉熵

如何在 PyTorch 中压缩二维张量

在这一节中,我们将学习如何在 PyTorch 中压缩二维张量。

这里我们在 PyTorch 中压缩一个二维张量。在二维压缩中,输出张量的形状没有变化。

代码:

在下面的例子中,我们导入 torch 库,然后描述输入张量变量,之后打印输入变量的张量大小,然后使用 2 维张量的压缩方法。之后,我们打印挤压张量后的尺寸。

# importing torch
import torch
# creating the input tensor
inp = torch.randn(6,1,5,1,7)
print("Dimension of input tensor:", inp.dim())
print("Input tensor Size:\n",inp.size())

# squeeze the tensor in dimension 2
out = torch.squeeze(input,dim=2)
print("Size after squeeze with dim=2:\n",
      out.size())

输出:

运行上面的代码后,我们得到了下面的输出,其中我们可以看到,我们在 2 维压缩,输出张量没有任何变化。

How to squeeze a tensor in 2 dimension in PyTorch

How to squeeze a tensor in 2 dimensions in PyTorch

结论

在本教程中,我们已经学习了如何在 PyTorch 中压缩一个张量,并且我们已经讲述了如何在 PyTorch 中压缩一个 5D 张量。我们还讨论了与其实现相关的不同示例。这是我们已经讨论过的例子列表。

  • 什么是挤压()
  • 如何在 PyTorch 中压缩张量
  • 如何在 PyTorch 中压缩 5D 张量
  • 如何在 PyTorch 中压缩 0 维张量
  • 如何在 PyTorch 中压缩一维张量
  • 如何在 PyTorch 中压缩二维张量

另外,看看更多的 Python PyTorch 教程。

Machine learning with Python Training courseVaishali ganotra

我是一名机器学习工程师,目前作为一名 Python 开发人员在 Tsinfo Technologies 工作。我有使用各种 Python 库的经验,比如 Scikit learn、Turtle、PyTorch 等。

堆积条形图 Matplotlib–完整教程

原文:https://pythonguides.com/stacked-bar-chart-matplotlib/

Python & Machine Learning training courses

在本 Python 教程中,我们将讨论 python 中的堆积条形图 matplotlib。在这里,我们将使用 matplotlib 介绍与堆积条形图相关的不同示例。我们还将讨论以下主题:

  • 堆积条形图 matplotlib
  • 如何绘制堆积条形图
  • 堆积条形图 matplotlib 示例
  • 带标签的堆积条形图 matplotlib
  • 堆积条形图图例 matplotlib
  • 堆积条形图 matplotlib 颜色
  • 堆积条形图熊猫数据框
  • 使用 for 循环的堆积条形图
  • 带数值的 Matplotlib 堆积条形图
  • 带有负值的 Matplotlib 堆积条形图
  • Matplotlib 堆叠条形图错误
  • matplotlib 中的水平堆积条形图

目录

堆积条形图 matplotlib

在本节中,我们将学习如何在 Python 的 matplotlib 中绘制堆积条形图。在开始这个话题之前,首先我们要了解什么是堆积条形图是:

堆积条形图也称为堆积条形图。这是一个用来比较整体各部分的图表。在堆积条形图中,每个条形代表一个整体,条形中的线段或部分代表该整体的类别。不同的颜色用来代表这些类别。

stacked bar chart matplotlib

” Stacked Bar Chart “

Matplotlib 如何绘制堆积条形图

当我们在一个类别中有多组数据时,我们可以对每组数据进行挂钩,并调整一个接一个的条形。

堆积条形图中条形图的高度取决于各组结果的组合高度。或者我们可以说是每个条的高度之和。

条函数中绘制堆积条形图,底部参数非常重要。因为我们必须一个接一个地拖动棒,所以下一个棒的底部等于前一个棒值。

以下步骤用于在 matplotlib 中绘制堆积条形图,概述如下:

  • 定义库:导入所需的重要库(用于数据创建和操作:Numpy 和 Pandas,用于数据可视化:来自 matplotlib 的 pyplot)。
  • 定义 X 轴和 Y 轴:定义用于 X 轴和 Y 轴的数据坐标值,或者我们可以说 X 轴和条形高度。
  • 绘制条形图:通过使用 bar() 的方法我们可以绘制条形图。
  • 设置底部:设置下一个条形的底部等于前一个条形的值。
  • 生成绘图:使用 show() 方法在用户窗口上可视化绘图。

阅读如何安装 matplotlib python

堆积条形图 matplotlib 示例

这里我们绘制了不同班级学生之间的堆积条形图。学生分成两堆,女生和男生。

代码:

**# Import Library** import matplotlib.pyplot as plt

**# Define Data** Class = ["First", "Second", "Third", "Fourth", "Fifth"]
Boys = [15, 20, 16, 18, 25]
Girls = [10, 12, 5, 9, 15]

**# Define width of stacked chart** 
w = 0.6

**# Plot stacked bar chart** plt.bar(Class, Boys, w)
plt.bar(Class, Girls, w, bottom=Boys)

**# Display** 
plt.show()
  • 在上面的例子中,我们导入 matplotlib.pyplot 库进行数据可视化。
  • 在此之后,我们定义用于绘图的数据和堆积条形图的宽度
  • 然后,通过使用 plt.bar() 方法,我们绘制一个条形图,并将底部定义为一个参数,以便条形图一个接一个地绘制。
  • 为了在用户屏幕上可视化图表,我们使用 plt.show() 方法。

stacked bar chart matplotlib example

” Output of code: Stacked bar chart “

带标签的堆积条形图 matplotlib

在本节中,我们将学习如何在 matplotlib 中创建带标签的堆积条形图。

要在 x 轴y 轴上添加标签,我们必须分别使用 plt.xlabel()plt.ylabel() 方法。

添加标签的方法如下:

**# To add labels on x-axis** 
matplotlib.pyplot.xlabel(xlabel, fontdict=None,    
                         labelpad=None, loc=None, **kwargs)

**# To add labels on y-axis** 
matplotlib.pyplot.ylabel(ylabel, fontdict=None,    
                        labelpad=None, loc=None, **kwargs) 

上面使用的参数是:

  • xlabel 和 ylabel: 指定标签文本。
  • labelpad: 指定间距。
  • loc: 指定标签的位置。
  • kwargs: 更多文本属性。

让我们看一个带标签的堆积条形图的例子:

**# Import Library** 
import matplotlib.pyplot as plt

**# Define Data** 
Class = ["First", "Second", "Third", "Fourth", "Fifth"]
Pass = [30, 33, 20, 26, 15]
Fail = [1, 2, 3, 1, 4]

**# Define width of stacked chart** 
w = 0.6

**# Plot stacked bar chart**

plt.bar(Class, Pass, w)
plt.bar(Class, Fail, w, bottom=Pass)

**# Add labels** 
plt.xlabel("Classes")
plt.ylabel("No.of students")

**# Display** 
plt.show()
  • 在上面我们使用 plt.bar() 方法和 bottom 参数来绘制堆积条形图。
  • 之后我们使用 plt.xlabel() 方法来定义 x 轴标签。
  • plt.ylabel() 方法用来定义 y 轴代表什么或者我们可以说 y 轴标签被定义了。

stacked bar chart with labels matplotlib

plt.xlabel() and plt.ylabel()

读取 Matplotlib 绘制一条线

堆积条形图图例 matplotlib

在本节中,我们将学习如何在 matplotlib 中创建一个带图例的堆积条形图。要添加图例,请使用 plt.legend() 方法。

添加图例的语法如下:

matplotlib.pyplot.legend()

我们来看一个例子:

**# Import Library** 
import matplotlib.pyplot as plt

**# Define Data** 
Class = ["First", "Second", "Third", "Fourth", "Fifth"]
Male = [15, 20, 16, 18, 25]
Female = [10, 12, 5, 9, 15]

**# Define width of stacked chart** 
w = 0.6

**# Plot stacked bar chart** 
plt.bar(Class, Male, w, label='Male')
plt.bar(Class, Female, w, bottom=Male, label='Female')

**# Add labels** 
plt.xlabel("Classes")
plt.ylabel("Students")

**# Add legend** 
plt.legend()

**# Display** 
plt.show()
  • 在上面的例子中,我们绘制了学生和班级之间的堆积条形图。这里学生酒吧分为男性和女性两类。
  • 这里,我们在一个 bar() 方法中将标签作为参数传递,并设置要打印的标签文本。
  • plt.legend() 方法用于给绘图添加一个图例。

stacked bar chart legend matplotlib

plt.legend()

读取 Matplotlib 两个 y 轴

堆积条形图 matplotlib 颜色

在这里,我们将学习如何在 matplotlib 中改变堆积条形图中堆积条形图的颜色。绕过颜色条()的方法我们可以很容易地改变颜色。

改变条形颜色的语法如下:

matplotlib.pyplot.bar(x, height, bottom, color)

上面使用的参数是:

  • x: 指定 x 轴
  • 高度:指定 y 轴。
  • bottom: 指定绘制另一个条形的数值。
  • 颜色:指定颜色。

让我们来看一个改变堆积条形图的颜色的例子:

**# Import Library** 
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import figure

**# Set figure size** 
figure(figsize=(9,6))

**# Define Data** 
x = ['Class 1', 'Class 2', 'Class 3', 'Class 4', 'Class 5']
A = np.array([35, 30, 29, 28, 26])
B = np.array([10, 15, 16, 9, 11])
C = np.array([5, 6, 9, 10, 8])
D = np.array([2, 1, 3, 2, 1])

**# Plot stacked bar chart
**     
plt.bar(x, A, color='cyan', label='A')
plt.bar(x, B, bottom=A, color='green', label='B')
plt.bar(x, C, bottom=A+B, color='red', label='C')
plt.bar(x, D, bottom=A+B+C, color='yellow', label='D')

**# Define labels
**     
plt.xlabel("Classes")
plt.ylabel("Students")

**# Add legend
**     
plt.legend(loc=1)

**# Display** 
plt.show()
  • 在上面的例子中,我们导入了 matplotlib.plotnumpy库。
  • 接下来,我们使用 numpy 的 figure() 方法设置 figsize,使用 array() 方法定义数据。
  • 然后通过使用 plt.bar() 方法,并通过将底部作为参数来绘制堆积条形图。
  • 这里我们也将 color 作为参数传递给 plt.bar() 方法来改变堆栈的颜色。
  • plt.xlabel()plt.ylabel() 方法分别用于添加 x 轴标签和 y 轴标签。
  • plt.legend() 方法用于给绘图添加图例。
  • plt.show() 方法用于在用户屏幕上可视化绘图。

stacked bar chart matplotlib color

plt.bar(color=None)

又念,水平线 matplotlib

堆积条形图熊猫数据框

在这里,我们将学习如何使用 pandas dataframe 创建堆积条形图。首先,你必须知道如何在熊猫中创建数据帧。

在 pandas 中创建数据帧的语法:

class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)

上面使用的参数是:

  • 数据:指定数据。
  • 索引:指定一个索引。
  • 列:指定结果帧的列。
  • 数据类型:指定数据类型。
  • 复制:从输入中复制数据。

让我们来看一个使用 pandas dataframe 创建堆积条形图的例子:

**# Import Library**

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

**# Create Dataframe**

df = pd.DataFrame([['A', 10, 12, 2, 20], 
                  ['B', 10, 23, 12, 18],
                  ['C', 12, 15, 19, 6],
                  ['D', 10, 18, 11, 19]],
     columns=['Team', 'C++', 'Java', 'Python', 'Php'])

**# View Data**

print(df)

**# Plot stacked bar chart**

df.plot(x='Team', kind='bar', stacked=True,
        title='Stacked Bar Chart Pandas Dataframe', 
        figsize=(12,6))

**# Rotate tick label** 
plt.xticks(rotation='horizontal')

**# Show** 
plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpypandas 库。
  • 之后,我们使用熊猫的 DataFrame() 方法创建数据。
  • 然后,打印数据帧,并使用 plot() 方法绘制堆积条形图。
  • plt.xticks() 方法用于创建刻度标签,旋转参数用于旋转刻度标签我们将其设置为水平

pandas dataframe

print(df)

stacked bar chart pandas dataframe

pd.DataFrame()

读取绘制垂直线 matplotlib

使用 for 循环的堆积条形图

在这里,我们学习使用 Python matplotlib 中的 for 循环创建一个堆叠条形图。

我们来看一个例子:

**# Import Library**

import numpy as np
import matplotlib.pyplot as plt

**# Define Data**

data = np.array([[5, 15, 12, 10, 7, 6],
                 [10, 19, 13, 9, 6, 9],
                 [4, 8, 6, 8, 3, 7],
                 [6, 9, 4, 3, 15, 19],
                 [9, 15, 19, 16, 8, 6]])

list = ['red','blue', 'yellow','pink','cyan','orange']

**# For loop for creating stacked bar chart** 
X = np.arange(data.shape[1])
for i in range(data.shape[0]):
    plt.bar(X, data[i],bottom = np.sum(data[:i], 
            axis =0),color = list[i % len(list)] )

**# Display**

plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpy 库。
  • 然后我们将数据存储在 NumPy 数组中。
  • 接下来,我们迭代每一行数据。这里对于底部参数,第 I 行接收所有行的总和。
  • plt.bar() 方法用于创建堆积条形图。

stacked bar chart using for loop

” Stacked bar chart using for loop “

读取 Matplotlib 反转 y 轴

Matplotlib 带值的堆积条形图

这里我们将使用 matplotlib 创建一个带有数值的堆积条形图。

让我们来看一个带有数值的堆积条形图示例:

**# Import libraries** 
import matplotlib.pyplot as plt
import pandas as pd

**# Define Data** 
df = pd.DataFrame({
    'Male': [35, 20, 43, 12, 19],
    'Female': [20, 11, 18, 6, 9]
 })

Class = ["Fisrt","Second","Third","Fourth","Fifth"]

**# Plot stacked bar chart** 
ax = df.plot(stacked=True, kind='bar')

for bar in ax.patches:
    height = bar.get_height()
    width = bar.get_width()
    x = bar.get_x()
    y = bar.get_y()
    label_text = height
    label_x = x + width / 2
    label_y = y + height / 2
    ax.text(label_x, label_y, label_text, ha='center',    
            va='center')

**# Set Tick labels** 
ax.set_xticklabels(Class,rotation='horizontal')

**# Display chart** 
plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotpandas 库。
  • 在这之后,我们创建了数据帧并定义了一个的列表。
  • 然后通过使用 plot() 方法绘制堆积条形图。
  • 定义为面片中的循环面片组成图表内的一切。
  • 通过使用 get_height()get_width() 方法得到高度和宽度。
  • 最后,我们使用 text() 方法来定义每个堆叠条形的高度,或者我们可以说是向条形添加值。

Matplotlib stacked bar chart with value

” Stacked bar chart with values “

读取将图例放在绘图 matplotlib 外

Matplotlib 带负值的堆积条形图

这里我们将使用 Python matplotlib 绘制一个具有负值的堆积条形图。

我们来看一个例子:

**# Import Library** 
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import figure

**# Set figure size** 
figure(figsize=(9,6))

**# Define Data** 
x = np.arange(3)
y1 = np.array([4, -6, -4])
y2 = np.array([2, -4, -2])
y3 = np.array([3, -3, -5])
y4 = np.array([4, -2, -3])

**# Plot stacked bar chart
**     
plt.bar(x, y1, color='cyan')
plt.bar(x, y2, bottom=y1, color='green')
plt.bar(x, y3, bottom=y1+y2, color='red')
plt.bar(x, y4, bottom=y1+y2+y3, color='yellow')

**# Define labels
**     
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

**# Display** 
plt.show()
  • 在上面的例子中,我们使用 numpy 的 array() 方法定义数据,定义的数据有负值。
  • plt.bar() 方法用于绘制条形图,我们将底部作为参数传递,使其成为一个堆叠条形图。

matplotlib stacked bar chart with negative value

” Stacked bar chart with negative values “

阅读 Matplotlib 另存为 pdf

Matplotlib 堆积条形图错误

在本节中,我们将学习如何绘制有误差的堆积条形图。

让我们看一个例子,我们绘制一个有误差的堆积条形图:

**# Import Library** 
import matplotlib.pyplot as plt
import numpy as np

**# Define Data** 
x = [5, 4, 9]
y = [2, 3, 3]
z = [7, 6, 8]

**# Error bars** 
x_error = np.std(x)
y_error = np.std(y)
z_error = np.std(z)

ind = np.arange(len(bars))
bar_padding = np.add(x, y).tolist()

**# Standard Bar Chart** plt.bar(ind, x, yerr=x_error)
plt.bar(ind, y, yerr=y_error, bottom=x)
plt.bar(ind, z, yerr=z_error, bottom=bar_padding)

**# Display chart** 
plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpy 库。
  • 然后我们定义数据和错误。
  • 接下来,通过使用 plt.bar() 方法我们绘制堆叠条形图,并将底部作为参数传递。

Matplotlib stacked bar chart error

” Stacked bar chart with errors “

读取 Matplotlib 标题字体大小

matplotlib 中的水平堆积条形图

为了在 matplotlib 中创建一个水平堆叠条形图,我们使用了 barh() 方法,并且我们传递了 left 作为该方法的参数,而不是 bottom 参数。

绘制水平堆积条形图的语法:

matplotlib.pyplot.barh(y, width, height=0.8, left=none, align='center', **kwargs)

使用的参数描述如下:

  • y: 指定 Y 轴的坐标。
  • 宽度:指定条形的宽度。
  • 高度:指定条形的高度。
  • 左:指定 x 坐标。

我们来看一个例子:

**# Import Library**

import matplotlib.pyplot as plt

**# Define Data**

Class = ["First", "Second", "Third", "Fourth", "Fifth"]
Boys = [15, 20, 16, 18, 25]
Girls = [10, 12, 5, 9, 15]

**# Define height of stacked chart** 
h = 0.6

**# Plot stacked bar chart**

plt.barh(Class, Boys, w)
plt.barh(Class, Girls, w, left=Boys)

**# Display**

plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplot 库。
  • 在这之后,我们定义条的数据和高度的
  • 然后通过使用 plt.barh() 方法我们绘制一个条形图,并绕过左侧作为参数我们将其创建到堆叠图中。

Horizontal stacked bar chart in matplotlib

plt.barh()

您可能还会喜欢以下 Python Matplotlib 教程:

在本 Python 教程中,我们已经讨论了“堆积条形图 matplotlib”,并且我们还介绍了一些与之相关的例子。这些是我们在本教程中讨论过的以下主题。

  • 堆积条形图 matplotlib
  • 如何绘制堆积条形图
  • 堆积条形图 matplotlib 示例
  • 带标签的堆积条形图 matplotlib
  • 堆积条形图图例 matplotlib
  • 堆积条形图 matplotlib 颜色
  • 堆积条形图熊猫数据框
  • 使用 for 循环的堆积条形图
  • 带数值的 Matplotlib 堆积条形图
  • 带有负值的 Matplotlib 堆积条形图
  • Matplotlib 堆叠条形图错误
  • matplotlib 中的水平堆积条形图

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Python 3 字符串方法及示例

原文:https://pythonguides.com/string-methods-in-python/

Python & Machine Learning training courses

在本 Python 教程中,我们将通过几个例子讨论各种 Python 3 string 方法。这些都是 python 中各种字符串操作的内置方法。我们将讨论下面的方法和一些 python 字符串程序

  • Python 字符串 title()方法
  • Python 字符串 casefold()方法
  • Python 字符串中心()方法
  • Python 字符串 isdigit()方法
  • Python 字符串连接()方法
  • Python 字符串 zfill()方法
  • Python 字符串交换()方法
  • Python 字符串 splitlines()方法
  • Python 字符串 rsplit()方法
  • Python 字符串 isspace()方法
  • Python 字符串 lower()方法
  • Python sting istrip()方法
  • Python string strip()方法
  • Python 示例中的字符串操作
  • 如何在 python 中找到字符串的长度
  • Python 计算字符串中的字符数
  • Python 重复字符串 n 次

目录

Python 3 string methods()

Python 为 Python 中的各种字符串操作提供了很多内置函数或方法。让我们看看 Python 字符串方法的例子。

阅读:Python 中的切片字符串+示例

Python string title()方法

Python title() string 方法用于将每个单词的第一个字符转换为大写,其余字符转换为字符串中的小写。

举例:

msg = "welcome to python"
s = msg.title()
print(s)

写完上面的代码(字符串标题方法 python),你将打印出 " s " ,然后输出将显示为"欢迎使用 Python" 。这里,title()方法用于将每个单词的字符串首字符转换为大写。

关于 string title()方法 python ,可以参考下面的截图。

Python string title() method

String title() method

Python 字符串 casefold()方法

在 python 中,我们可以使用 casefold() string 方法将所有大写字符转换成小写。这里,casefold 方法返回所有字符都是小写的字符串。

举例:

msg = "Welcome To Python"
s = msg.casefold()
print(s)

写完上面的代码(字符串 casefold 方法 python),你将打印出 " s " ,然后输出将显示为"欢迎使用 python" 。这里,casefold()方法返回一个字符串,其中所有字符都是小写字母。

你可以参考下面的截图了解字符串 casefold 的方法

Python string casefold() method

Python string casefold() method

Python 字符串中心()方法

python string center()方法将返回指定大小的居中字符串。这里,center()方法将使字符串居中对齐。

举例:

msg = "Welcome"
s = msg.center(50)
print(s)

写完上面的代码(字符串中心方法 python),你将打印出 " s " ,然后输出将显示为"欢迎"。这里,center()方法将指定大小的字符串居中对齐。

你可以参考下面的字符串中心方法 python 的截图

Python string center() method

Python string center() method

Python 中的 String isdigit()方法

在 python 中, isdigit() 方法会检查字符串是否只包含数字。如果它只包含数字,那么它将返回真,否则返回假。

举例:

msg = "150297"
s = msg.isdigit()
print(s)

写完上面的代码(string isdigit method python),你将打印出 " s " ,然后输出将显示为 " True " 。这里,isdigit()方法将返回 true,因为该字符是一个数字。

可以参考下面截图字符串 isdigit 方法 python。

Python string isdigit() method

Python string isdigit() method

Python 字符串连接()方法

在 python 中, join() 方法通过使用“@”字符作为分隔符将所有项目连接成一个字符串。

举例:

msg = ("Joe", "ricky", "stephen")
s = "@".join(msg)
print(s)

写完上面的代码(字符串连接方法 python),你将打印出 " s " ,然后输出将显示为"乔@里基@斯蒂芬"。这里,join()方法通过使用“@”字符作为分隔符将所有元组连接成一个字符串。

Python 中的 string join()方法可以参考下面的截图。

Python string join() method

Python string join() method

Python 字符串 zfill()方法

让我们看看,如何使用 Python 字符串 zfill()方法

在 python 中,【zfill()方法返回字符串的副本,从左边的零开始,直到它是 5 个字符。

举例:

msg = "20"
s = msg.zfill(5)
print(s)

写完上面的代码(string zfill 方法 python),你将打印出 " s " ,然后输出将显示为 " 00020 " 。这里,zfill()方法将返回从左侧开始直到其指定长度的带有“0”字符的字符串副本。

关于字符串 zfill 方法 python 可以参考下面的截图。

Python string zfill() method

String zfill() method in python

Python string swapcase()方法

Python string swapcase()方法将给定字符串的所有小写字符转换为大写,所有大写字符转换为小写。

举例:

msg = "Hello welcome to Python"
s = msg.swapcase()
print(s)

写完上面的代码(字符串交换方法 python),你将打印出 " s " ,然后输出将显示为" hello WELCOME TO pYTHON "。这里,swapcase()方法返回所有大写字母都是小写的字符串,反之亦然。

你可以参考下面的字符串交换方法 python 的截图

Python string swapcase() method

String swapcase() method python

Python 字符串 splitlines()方法

Python string splitlines()方法用于将换行符处的字符串拆分到列表中。

举例:

msg = "Welcome to python\nNew to python"
s = msg.splitlines()
print(s)

编写上述代码(string splitlines 方法 python)后,您将打印出 " s " ,然后输出将显示为 " ['欢迎使用 python ',' python 新手'] " 。这里,splitlines()方法用于在换行符处拆分字符串。

你可以参考下面的字符串 splitlines 方法 python 的截图

String splitlines method python

Python string splitlines() method

Python 字符串 rsplit()方法

Python string rsplit()方法会用指定的分隔符将字符串从右边拆分成列表。

举例:

msg = "vanilla, chocolate, strawberry"
s = msg.rsplit()
print(s)

写完上面的代码(string rsplit 方法 python),你将打印出 " s " ,然后输出将显示为 " ['香草','巧克力','草莓'] " 。这里,rsplit()方法用于将字符串拆分成列表。

你可以参考下面的字符串 rsplit 方法 python 的截图

Python string rsplit() method

Python string rsplit() method

Python 字符串 isspace()方法

如果字符串中只有空白字符,Python string isspace()方法将返回 true,否则将返回 false。

举例:

msg = "     "
s = msg.isspace()
print(s)

写完上面的代码(string isspace method python),你将打印出 " s " ,然后输出将显示为 " True " 。这里,isspace()方法用于检查字符串中的空白字符。

你可以参考下面的字符串空间方法 python 的截图

Python string isspace() method

Python string isspace() method

Python sting istrip()方法

strip() 函数是 python 中的内置函数。它用于删除字符串开头和结尾的空白,并返回没有空白的原始字符串。

举例:

car_name = "       BMW X3    "
r = car_name.strip()
print("My fav car is",r)

写完上面的代码(strip 在 python 中是做什么的),你将打印出“r”,然后输出将显示为“我最喜欢的车是宝马 X3”。在这里,strip()方法被用来删除开头和结尾的空白。

你可以参考下面的截图,strip 在 python 中是做什么的

Python sting istrip() method

Python sting istrip() method

同样,如果你想从字符串中删除前导和尾随字符,我们可以使用strip(char)方法。

举例:

car_name = "#####...BMW X3`*`CC.."
r = car_name.strip('#*.c')
print("My fav car is",r)

写完上面的代码(python string()方法),你将打印出 " r " ,然后输出将显示为"我最喜欢的车是宝马 X3 " 。这里,strip(character)方法将删除字符串中所有的前导和尾随字符。

可以参考下面截图 python string strip()方法

Python string strip() method

Python string strip() method

Python 字符串 lower()方法

Python string lower()方法用于将字符串中的所有大写字符转换成小写字符。

举例:

my_string = "Welcome to Python Guides"
my_string = my_string.lower()
print(my_string)

在编写完上面的代码(python string lower()方法)后,您将打印出“my _ string”,然后输出将显示为“欢迎使用 python 指南”。这里, string.lower() 方法返回一个小写的字符串。

python string lower()方法可以参考下面的截图。

Python string lower() method

Python string lower() method

Python 字符串 lstrip()方法

Python strip lstrip()方法返回一个新的字符串,从左侧移除了前导空格和指定字符。如果没有参数传递给 lstrip() ,那么它将删除左边的前导空格。

my_str = "   ***www.pythonguides"
r = my_str.lstrip("   ***www.")
print(r)

写完上面的代码(python string lstrip()方法),你将打印出 " r " ,然后输出将显示为 " pythonguides " 。这里, lstrip() 方法用于从字符串中删除任何前导字符或指定字符。

可以参考下面 python string lstrip()方法的截图。

Python string lstrip() method

Python string lstrip() method

Python 示例中的字符串操作

现在,让我们看看 Python 中关于字符串操作的各种例子。

如何在 python 中找到一个字符串的长度

  • 使用 python 中内置的函数 len() ,我们可以使用 len()方法来获得 Python 中给定字符串的长度。
  • 为了找到字符串的长度,内置函数 len()方法返回字符串的长度。
  • 该函数可以将任何字符串值作为输入,并将整数值作为输出返回。

举例:

  • 首先,我们需要取一个字符串值。在下面的 python 代码中,你可以看到,我把值取为“Python”
  • 现在打印 "len(msg)" ,它将返回项目的数量。

Python 求一个字符串的长度

下面是查找字符串长度的 python 代码。

msg = 'Python'
print(len(msg))
  • 写完上面的 Python 代码(字符串长度),你将打印出 "len(msg)" ,然后输出将显示为一个 "6" ,它是作为输出的字符串的长度。另外,你可以参考下面的截图。

python string length

find length of a string in python

Python 计算字符串中的字符数

在 python 中,为了计算字符串中的字符总数,我们将使用 for 循环来迭代字符串中的每个字符。

举例:

my_string = "Hello all"
total = 0
for val in my_string:
total = total + 1
print("Total Number of Characters = ", total)

在编写上述 python 代码(Python 计算字符串中的字符数)后,您将打印这些代码,然后输出将显示为“总字符数= 9”

这里,for 循环将迭代字符串中的每个字符,并且它将增加每个字符的总值。另外,你可以参考下面的截图

Python count characters in a string

Python count characters in a string

这就是如何在 Python 中计算一个字符串中的字符数。

阅读: Python 检查变量是否为数字

Python 重复字符串 n 次

要重复字符串 n 次,我们将使用 " * "重复字符串的语法【string * n】其中 n 为整数重复一个字符串 n 次。

举例:

str_repeat = "Guides" * 5
print(str_repeat)

写完上面的代码(python 重复字符串 n 次),你将打印出 "str_repeat" ,然后输出将显示为" Guides Guides**Guides GuidesGuides "。**这里 n 的值是 5,字符串会重复 n 次。

你可以参考下面的截图 python 重复字符串 n 次

Python repeat string n times

Python repeat string n times

这就是如何在 Python 中重复 n 次字符串。

Python string upper()方法

可以使用 Python string upper() 方法返回大写的字符串。

示例:

x = "pythonguides"

print(x.upper())

输出将是

PYTHONGUIDES

Python string methods

Python String Functions

Python 字符串 lower()方法

您可以使用 Python string lower() 方法以小写形式返回字符串。

示例:

x = "PYTHONGUIDES"

print(x.lower())

输出将是

pythonguides

Builtin methods in python string

Python String Functions

Python strip()方法

我们可以使用 Python 中的 strip()方法删除字符串开头出现的空白。

示例:

x = "   PythonGuides"

print(x.strip())

现在看看这里的输出

Python string lower method

Python String strip() Functions

Python 字符串替换()方法

可以在 Python 中使用 replace() 方法,用另一个字符替换一个字符串内的一个字符,或者用另一个字符串替换一个字符串。

示例:

x = "I love Python"

print(x.replace("love","like")

输出将是

I like Python

Replace method in python string

Python String replace() Functions

Python 中的 split()方法

我们可以使用 Python split()方法将字符串拆分成子字符串。

示例:

x = "python, guides"

print(x.split(","))

输出将是

['python', ' guides']

How to use split method in python string

split() method in python string

Python count()方法

我们可以使用 Python 中的 count() 方法来计算字符串中使用的字符数。

示例:

x = "I love Python"

print(x.count('o'))

所以我们要问在上面的字符串中有多少时间是“o”。输出将是 2。

count function in python string

count() in python string

Python 字符串中心()方法

我们可以使用 Python string center() 方法来获取居中的字符串。

例子

val = "PythonGuides"

y = val.center(20,"O")

print(y)

输出将是

OOOOPythonGuidesOOOO

How to use center function in python

center() in python

您可能会喜欢以下 Python 教程:

在这个 Python 教程中,我们学习了各种 python 3 string methods() 的例子。

  • Python 3 字符串方法()
  • Python 字符串 title()方法
  • Python 字符串 casefold()方法
  • Python 字符串中心()方法
  • Python 中的 String isdigit()方法
  • Python 字符串连接()方法
  • Python 字符串 zfill()方法
  • Python 字符串交换()方法
  • Python 字符串 splitlines()方法
  • Python 字符串 rsplit()方法
  • Python 字符串 isspace()方法
  • Python sting istrip()方法
  • Python 字符串 lower()方法
  • Python 字符串 lstrip()方法
  • Python 示例中的字符串操作
  • 如何在 python 中找到字符串的长度
  • Python 计算字符串中的字符数
  • Python 重复字符串 n 次

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

如何在 Python 中划分数据帧的子集

原文:https://pythonguides.com/subset-a-dataframe-in-python/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习 如何在 Python 中子集化一个数据帧。为了理解各种方法,我们将使用一些内置函数来对 Python 中的数据帧进行子集化。

作为一名开发人员,在制作 Python 项目时,我得到了在 Python 中设置数据帧子集的要求。

在这里我们将看到:

  • 如何使用 loc()在 Python 中对数据帧进行子集化
  • 如何使用 iloc()在 Python 中子集化数据帧
  • 如何在 Python 中使用索引操作符对数据帧进行子集化
  • 选择 student_age 等于或大于 15 的行

目录

如何在 Python 中子集化数据帧

在 Python 中,主要有三种常用的方法,对于理解如何在 Python 中对数据帧进行子集化非常重要。

如何使用 loc() 在 Python 中子集化数据帧

  • 在这一节中,我们将讨论如何使用 loc()对 Pandas 中的数据帧进行子集化。
  • 从数据帧中选择一组所需的行和列的过程称为子集化。
  • 借助 Python 中的 loc() 函数,我们可以基于特定的行、列或两者创建数据框的子集。
  • loc() 函数依靠标签来选择和生成定制的子集,因此我们必须为它提供行或列的标签。
  • 首先在这个例子中,我们将创建一个数据帧,为此我们将使用 Python 中的 pd.dataframe() 函数。

注意:我们必须先创建一个数据帧,然后才能创建它的子集。首先,让我们把它弄清楚。

import pandas as pd

Student_info = {'Student_id': [672,345, 678,123,783],
         'Student_name': ['John','James','Potter','George','Micheal'],
         'Student_age': [17,15,14,12,11]
        }

df = pd.DataFrame(Student_info, columns= ['Student_id','Student_name','Student_age'])
print (df)

下面是下面给出的代码的截图。

How to create a student dataframe in Python Pandas

How to create a student dataframe in Python Pandas

在这种情况下,熊猫用于生成数据帧。DataFrame()技术。

通过提供列的标签和行的索引,Python 中的 loc() 方法也可以用于更改与列相关的行的值。

语法:

下面是 Python Pandas 中 loc()方法的语法

dataframe.loc[row index,['column-names']] = value

举例:

让我们举一个例子,看看如何使用 loc()在 Python 中对数据帧进行子集化。

源代码:

result= df.loc[[0,1,3]]
print(result)

你可以参考下面的截图

How to Subset a DataFrame in Python using loc

How to Subset a DataFrame in Python using loc

这就是如何使用 loc()在 Python 中对数据帧进行子集化。

阅读: Python 熊猫 CSV 教程

如何使用 iloc()在 Python 中对数据帧进行子集化

  • 现在,让我们了解如何使用 iloc()对 Pandas 中的数据帧进行子集划分。
  • Python 中的 iloc()方法允许我们通过基于行和列的索引选择特定值来构造子集。
  • 换句话说,iloc()函数对索引值而不是标签进行操作,loc()函数也是如此。使用行和列的数据和索引号,我们可以挑选并生成 Python 数据帧的子集。

举例:

让我们举一个例子,看看如何使用 iloc()在 Python 中对数据帧进行子集化。

源代码:

result= df.iloc[[0,1,3],[0,2]]
result

下面是以下给定代码的实现

How to Subset a DataFrame in Python using iloc

How to Subset a DataFrame in Python using iloc

正如您在截图中看到的,我们已经讨论了如何使用 iloc()在 Pandas 中设置数据帧的子集。

阅读:如何删除熊猫中的一个栏目

如何在 Python 中使用索引运算符对数据帧进行子集化

  • 在这一节中,我们将讨论如何使用索引操作符对 Pandas 中的数据帧进行子集化。
  • 我们可以通过使用索引运算符方括号来快速构建数据的子集。
  • 在 Python 中,索引是一种通过位置引用 iterable 中特定元素的技术。换句话说,根据您的需求,您可以直接访问 iterable 中您喜欢的元素,并执行不同的操作。

举例:

这里我们将举一个例子,并检查如何使用索引操作符在 Python 中对数据帧进行子集化。

源代码:

df[['Student_id','Student_name']] 

你可以参考下面的截图

How to Subset a DataFrame in Python using Indexing operator

How to Subset a DataFrame in Python using Indexing operator

在本例中,我们已经了解了如何使用索引操作符在 Python 中对数据帧进行子集化。

阅读:Python 熊猫中的 group by

选择 student_age 等于或大于 15 的行

  • 在本节中,我们将讨论如何选择 student_age 等于或大于 15 的行。
  • 为了获得 student_age 等于或大于 15 的所有行,我们将使用 loc()方法。 loc() 函数依靠标签来选择和生成定制的子集,因此我们必须为它提供行或列的标签。

举例:

让我们举一个例子,看看如何选择 student_age 等于或大于 15 的行。

源代码:

new_result = df.loc[df['Student_age'] >= 10]
print (new_result)

下面是以下给定代码的执行过程

Select rows where the student_age is equal or greater than 15

Select rows where the student_age is equal or greater than 15

这就是如何选择 student_age 等于或大于 15 的行。

你可能也喜欢阅读下面的 Python 熊猫教程。

在本文中,我们讨论了如何在 Python 中对数据帧进行子集化。我们还讨论了以下主题。

  • 如何使用 loc()在 Python 中对数据帧进行子集化
  • 如何使用 iloc()在 Python 中子集化数据帧
  • 如何在 Python 中使用索引操作符对数据帧进行子集化
  • 选择 student_age 等于或大于 15 的行

Machine Learning From Basic to AdvancedArvind

Arvind 目前是 TSInfo Technologies 的高级 Python 开发人员。他精通 Python 库,如 NumPy 和 Tensorflow。

如何在 Python 中减去两个数

原文:https://pythonguides.com/subtract-two-numbers-in-python/

Python & Machine Learning training courses

在这个 python 教程中,你将了解到 Python 程序减去两个数,我们还将检查 :

  • Python 程序减去两个数
  • 使用函数减去两个数的 Python 程序
  • Python 程序减去用户输入的两个数
  • 如何在 python 中减去变量
  • 使用函数减去两个浮点数程序
  • python 中减去复数的程序
  • 程序使用类减去数字
  • 不使用算术运算符减去数字的程序
  • Python 程序减去两个二进制数

目录

Python 程序将两个数相减

这里可以看到程序用 python 减去两个数

  • 在这个例子中,我取了两个数字作为数字 1 = 10数字 2 = 7
  • "-" 运算符用于将两个数相减。
  • 我已经用 print(number) 得到了输出。

示例:

number1 = 10
number2 = 7
number = number1 - number2
print(number)

下面的截图显示了输出结果。

Python program to subtract two numbers

Python program to subtract two numbers

这是如何用 Python 减去两个数。

阅读, Python 程序查闰年

Python 程序使用函数将两个数相减

在这里,我们可以看到如何使用 python 中的函数编写一个程序来减去两个数。

  • 在这个例子中,我定义了一个函数为 def sub(num1,num2)
  • 该函数使用表达式作为 return(num1-num2) 返回。
  • 要减去的值作为参数传递到函数中,如 print(sub(90,70))

示例:

def sub(num1,num2):
    return(num1-num2)
print(sub(90,70)) 

你可以参考下面的输出截图。

Python program to subtract two numbers using a function

Python program to subtract two numbers using a function

这段代码,我们可以用 Python 中的函数将两个数相减。

Python 程序将用户输入的两个数相减

现在,我们可以看到如何用 python 写一个程序来减去用户输入的两个数

  • 在这个例子中,我使用了 input() 方法。接受用户的输入。
  • 我已经用 c = a-b 减去了数字。
  • print("结果是",c) 用于获取输出。

示例:

a = int(input("Enter a first number\n"))
b = int(input("Enter a second number\n"))
c = a-b
print("The result is",c)

下面的截图显示了输出。

Python program to subtract two number user input

Python program to subtract two number user input

如何在 python 中减去变量

这里可以看到如何在 python 中减去变量

  • 在这个例子中,我取了两个变量作为变量 1 和变量 2。
  • 变量 1 被赋值为变量 1 = 100 ,变量 2 被赋值为变量 2 = 65
  • 为了减去变量,我使用了 "-" 操作符。
  • 我已经用 print(variable) 得到了输出。

示例:

variable1 = 100
variable2 = 65
variable = variable1 - variable2
print(variable)

结果显示为输出。您可以参考下面的输出截图。

How to subtract variables in python

How to subtract variables in python

上面的代码,我们可以用 Python 中的来减去变量。

程序使用函数减去两个浮点数

在这里,我们可以看到程序使用 python 中的函数减去两个浮点数。

  • 在这个例子中,我使用了 input() 方法。接受用户的输入。
  • float 数据类型用于输入十进制数作为输入。
  • 我已经定义了一个叫做减法的函数为 def subtraction(a,b):
  • 为了减去这些数字,我使用了 sub=a-b.
  • 该函数作为返回子函数返回。
  • 为了得到输出,我使用了 print("Result is:",subtraction(number1,number2))

示例:

number1=float(input("Enter first number: "))
number2=float(input("Enter second number: "))
def subtraction(a,b): 
    sub=a-b
    return sub
print("Result is: ",subtraction(number1,number2))

下面的截图显示了两个数字相减的结果。

Program to subtract two float number using a function

Program to subtract two float number using a function

这段代码,我们可以用 Python 中的函数来用减去两个浮点数。

python 中减去复数的程序

这里可以看到如何用 python 写一个程序来减去复数

  • 在这个例子中,我取了两个复数作为 a =复数(9,8)b =复数(3,5)。
  • complex() 函数用于通过指定实数和虚数来返回复数。
  • 该函数被定义为 def 子复数(a,b)
  • 该函数作为return a–b返回。
  • 我已经使用了 print( "Result is:",subComplex(a,b)) 来获得输出。

示例:

a = complex(9, 8) 
b = complex(3, 5) 
def subComplex( a, b): 
	return a - b 
print( "Result is : ", subComplex(a, b)) 

我们可以看到实数和虚数的减法作为输出。下面的截图显示了输出。

Program to subtract the complex number in python

Program to subtract the complex number in python

上面的代码,我们可以用 Python 中的减去复数

使用类编程减去数字

在这里,我们可以看到如何使用 python 中的类编写一个程序来减去数字。

  • 在这个例子中,我使用了 input() 方法。接受用户的输入。
  • 我已经创建了一个,使用一个构造函数来初始化这个类的值
  • 我创造了一个方法来从数字中减去。
  • 对象是为类创建的,用于传递参数。
  • self 是用于将属性和方法传递给类的关键字。
  • 为了得到输出,我使用了 print("Result:",obj.num())

示例:

a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
class sub():
    def __init__(self,a,b):
        self.a=a
        self.b=b
    def num(self):
        return self.a-self.b
obj=sub(a,b)
print("Result: ",obj.num())

下面的截图显示了输出。

Program to subtract the numbers using class

Program to subtract the numbers using class

这就是我们如何使用 Python 中的类来减去数字。

不使用算术运算符的程序减去数字

在这里,我们可以看到如何在 python 中不使用算术运算符的情况下,编写一个将数字相减的程序。

  • 在这个例子中,我定义了一个函数为 def subtract(a,b)
  • 使用 if 条件,如果条件为真,则返回。
  • 如果条件不成立,则返回 return subtract(a ^ b,(~a & b) < < 1)
  • 在 a 和 b 之间执行异或运算。
  • ~ 用于反转所有位
  • & 操作用于在两位都为 1 时将两位设置为 1。
  • < < 是零填充左移,它通过从右侧推入零来左移。
  • 输入为 a = 25b = 15。
  • 为了得到输出,我使用了print(" a–b is ",subtract(a,b))

示例:

def subtract(a, b):
    if (b == 0):
	    return a
    return subtract(a ^ b, (~a & b) << 1)
a = 25
b = 15
print("a - b is", subtract(a, b))

我们可以看到输出是两个数的相减。您可以参考下面的输出截图。

Program to subtract the numbers without using arithmetic operator

Program to subtract the numbers without using arithmetic operator

这段代码我们可以用来减去数字,而不需要使用 Python 中的算术运算符。

Python 程序将两个数二进制相减

现在,我们可以如何用 python 写一个程序来减去二进制数

  • 在这个例子中,我取了两个二进制数,如数字 1 =‘110010’数字 2 =‘11001’
  • 使用内置函数 bin 减去二进制数。
  • 2 作为基值传递以获得二进制数。
  • 为了得到输出,我使用了 print(result)

示例:

number1 = '110010'
number2 = '11001'
result = bin(int(number1,2) - int(number2,2))
print(result)

我们可以将二进制数视为输出。您可以参考下面的输出截图。

Python program to subtract two numbers binary

Python program to subtract two numbers binary

这是将二进制数减去二进制数的 Python 程序。

您可能会喜欢以下 Python 教程:

在本 Python 教程中,我们学习了关于****的 Python 程序来减去两个数。此外,我们还讨论了以下主题:

*** 如何在 Python 中减去两个数

  • 如何使用 Python 中的函数将两个数相减
  • Python 程序减去用户输入的两个数
  • 如何在 python 中减去变量
  • 如何使用 Python 中的函数减去两个浮点数
  • python 中如何做复数减法
  • 程序使用类减去数字
  • 不使用算术运算符减去数字的程序
  • Python 中如何进行两个数二进制相减

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/**

如何在 Python 中使用 For 循环对列表中的元素求和

原文:https://pythonguides.com/sum-elements-in-list-in-python-using-for-loop/

Python & Machine Learning training courses

在本 Python 教程中,我们将通过几个例子学习如何使用 for 循环对 Python 中的列表元素求和。

目录

使用 For 循环对 Python 中的列表元素求和

让我们举个例子,用不同的方法添加 Python 列表的元素。

使用下面的代码将变量“sum”初始化为零。

sum = 0

使用下面的代码创建一个包含美国前 10 大城市人口数百万的列表,如Los Angeles = 3.9Chicago = 2.7Houston = 2.3Phoenix = 1.6Philadelphia = 1.6San Antonio = 1.5San Diego = 1.4Dallas = 1.3San Jose = 1.0

usa_pop = [8.5, 3.9, 2.7, 2.3, 1.6, 1.6, 1.5, 1.4, 1.3, 1.0]

定义 for 循环,遍历列表“usa_pop”的元素,并使用下面的代码将它们添加到变量“sum”中。

for element in range(0, len(usa_pop)):
    sum = sum + usa_pop[element]

使用下面的代码检查变量“sum”中列表元素的总和。

print(sum)

How To Sum Elements In List In Python Using For Loop

How To Sum Elements In List In Python Using For Loop

使用 Python For 循环中的 add()函数对列表中的元素求和

在模块“operator”下,Python 包含了各种逻辑、按位、关系和其他运算的预定义函数。所以在这种方法中,我们将使用模块操作符的 add()函数。

首先使用下面的代码导入模块操作符。

from operator import*

使用下面的代码将变量“sum”初始化为零。

sum = 0

使用下面的代码创建一个包含美国前 10 大城市人口数百万的列表,如Los Angeles = 3.9Chicago = 2.7Houston = 2.3Phoenix = 1.6Philadelphia = 1.6San Antonio = 1.5San Diego = 1.4Dallas = 1.3San Jose = 1.0

usa_pop = [8.5, 3.9, 2.7, 2.3, 1.6, 1.6, 1.5, 1.4, 1.3, 1.0]

定义 for 循环来访问列表“usa_pop”中的每个元素,并使用 add()函数对列表中的元素求和,代码如下。

for i in usa_pop:
    sum = add(i, 0)+sum

使用下面的代码查看变量“sum”中列表元素的总和。

print(sum)

How To Sum Elements In List In Python Using For Loop Add Function

How To Sum Elements In List In Python Using For Loop Add Function

这是如何在 Python for 循环中使用 add()函数对列表中的元素求和。

另外,请查看:如何将列表追加到另一个列表中

使用 Python For 循环中的 enumerate()函数对列表中的元素求和

使用下面的代码将变量“sum”初始化为零。

sum = 0

使用下面的代码创建一个包含美国前 10 大城市人口数百万的列表,如Los Angeles = 3.9Chicago = 2.7Houston = 2.3Phoenix = 1.6Philadelphia = 1.6San Antonio = 1.5San Diego = 1.4Dallas = 1.3San Jose = 1.0

usa_pop = [8.5, 3.9, 2.7, 2.3, 1.6, 1.6, 1.5, 1.4, 1.3, 1.0]

使用下面的代码定义 for 循环,用 enumerate() 函数访问列表“usa_pop”的每个元素,对列表的元素求和。

for i,d in enumerate(usa_pop):
  sum+=d

使用下面的代码查看变量“sum”中列表的 sum 元素。

print(sum)

Sum Elements in List Using enumerate function in Python For Loop

Sum Elements in List Using enumerate function in Python For Loop

这是如何在 Python For 循环中使用 enumerate()函数对列表中的元素求和。

使用 Python For 循环中的理解对列表中的元素求和

使用下面的代码生成一个包含美国前 10 大城市人口数百万的列表,如Los Angeles = 3.9Chicago = 2.7Houston = 2.3Phoenix = 1.6Philadelphia = 1.6San Antonio = 1.5San Diego = 1.4Dallas = 1.3San Jose = 1.0

usa_pop = [8, 3, 2, 2, 1, 1, 1, 1, 1, 1]

使用 list comprehension 创建 for 循环来访问列表“usa_pop”的每个元素,并使用下面的代码对列表的元素求和。

summ =[i for i in usa_pop]
print(sum(summ))

Sum Elements in List Using Comprehension in Python For Loop

Sum Elements in List Using Comprehension in Python For Loop

看上面的输出,列表中所有元素的求和都是用 Python 中的 comprehension 方法完成的。

我们已经学习了如何使用不同的方法计算列表中存在的元素的总和,例如使用 for 循环的 comprehension、enumerate 和 add()函数。

您可能会喜欢以下 Python 教程:

my picSaurabh

我叫 Kumar Saurabh,是一名 Python 开发人员,在 TSInfo Technologies 工作。此外,像 Python 编程,SciPy,机器学习,人工智能等技术的专业知识。是我喜欢做的事情。

如何在 Python 中求一个数的位数之和

原文:https://pythonguides.com/sum-of-digits-of-a-number-in-python/

Python & Machine Learning training courses

在这个 Python 教程中,我们将讨论几种计算给定数字位数总和的方法。此外,我们将查看各种示例来查找给定数字的数字总和。

作为一名开发人员,在开发 Python 项目时,我需要计算一个数字的总和

在这里我们将看到:

  • 如何在 Python 中用 str()和 int()求一个数的位数之和
  • Python 中使用递归对数字进行求和
  • 如何在 Python 中使用迭代求一个数的位数之和
  • Python 中使用 Sum()对数字的位数求和
  • 如何在 Python 中用蛮力求一个数的位数之和

目录

Python 中数字的位数总和

为了计算数字的位数之和,首先,我们将从用户那里获取输入。接下来,我们将数字分成几个数字,然后将每个数字添加到 sum 变量中。

如果我们有数字 678 ,我们可以通过将 6 + 7 + 8 相加得到数字和,结果是 21。

在 Python 中,在计算一个数字的数字总和时,主要有三种常用且重要的理解方法。

如何在 Python 中用 str()和 int() 求一个数的位数之和

  • 在这一节中,我们将讨论如何在 Python 中使用 str()和 int() 求一个数的数字之和。
  • 在 Python 中, int() 方法用于将字符串值转换为整数, str() 方法用于将整数转换为字符串。

举例:

我们举个例子,检查一下 Python 中如何用 str()和 int() 求一个数的位数之和。

源代码:

USA_state_ZIPCode=int(input("Enter the value"))

total=0

for i in str(USA_state_ZIPCode):
    total=total+int(i)

print("Sum of digits of a number :",total)

在下面给出的代码中,我们首先从用户那里获取输入,然后创建一个变量来存储总数。接下来,我们使用 str() 方法将数字转换为字符串。

之后,我们使用 for 循环来迭代一个数字的每个数字,并通过使用 int() 方法将它们转换为整数。

下面是以下给定代码的实现

How to find the Sum of digits of a number in Python using str and int

Finding sum of digits of a given number in Python using str and int

这是如何在 Python 中用 str 和 int 求一个数的位数之和。

阅读:用 Python 询问用户输入

Python 中使用递归对数字的位数求和

  • 现在让我们看看如何在 Python 中使用递归计算一个数字的位数之和。
  • 递归函数是那些重复调用自己的函数。当一个具体问题就其本身而言被定义时,这种方法被应用。

举例:

在这里,我们将举一个例子,并检查如何在 Python 中使用递归计算一个数字的位数之和。

源代码:

def total_num(i):
    if i< 10:
        return i
    else:
        return i%10 + total_num(i//10)

new_val = int(input("Enter the value :"))
# Display the result
print("Sum of digit an input number is :",total_num(new_val))

在上面的代码中,我们首先使用参数“I”定义了函数“total _ num”来计算总和。接下来,我们将检查条件,如果“I”小于 10,则它将返回 I。如果不是,则通过将该数乘以 10 来计算余数(n%10)。

以(n/10)作为参数递归调用函数。然后将函数值与余数相加得到总和。之后,接受用户的输入,调用函数“total _ num”,并将输入作为一个参数。

下面是以下代码的截图

Sum of digits of a number in Python using recursion

Calculating the sum of digits of a given number in Python using recursion

在这个例子中,我们已经了解了如何在 Python 中使用递归来计算一个数字的位数之和。

阅读: Python 比较运算符

如何在 Python 中使用迭代求一个数的位数之和

  • 在这里,我们将讨论如何在 Python 中使用迭代计算一个数字的位数之和。
  • 为了在这个程序中计算总和,将使用循环语句。要重复运行代码的某一部分,请使用循环。一些循环语句包括 for 循环、while 和 do-while。
  • 将一个数除以 10,得到该数最右边的数字 0。最右边的数字将最终构成余数。使用余数运算符“%”获得余数。用商除以 10 得到一个数的完整位数。每次使用 "//" 得到一个整数商。

举例:

让我们举一个例子,看看如何在 Python 中使用迭代求一个数的位数之和。

源代码:

def total_num(m):    
    total_num = 0
    while (m != 0): 
         total_num = total_num + (m % 10)
         m = m//10
    return total_num    

m=int(input("Enter the value"))
print("Sum of digits of given number :",total_num(m))

在给定的示例中,我们首先用参数“m”定义函数“total_num ”,然后声明一个变量“total _ num”来包含数字的总和。

创建一个循环,直到 n 不为 0,然后将 sum 变量添加到返回的余数 (n%10) 中。修订版 n 到 n/10 调用函数 Sum,将用户的输入作为参数。
打印返回的总值。

你可以参考下面的截图。

How to find the Sum of digits of a number in Python using iteration

How to find the Sum of digits of a number in Python using iteration

这是如何在 Python 中使用迭代来求一个数的位数之和。

阅读:检查一个数是否是素数 Python

Python 中使用 sum() 对数字的位数求和

  • 在本节中,我们将讨论如何在 Python 中使用 sum() 求一个数的位数之和。
  • Python 的 sum() 函数用于计算一个数字在列表中的位数和。
  • 使用 str() 函数将数字转换为字符串,然后使用 strip()map() 方法将字符串转换为数字列表。之后,使用 sum() 方法计算总数。

举例:

这里我们将举一个例子,检查如何在 Python 中使用 sum()求一个数的位数之和。

源代码:

def total_num(m):

    new_val = str(m)
    new_result = list(map(int, new_val.strip()))
    return sum(new_result)

m = 456
print("Sum of numbers :",total_num(m))

在上面的代码中,我们首先使用参数“m”定义了函数“total _ num”来计算总和。接下来,我们使用 str()方法将数字转换为字符串。

下面是以下给定代码的实现。

Sum of digits of a number in Python using sum

Sum of digits of a number in Python using sum

正如你在截图中看到的,我们已经用 sum()讨论了 Python 中一个数字的数字总和。

阅读:如何用 Python 把两个数相加

如何在 Python 中用蛮力求一个数的位数之和

  • 在这一节中,我们将讨论如何在 Python 中使用蛮力求出一个数的位数之和。
  • 这里,我们通过计算整个输入乘以 10 的模数来提取每个数字。

举例:

让我们举个例子,检查一下如何在 Python 中用蛮力求一个数的位数之和。

源代码:

USA_police_num=67232
total_number = 0

while USA_police_num!=0:
	new_char = int(USA_police_num%10)
	total_number += new_char
	USA_police_num = USA_police_num/10

print(total_number)

下面是以下给定代码的实现

How to find the Sum of digits of a number in Python using brute force

How to find the Sum of digits of a number in Python using brute force

在本文中,我们已经讨论了如何在 Python 中计算一个数字的数字总和,我们还讨论了下面给出的方法

  • 如何在 Python 中用 str()和 int()求一个数的位数之和
  • Python 中使用递归对数字进行求和
  • 如何在 Python 中使用迭代求一个数的位数之和
  • Python 中使用 Sum()对数字的位数求和
  • 如何在 Python 中用蛮力求一个数的位数之和

另外,看看更多的 Python 教程。

Machine Learning From Basic to AdvancedArvind

Arvind 目前是 TSInfo Technologies 的高级 Python 开发人员。他精通 Python 库,如 NumPy 和 Tensorflow。

如何在 Python +各种例子中交换两个数

原文:https://pythonguides.com/swap-two-numbers-in-python/

Python & Machine Learning training courses

在这个 python 教程中,你将学习到交换两个数的 python 程序,我们将看到如何在 Python 中交换两个数,我们还将检查 :

  • Python 程序交换两个数
  • Python 程序交换列表中的两个数字
  • 使用函数交换两个数的 Python 程序
  • 不使用第三个变量交换两个数的 Python 程序
  • 使用按位异或来交换两个数的 Python 程序
  • 使用乘法和除法交换两个数的 Python 程序。
  • 使用第三个变量交换两个数的 Python 程序
  • 使用类交换两个数的 Python 程序
  • 使用临时变量交换两个数的 Python 程序
  • 使用元组交换两个数的 Python 程序
  • Python 程序交换用户输入的两个数字
  • python 中三个数的交换
  • 使用 python 中的函数交换三个数
  • Python 程序使用 +运算符交换两个数。
  • Python 程序在没有临时变量的情况下交换四个变量

目录

Python 程序交换两个数

在这里,我们可以看到如何用 python 写一个程序来交换两个数

  • 在这个例子中,我取了两个数字作为数字 1 = 25数字 2 = 30
  • 为了交换数字,我使用了数字 1,数字 2 =数字 2,数字 1
  • 为了得到输出,我使用了 print("number1 = ",number1)print("number2 = ",number2)

示例:

number1 = 25
number2 = 30
number1, number2 = number2, number1
print("number1 =", number1)
print("number2 =", number2)

我们可以看到这两个数字交换了输出。您可以参考下面的输出截图。

Python program to swap two numbers

Python program to swap two numbers

上面的代码,我们可以用 Python 中的来交换两个数。

阅读, Python 程序查闰年

Python 程序交换列表中的两个数

现在,我们可以看到如何用 python 编写程序来交换列表中的两个数字。

  • 在这个例子中,我定义了一个函数为 def swapIndex(list,index1,index2)
  • 参数作为一个列表,index1,index2 传递给函数。
  • 为了交换数字,我使用了 list[index1],list[index2] = list[index2],list[index1]
  • 然后函数作为一个返回列表返回。
  • 要交换的值称为 index1,index2 = 1,3
  • 为了得到输出,我使用了 print(swapIndex(List,index1-1,index2-1))
  • 在索引 1-1 中, -1 代表列表中从 1 开始的索引值

示例:

def swapIndex(list, index1, index2):
	list[index1], list[index2] = list[index2], list[index1]
	return list
List = [25, 85, 30, 40]
index1, index2 = 1, 3
print(swapIndex(List, index1-1, index2-1))

列表中的数字被交换。我们可以在下面的截图中看到输出。

Python program to swap two numbers in a list

Python program to swap two numbers in a list

这段 Python 代码,我们可以用来在 Python 中交换列表中的两个数字。

您可能喜欢:

Python 程序使用函数交换两个数

在这里,我们可以看到如何使用 Python 中的函数编写程序来交换两个数字。

  • 在这个例子中,我将一个名为 swapnumber 的函数定义为 def swapnumbers(a,b)
  • 这里我用了一个叫做临时变量的变量作为 temp = a ,a = b,b = temp 被赋值交换数字。
  • 在这里,我使用了 input() 方法。接受用户的输入。
  • 为了得到输出,我使用了 print("交换两个数之前",(number1,number2))print("交换两个数之后",(a,b))

示例:

def swapnumbers(a, b):
    temp = a
    a = b
    b = temp
    print("After Swapping two Number",(a, b))
number1 = int(input(" Please Enter the First number : "))
number2 = int(input(" Please Enter the Second number : "))
print("Before Swapping two Number",(number1, number2))
swapnumbers(number1, number2)

作为输出,我们可以看到交换前后的数字。您可以参考下面的输出截图。

Python program to swap two numbers using function

Python program to swap two numbers using function

这就是如何使用 Python 中的函数交换两个数。

查看以下 Python 函数示例:

不使用第三个变量的 Python 程序交换两个数

在这里,我们可以看到如何在不使用 python 中的第三个变量的情况下编写程序来交换两个数字

  • 在这个例子中,我使用了 input() 方法。接受用户的输入。
  • 而不是用第三个变量来交换数字。
  • 对数字执行乘法和除法
  • 我已经使用 print("数字 1 的交换数字是%d &)数字 2 是%d" %(a,b)) 得到输出。

示例:

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
a = a * b
b = a / b
a = a / b
print("Swapped numbers of number1 is %d & number2 is %d" %(a,b))

这些数字被交换作为输出。您可以参考下面的输出截图。

Python program to swap two numbers without using third variable

Python program to swap two numbers without using third variable

上面的代码,我们可以用来交换两个数,而不需要使用 Python 中的第三个变量

Python 程序使用按位异或来交换两个数

现在,我们可以看到如何用 python 写一个程序来使用按位异或交换两个数。

  • 在这个例子中,我拿了两个数来交换。
  • 为了交换数字,我使用了按位异或,比如数字 1 =数字 1 ^数字 2数字 2 =数字 1 ^数字 2,数字 1 =数字 1 ^数字 2。
  • 我已经使用 print (“交换后:number1 = ",number1," number2 = ",number2) 得到输出。

示例:

number1 = 30
number2 = 5
number1 = number1 ^ number2;
number2 = number1 ^ number2;
number1 = number1 ^ number2;
print ("After Swapping: number1 = ", number1, " number2 =", number2)

我们可以看到输出中的数字被交换了。您可以参考下面的输出截图。

Python program to swap two numbers using bitwise XOR

Python program to swap two numbers using bitwise XOR

这是使用按位异或来交换两个数的 Python 程序。

使用乘法和除法交换两个数的 Python 程序

现在,我们可以看到如何用 python 写程序用乘法和除法交换两个数。

  • 在这个例子中,我取了两个数字作为 a = 25b = 30。
  • 我们应该乘和除 a,b。
  • 再次将变量 a 赋值为 a = a // b
  • 我已经用 print("After Swapping: a = ",a," b = ",b) 得到了输出。

示例:

a = 25
b = 30
a = a * b
b = a // b;
a = a // b;
print("After Swapping: a =",a, " b =", b);

分配给 a 和 b 的值作为输出进行交换。您可以参考下面的输出截图。

Python program to swap two numbers using multiplication and division.

Python program to swap two numbers using multiplication and division

上面的代码,我们可以用 Python 中的来用乘法和除法交换两个数。

Python 程序使用第三个变量交换两个数

在这里,我们可以看到如何使用 python 中的第三个变量编写一个程序来交换两个数。

  • 在这个例子中,我使用了 input() 方法。接受用户的输入。
  • 在这里,我使用了 temp 作为第三个变量来交换数字。
  • 我已经使用了print(" number 1 的值是% d " % number 1 ")来获得输出。

示例:

number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
temp = number1
number1 = number2
number2 = temp
print("Value of number1 is %d" %number1)
print("Value of number2 is %d" %number2)

您可以参考下面的输出截图。

Python program to swap two numbers with using the third variable

Python program to swap two numbers with using the third variable

这段代码我们可以用 Python 中的第三个变量来交换两个数。

Python 程序使用类交换两个数

在这里,我们可以看到如何使用 python 中的类编写程序来交换两个数字。

  • 在这个例子中,我创建了一个,使用构造函数初始化该类的值。
  • 我发明了一种交换数字的方法。
  • self 是用于将属性方法传递给类的关键字。
  • 我使用了 input() 方法从用户那里获取输入。
  • 对象是为类创建的,用于传递参数。
  • 为了显示交换后的数字,我使用了 obj.display()

示例:

class Number:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def swap(self):
        temp = self.x
        self.x = self.y
        self.y = temp
    def display(self):
        print("After swap a is:", self.x)
        print("After swap b is:", self.y)
x = int(input("Enter first number:"))
y = int(input("Enter second number:"))
obj = Number(x, y)
obj.swap()
obj.display()

下面的屏幕截图显示了输出。

Python program to swap two numbers using class

Python program to swap two numbers using class

这是使用类交换两个数的 Python 程序。

Python 程序使用临时变量交换两个数

在这里,我们可以看到如何使用 python 中的临时变量编写程序来交换两个数字。

  • 在这个例子中,我取了两个变量,并给它们赋值,比如 x = 100,y= 300。
  • 为了交换数字,我使用一个临时变量作为 temp
  • 我已经用 print("after swapping= ",x," y= ",y) 得到了输出。

示例:

x = 100
y= 300
print("before swapping=", x, " y=", y)
temp = x
x = y
y = temp
print("after swapping=", x, " y=", y)

您可以参考下面的输出截图。

Python Program to swap two numbers using a temporary variable

Python Program to swap two numbers using a temporary variable

这是使用 Python 中的临时变量来交换两个数字的 Python 代码。

Python 程序使用元组交换两个数

现在,我们可以看到如何在 python 中使用元组编写程序来交换两个数字。

  • 在这个例子中,我使用了input()方法。接受用户的输入。
  • 我已经用 (x,b)=(b,x) 交换过数字了。
  • 我有 print ("x= ",x," b= ",b) 来获得输出。

示例:

x=int(input("Enter the first number :"))
b=int(input("Enter the second number :"))
print ("x=",x, "b=",b)
(x,b)=(b,x)
print("x=",x, "b=",b)

数字作为输出进行交换。您可以参考下面的输出截图。

Python program to swap two numbers using tuple

Python program to swap two numbers using tuple

这是在 Python 中使用 tuple 来交换两个数字的 Python 代码。

Python 程序交换用户输入的两个数字

在这里,我们可以看到如何编写程序来交换用户在 python 中输入的两个数字

  • 在这个例子中,我使用了 input() 方法。从用户那里获取信息。
  • 这里,我使用了 temp 变量来交换数字。
  • 我已经用 print((a,b)) 得到了输出。

示例:

a = float(input(" Enter the First number "))
b = float(input(" Please Enter the Second number b: "))
print((a, b))
temp = a
a = b
b = temp
print((a, b))

我们可以看到,数字是由用户输入的,然后作为输出进行交换。您可以参考下面的输出截图。

Python program to swap two numbers entered by the user

Python program to swap two numbers entered by the user

这是一个 Python 程序,用来交换用户输入的两个数字。

Python 中三个数的交换

在这里,我们可以看到如何用 python 编写三个数交换的程序。

  • 在这个例子中,我使用了input()方法来获取用户的输入。
  • 在这里,我将变量值赋给了 a。将 a 的值赋给了 b ,将 b 的值赋给了 c ,将 c 的值赋给了 a 变量。
  • 为了得到输出,我使用了 print('交换后 a 的值是{} '。格式(一))

**示例:

a = input("Enter a first number")
b = input("Enter a second number")
c = input("Enter a third number")
print('The value of a is {}'.format(a))
print('The value of b is {}'.format(b))
print('The value of c is {}'.format(c))
variable = a
a = b
b = c
c = variable
print('The value of a after swapping is {}'.format(a))
print('The value of b after swapping is {}'.format(b))
print('The value of c after swapping is {}'.format(c))

您可以参考下面的输出截图。

Swapping of three numbers in Python

Swapping of three numbers in Python

这段代码,我们可以用 Python 中的来交换三个数。

使用 python 中的函数交换三个数字

在这里,我们可以看到如何使用 python 中的函数交换三个数。

  • 在这个例子中,我定义了一个名为 def swapThree(x,y,z) 的函数。
  • 值的和存储在 x 中,接下来 y 存储 x 的值,之后 x 存储 y 的值。
  • 此后,x 存储 z 的值。
  • if name == 'main' 用于在不执行文件时执行代码。
  • 要交换的值被分配给变量。
  • 为了得到输出**,使用 print("交换 x = ",x,",y = ",y,",z = ",z)T1 和 print("交换 x = ",x,",y = ",y,",z = ",z)T3。**

示例:

def swapThree(x, y, z):
	x = x + y + z 
	y = x - (y+z)
	z = x - (y+z)
	x = x - (y+z)
	print("After swapping x =",x,", y =",y,", z =",z)
if __name__ == '__main__':
	x = 2
	y = 4
	z = 6
print("Before swapping x =",x,", y =",y,", z =",z)
swapThree(x, y, z)

您可以参考下面的输出截图。

Swapping of three numbers using function in python

Swapping of three numbers using function in python

这是使用 python 中的函数来交换三个数字的 Python 代码。

Python 程序使用 +运算符交换两个数

在这里,我们可以看到如何使用 python 中的+和–运算符编写程序来交换两个数字

  • 在这个例子中,我使用了 float 数据类型来输入十进制格式的输入。
  • 这两个数相加,然后相减。它再次被赋给变量 x。
  • 我已经用print(" x 的交换值是%.1f & y 是%.1f" %(x,y)) 得到输出。
  • .1f 是浮点数的占位符。

示例:

x = float(input("Enter the first number: "))
y = float(input("Enter the second number: "))
x = x + y
y = x - y
x = x - y
print("Swapped values of x is %.1f & y is %.1f" %(x,y))

您可以参考下面的输出截图。

Python program to swap two numbers using + and - operator.

Python program to swap two numbers using + and – operator.

这是在 Python 中使用+和–运算符交换两个数的 Python 代码。

Python 程序在没有临时变量的情况下交换四个变量

现在,我们可以看到如何用 python 编写一个程序来交换四个变量而不用临时变量

  • 在这个例子中,我定义了一个函数为 def swap(a,b,c,d)。
  • a = a + b,b = a–b,a = a–b用于交换变量 a 和 b
  • a = a + b,b = a–b,a = a–b用于交换变量 b 和 c。
  • c = c + d,d = c–d,c = c–d用于交换变量 c 和 d。
  • 然后将值初始化为变量。该函数称为 swap(a,b,c,d)

示例:

def swap(a, b, c, d):
	a = a + b
	b = a - b
	a = a - b

	b = b + c
	c = b - c
	b = b - c

	c = c + d
	d = c - d
	c = c - d

	print("values after swapping are : ")
	print("a = ", a)
	print("b = ", b)
	print("c = ", c)
	print("d = ", d)
a = 1
b = 2
c = 3
d = 4
print("values before swapping are : ")
print("a = ", a)
print("b = ", b)
print("c = ", c)
print("d = ", d)
print("")
swap(a, b, c, d)

所有四个变量作为输出被交换。您可以参考下面的输出截图。

Python program to swap four variables without temporary variable

Python program to swap four variables without temporary variable

这是在 Python 中没有临时变量的情况下交换四个变量的代码。

Python 程序在没有临时变量的情况下交换三个数字

在这里,我们可以看到如何用 python 写一个 程序,在没有临时变量的情况下交换三个数。

  • 在这个例子中,我已经给变量赋值了。
  • 然后交换数字 x = x + y + z,y = x—(y+z)z = x—(y+z)x = x—(y+z)进行加减运算。
  • 我已经使用了 print("交换 a = ",x,",b = ",y,",c = ",z 之前)print("交换 a = ",x,",y = ",y,",z = ",z 之后)得到输出。

示例:

x = 14
y = 12
z = 97
print("Before swapping a = ",x,", b = ",y,", c = ",z) 
x = x + y + z
y = x - (y+z)
z = x - (y+z)
x = x - (y+z)
print("After swapping a = ",x,", y = ",y,", z = ",z) 

我们可以将交换后的数字视为输出。您可以参考下面的输出截图。

Python program to swap three numbers without a temporary variable

Python program to swap three numbers without a temporary variable

这是在 Python 中没有临时变量的情况下,交换三个数字的 Python 代码。

您可能会喜欢以下 Python 教程:

在这篇 Python 教程中,我们学习了交换两个数的 Python 程序。此外,我们还讨论了以下主题:

  • Python 程序交换两个数
  • Python 程序交换列表中的两个数字
  • 使用函数交换两个数的 Python 程序
  • 不使用第三个变量交换两个数的 Python 程序
  • 使用按位异或来交换两个数的 Python 程序
  • 使用乘法和除法交换两个数的 Python 程序。
  • 使用第三个变量交换两个数的 Python 程序
  • 使用类交换两个数的 Python 程序
  • 使用临时变量交换两个数的 Python 程序
  • 使用元组交换两个数的 Python 程序
  • Python 程序交换用户输入的两个数字
  • python 中三个数的交换
  • 使用 python 中的函数交换三个数
  • Python 程序使用 +运算符交换两个数。
  • Python 程序在没有临时变量的情况下交换四个变量

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/**

语法错误标识符 python3 中有无效字符

原文:https://pythonguides.com/syntaxerror-invalid-character-in-identifier-python3/

Python & Machine Learning training courses

在这个 Python 教程中,我们将讨论修复一个错误, syntaxerror 标识符 python3 中的无效字符,以及 SyntaxError:行继续符后的意外字符。使用 Python 字典Python 列表时,出现错误标识符中的无效字符。

目录

语法错误标识符 python3 中的无效字符

  • 在 python 中,如果你运行代码,那么你可能会得到标识符中的 python 无效字符错误,因为在 Python 变量名称、函数中间有一些字符。
  • 或者最常见的是,我们得到这个错误是因为你从任何网站复制了一些格式化的代码。

举例:

def check(x):
if k in range(4,9):
print("%s in the range"%str(x))
else:
print("not in the range")
check   (5)

写完上面的代码后,我在第 6 行得到了标识符 python error 中的无效字符。

您可以在下面的屏幕截图中看到错误:syntax error:identifier 中的无效字符。

syntaxerror invalid character in identifier python3

python open syntaxerror invalid character in identifier

为了解决标识符 python 错误中的无效字符,我们需要检查代码或删除它并重新键入。基本上,我们需要找到并修复这些字符。

举例:

def check(x):
if k in range(4,9):
print("%s in the range"%str(x))
else:
print("not in the range")
check(5)

在编写了上面的代码( syntaxerror 标识符中的无效字符)之后,一旦您要打印,那么输出将显示为范围中的“ 5”。这里,check (5)已被重新键入,错误已被解决。

检查下面的屏幕截图,标识符中的无效字符已解决。

syntaxerror invalid character in identifier python3

invalid character in identifier python list

语法错误:行继续符后出现意外字符

这个错误发生在编译器发现一个字符不应该在行继续符之后。因为反斜杠在 python 中被称为行继续符,不能用于除法。所以,当它遇到一个整数时,它抛出错误。

举例:

div = 5\2
print(div)

写完上面的代码( syntaxerror:行继续符后的意外字符),一旦你要打印 "div" ,那么错误就会出现为" SyntaxError:行继续符 后的意外字符"。这里,当我们试图划分“5 \ 2”时,引发了 syntaxerror 。使用了无法分割数字的反斜杠 ""

检查下面的截屏语法错误:行继续符后出现意外字符。

SyntaxError: unexpected character after line continuation character

SyntaxError: unexpected character after line continuation character

为了解决这种行继续符后出现意外字符的错误,我们必须使用除法运算符,即前斜杠“/”对数字进行除法运算,以避免这种错误。

举例:

div = 5/2
print(div)

写完上面的代码后(syntax error:python 中的行继续符后的意外字符),您将打印出 "div" ,然后输出将显示为 " 2.5 " 。在这里,我的错误是通过给前斜杠解决的,它将两个数分开。

检查下面的屏幕截图,看行继续符解析后是否有意外字符。

SyntaxError: unexpected character after line continuation character in python

SyntaxError: unexpected character after line continuation character in python

您可能会喜欢以下 Python 教程:

这就是如何解决 python SyntaxError:标识符错误中的无效字符或者标识符 python 列表错误中的无效字符,我们还看到了syntax error:python中的行延续字符后的意外字符。

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

python 语法错误:函数外部的“return”

原文:https://pythonguides.com/syntaxerror-return-outside-function-python/

Python & Machine Learning training courses

在本 Python 教程中,我们将讨论如何修复一个错误,syntax error return outside function python中,无法赋值给函数调用 Python 中的函数在使用 python 中的函数时出现的错误 return outside function Python。

目录

Python 语法错误:函数外的“return”

在 python 中,当缩进或返回函数不匹配时,就会出现这种错误。

举例:

def add(x, y):
  sum = x + y
return(sum)
print(" Total is: ", add(20, 50))

在编写上述代码(syntax error return outside function python)之后,您将打印这些代码,然后错误将显示为“syntax error return outside function python”。这里,第 3 行没有缩进或对齐,因为它在函数外部抛出了一个错误“return”。

可以参考下面截图 python 语法错误:函数外的‘return’

Syntaxerror return outside function python

python syntaxerror: ‘return’ outside function

为了解决这个syntax error:return outside function python我们需要检查代码的缩进是否正确,return 语句也应该在函数内部,这样这个错误就可以解决了。

举例:

def add(x, y):
  sum = x + y
  return(sum)
print(" Total is: ", add(20, 50))

在编写了上面的代码(syntaxerror 在函数 python 外部返回)之后,一旦打印,输出将显示为“Total is: 70”。在这里,第 3 行是通过给出返回语句的正确缩进来解决的,它应该在函数内部,这样我们就可以解决这个语法错误。

你可以参考下面的截图:

Syntaxerror return outside function python

return outside function python

SyntaxError 无法赋值给 python 中的函数调用

在 python 中, syntaxerror:不能赋值给函数调用如果试图给函数调用赋值,就会出现错误。这意味着我们试图给一个函数赋值。

举例:

chocolate = [
     { "name": "Perk", "sold":934 },
     { "name": "Kit Kat", "sold": 1200},
     { "name": "Dairy Milk Silk", "sold": 1208},
     { "name": "Kit Kat", "sold": 984}
]
def sold_1000_times(chocolate):
    top_sellers = []
    for c in chocolate:
        if c["sold"] > 1000:
            top_sellers.append(c)
    return top_sellers
sold_1000_times(chocolate) = top_sellers
print(top_sellers)

写完上面的代码后(syntaxerror:在 python 中不能赋值给函数调用),你将打印出 "top_sellers" ,然后错误将显示为"" syntax error:不能赋值给函数调用"。这里,我们得到错误是因为我们试图给一个函数调用赋值。

你可以参考下面的截图在 python 中不能赋值给函数调用

SyntaxError can't assign to function call in python

SyntaxError can’t assign to function call in python

为了解决这个语法错误:不能分配给函数调用我们必须分配一个函数调用给一个变量。我们必须首先声明变量,后面跟一个等号,后面跟应该赋给该变量的值。因此,我们颠倒了变量声明的顺序。

举例:

chocolate = [
     { "name": "Perk", "sold":934 },
     { "name": "Kit Kat", "sold": 1200},
     { "name": "Dairy Milk Silk", "sold": 1208},
     { "name": "Kit Kat", "sold": 984}
]
def sold_1000_times(chocolate):
    top_sellers = []
    for c in chocolate:
        if c["sold"] > 1000:
            top_sellers.append(c)
    return top_sellers
top_sellers
 = sold_1000_times(chocolate)
print(top_sellers)

在编写完上面的代码(在 python 中不能赋值给函数调用)之后,你要打印的代码将显示为 "[{ "name": "Kit Kat "," sold": 1200},{"name": "Dairy Milk Silk "," sold": 1208}] " 。这里,通过首先给出变量名,然后给出应该分配给该变量的值来解决错误。

你可以参考下面的截图不能在 python 中赋值给函数调用是解决了

SyntaxError can't assign to function call in python

SyntaxError can’t assign to function call in python

您可能会喜欢以下 Python 教程:

这里是如何解决 python SyntaxError:返回外部函数错误和 SyntaxError 不能赋给 python 中的函数调用。这篇文章对下面的错误信息有帮助:

  • 语法错误在函数外部返回
  • python 语法错误:函数外部的“return”
  • 函数 python 外部的返回
  • python 函数外部的“return”
  • python 错误返回到函数外部
  • python 在函数外部“返回”
  • 语法错误返回不在函数中

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流 clip _ by _ value–完整教程

原文:https://pythonguides.com/tensorflow-clip_by_value/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习如何在 Python TensorFlow 中按值裁剪张量。此外,我们将涵盖以下主题。

  • 张量流剪辑值
  • 张量流 clip_by_value 渐变
  • 张量流 clip_by_value 函数
  • S7-1200 可编程控制器
  • 张量流剪辑值唯一

目录

张量流 clip_by_value

  • 在本节中,我们将讨论如何在 Python TensorFlow 中按值裁剪张量。
  • 为了执行这个特定的任务,我们将使用 tf.clip_by_value() 函数。
  • 并且 tf.clip_by_value() 被表示为将张量值裁剪为给定的最小和最大数。

语法:

让我们看看语法,了解 Python TensorFlow 中的 tf.clip_by_value() 函数的工作原理。

tf.clip_by_value
                (
                 t,
                 clip_value_min,
                 clip_value_max,
                 name=None
                )
  • 它由几个参数组成
    • t: 该参数表示输入张量。
    • clip_value_min: 该参数指定最小剪辑值,可扩展为张量的形状。
    • 剪辑值最大值:该参数表示最大剪辑值,可扩展为张量的形状。
    • name:缺省情况下,它采用 none 值,并指定操作的名称。

举例:

让我们举个例子,看看如何在 Python TensorFlow 中按值裁剪张量。

源代码:

import tensorflow as tf

tensor = tf.constant([[-5., -2., 1.], [1., 3., 5.]])
new_result = tf.clip_by_value(tensor, clip_value_min=-1, clip_value_max=1)
output=new_result.numpy()
print(output)

在上面的代码中,我们已经导入了 TensorFlow 库,然后使用 tf.constant() 函数创建了张量。在这个函数中,我们给它分配了整数的正值和负值。

之后,我们使用了 tf.clip_by_value() 函数,并指定输入张量以及最小值和最大值作为参数。

下面是以下给定代码的实现。

Tensorflow clip by value in Python

Tensorflow clip by value in Python

阅读:张量流图-详细指南

张量流 clip_by_value 渐变

  • 在这个程序中,我们将讨论如何在 Python TensorFlow 中使用渐变裁剪。
  • 首先,我们将讨论梯度削波,这是一个函数,其中导数通过网络被修改或削波到阈值,并且还用于修改权重。
  • 有两种方法来执行渐变裁剪,按值裁剪和按规范裁剪。在这个例子中,我们将定义一个最小和最大的剪辑值。

举例:

让我们举个例子,看看如何在 Python TensorFlow 中使用渐变裁剪。

源代码:

import tensorflow as tf
from tensorflow.keras.datasets import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train, x_test = x_train / 255., x_test / 255.

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128,activation='relu'),
  tf.keras.layers.Dense(10)
])
model.compile(
    optimizer=tf.keras.optimizers.Adam(clipvalue=0.5),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
)

在下面给出的代码中,我们通过从 TensorFlow 导入创建了一个数据集模型 mnist.load_data() 。Keras.datasets 导入 mnist 包。创建模型后,我们必须训练和测试给定的模型。

下面是以下给定代码的实现。

TensorFlow clip_by_value gradient

TensorFlow clip_by_value gradient

阅读; Python TensorFlow 占位符

tensorlow clip _ by _ value relu

  • 本节我们将讨论如何在clip _ by _ value()tensor flow Python 中使用 relu 激活函数。
  • 为了执行这一特定任务,我们将使用 tf.keras.layers.ReLU() 函数,该函数将帮助用户调整线性激活函数 ReLU,它用于卷积神经网络。

语法:

让我们看看语法,了解一下 tf 的工作原理。Keras.layers.ReLU() 函数。

tf.keras.layers.ReLU
                    (
                     max_value=None,
                     negative_slope=0.0,
                     threshold=0.0,
                     **kwargs
                    )
  • 它由几个参数组成
    • max_value: 默认情况下不取值,指定最大激活值。
    • negative_slope: 默认取 0 值,表示负斜率集合。
    • 阈值:默认取 0 值,指定阈值激活的阈值。

举例:

import tensorflow as tf

tensor = tf.keras.layers.ReLU()
new_result = tensor([-4.0, -2.0, 0.0, 0.0])
list(new_result.numpy())

在下面的代码中,我们导入了 TensorFlow 库,然后使用了 tf。Keras.layers.ReLU() 函数。一旦执行了这段代码,输出将显示零值。

下面是下面给出的代码的截图。

TensorFlow clip_by_value relu

TensorFlow clip_by_value relu

阅读:Python tensor flow expand _ dims

张量流 clip_by_value 函数

  • 在本例中,我们将讨论如何在 Python TensorFlow 中按值裁剪张量。
  • 为了执行这个特定的任务,我们将使用 tf.clip_by_value() 函数,这个函数被表示为将张量值裁剪为给定的最小和最大数。

语法:

下面是 Python TensorFlow 中 tf.clip_by_value()函数的语法。

tf.clip_by_value
                (
                 t,
                 clip_value_min,
                 clip_value_max,
                 name=None
                )

举例:

 import tensorflow as tf

tensor = tf.constant([[7, 8], [2, 1]],dtype = tf.int32)
min_val = [8, 6]
max_val = [2, 3]

new_result = tf.clip_by_value(tensor, min_val, max_val)
print(new_result) 

在上面的代码中,我们已经导入了 TensorFlow 库,然后使用 tf.constant() 函数创建了张量。在这个函数中,我们给它分配了整数的正值和负值。

之后,我们使用了 tf.clip_by_value() 函数,并指定输入张量以及最小值和最大值作为参数。

你可以参考下面的截图。

TensorFlow clip_by_value example

TensorFlow clip_by_value example

阅读: Python TensorFlow 随机均匀

张量流 clip_by_value unique

  • 在本节中,我们将讨论如何在 Python TensorFlow 中从 clip_by_value 获取唯一值。
  • 为了执行这个特定的任务,首先,我们将通过使用 tf.constant() 函数创建一个张量,并将整数值赋给它。
  • 接下来,我们将使用 tf.clip_by_value() 函数按值裁剪一个张量,然后我们将应用 tf.unique() 函数并从中获取唯一值。

语法:

下面是 Python TensorFlow 中 tf.unique()函数的语法。

tf.unique
         (
          x,
          out_idx=tf.dtypes.int32,
          name=None
         )

举例:

import tensorflow as tf

tensor = tf.constant([-5., -2., 1.,1., 3., 5.])
new_result = tf.clip_by_value(tensor, clip_value_min=-1, clip_value_max=1)
output=new_result.numpy()
new_result=tf.unique(output)
print(new_result)

下面是以下给定代码的执行。

TensorFlow clip_by_value unique

TensorFlow clip_by_value unique

还有,多看看一些 TensorFlow 教程。

在本 Python 教程中,我们已经学习了如何在 Python TensorFlow 中按值裁剪张量。此外,我们还讨论了以下主题。

  • 张量流剪辑值
  • 张量流 clip_by_value 渐变
  • 张量流 clip_by_value 函数
  • S7-1200 可编程控制器
  • 张量流剪辑值唯一

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流将稀疏张量转换为张量

原文:https://pythonguides.com/tensorflow-convert-sparse-tensor-to-tensor/

Python & Machine Learning training courses

你知道如何把稀疏张量转换成张量吗,我们会在 Python 中讨论稀疏张量和一个张量。稀疏张量数据集是其中大多数条目为零的数据集;这方面的一个例子是一个大的对角矩阵。(其中大部分为零)。

  • 张量流将稀疏张量转换为张量
  • 张量流将张量转换为稀疏张量
  • 将张量流张量转换为 torch 张量
  • 张量流将张量转换为数字
  • 张量流将张量转换为维度
  • 张量流张量长度

目录

Tensorflow 将稀疏张量转换为张量

  • 在本节中,我们将讨论如何在 Python TensorFlow 中将稀疏张量转换为张量。
  • 被称为稀疏张量的数据集是其中大多数条目为零的数据集;这方面的一个例子是一个大的对角矩阵。(其中大部分为零)。存储非零值及其相关坐标,而不是张量对象的整组值。

语法:

以下是给定代码的语法

tf.sparse.to_dense(
    sp_input, default_value=None, validate_indices=True, name=None
)

举例:

import tensorflow as tf
new_tensor = tf.SparseTensor(dense_shape=[3, 5],values=[7, 8, 9],indices =[[0, 1],[0, 3],[2, 0]])
result=tf.sparse.to_dense(new_tensor).numpy()
print(result)

在这个例子中,我们导入了 tensorflow 库,然后使用 tf 创建了一个张量。SparseTensor()函数,在这个函数中,我们指定了 dense_shape、值和索引。

接下来,为了将稀疏张量转换成张量,我们使用了。numpy()函数并显示结果。

下面是以下代码的截图

Tensorflow convert sparse tensor to tensor

Tensorflow convert sparse tensor to tensor

这就是我们如何在 Python TensorFlow 中将稀疏张量转换为张量。

阅读:模块“张量流”没有属性“会话”

将张量转换为稀疏张量

  • 这里我们将讨论如何在 Python TensorFlow 中将张量转换为稀疏张量。
  • 在本例中,我们将使用 tf.sparse.from_dense() 函数,该函数用于将密集张量转换为稀疏张量。

语法:

下面是 Python TensorFlow 中*TF . sparse . from _ dense()*函数的语法

tf.sparse.from_dense(
    tensor, name=None
)
  • 它由几个参数组成
    • 张量:该参数定义了要转换为稀疏张量的输入张量和密集张量。
    • name :该参数定义了操作的名称,默认为 none。

举例:

import tensorflow as tf

new_tens = tf.sparse.from_dense([1, 0, 1, 0, 0])
new_tens.shape.as_list()
new_tens.values.numpy()
new_tens.indices.numpy()

你可以参考下面的截图

Convert tensor to sparse tensor

Convert tensor to sparse tensor

正如你在截图中看到的,输出显示了张量到稀疏张量的转换。

阅读:张量流得到形状

如何将张量流张量转换为 torch 张量

  • 让我们讨论如何在 Python TensorFlow 中将 TensorFlow 张量转换为 torch 张量。
  • 在这个例子中,我们将使用 torch.from_numpy()函数,这个 numpy 数组可以使用 torch.from numpy()函数转换成 PyTorch 中的张量。
  • 它预期一个 NumPy 数组(numpy.ndarray)的输入。张量是输出格式。返回的张量和 ndarray 使用的内存是相同的。没有办法调整返回张量的大小。

语法:

下面是 Python 中的 torch.from_numpy() 函数的语法

torch.from_numpy(ndarray)

注意:它只包含一个参数,并且指定 NumPy 数组。

例子

import tensorflow as tf
import torch

tensorflow_tens=tf.constant([12,3,4,5,6])
py_tensors = torch.from_numpy(tensorflow_tens.numpy())
print(py_tensors)

在下面给出的代码中,我们首先导入了所有必需的库,然后使用 tf.constant()函数创建了一个张量。接下来,我们要将张量流张量转换为 PyTorch 张量。为此,我们使用了 torch.from_numpy()函数,并在该函数中为其指定了张量。

下面是以下代码的截图

How to Convert tensorflow tensor to torch tensor

How to Convert tensorflow tensor to torch tensor

这就是我们如何在 Python TensorFlow 中将 tensorflow 张量转换为 torch 张量。

阅读:Python tensor flow reduce _ sum

将张量转换为数字

  • 在这一节中,我们将讨论如何把张量转换成数字。
  • 为了完成这项任务,我们将使用 tf.reduce_sum()函数,该函数用于计算所有维度的张量元素总和。

语法:

让我们看一下语法并理解 Python TensorFlow 中 tf.reduce_sum()函数的工作原理。

tf.math.reduce_sum(
    input_tensor, axis=None, keepdims=False, name=None
)
  • 它由几个参数组成
    • input_tensor :该参数定义了输入张量,用于减少张量。
    • :默认情况下,不取值,降维,检查条件,如果不取值,则降维,所有维度必须在[-rank(input_tensor),rank(input_tensor)]范围内。
    • keepdims :如果为真,则保留长度为 1 的缩减维度。
    • name :默认情况下,取 none 值,指定操作的名称。

举例:

让我们举一个例子,检查如何将输入张量转换为数字。

源代码:

import tensorflow as tf
# Creation of input tensor
new_tensor = tf.constant([[12, 14, 16], [19, 20, 21]])
# By using the tf.reduce_sum() function
new_output_reduce_sum = tf.reduce_sum(new_tensor)
print(new_output_reduce_sum ) 
print(new_output_reduce_sum .numpy())

在下面给出的代码中,我们首先导入 TensorFlow 库,然后通过使用 tf.constant() 函数创建一个输入张量,在这个函数中,我们将整数值指定为一个参数。

接下来,我们要将张量转换成一个数字,为此我们使用了 tf.reduce_sum()函数,并将张量作为一个参数。

下面是下面给出的代码的截图。

Convert TensorFlow to a number

Convert TensorFlow to a number

在这个例子中,我们已经讨论了张量流到数字的转换。

阅读: Python TensorFlow 随机均匀

将张量转换为维度

  • 这里我们将讨论如何在 Python TensorFlow 中将输入张量转换为维度。
  • 为了执行这个任务,我们将使用 tf.shape() 函数,这个函数返回一个包含给定张量形状的张量。

语法:

让我们看看语法,了解一下 Python TensorFlow 中 tf.shape()函数的工作原理。

tf.shape(
    input,
    out_type=tf.dtypes.int32,
    name=None
)
  • 它由几个参数组成
    • 输入:该参数定义输入张量并应用于函数。
    • out_type :默认取 tf.dtypes.int32 ,是该操作指定的输出类型。
    • name :该参数定义了操作的名称,默认为 none。

举例:

import tensorflow as tf

new_tens = tf.constant([[12, 25, 87],
      [18, 29, 28]])
print(tf.shape(new_tens).numpy())

在这个例子中,我们已经通过使用 tf.constant() 函数创建了一个张量,然后使用 tf.shape() 函数获得该张量的维数。

下面是以下给定代码的实现。

Convert Tensor to dimensions

Convert Tensor to dimensions

正如你在截图中看到的,我们已经讨论了张量到维度的转换。

阅读:Python tensor flow expand _ dims

张量流张量长度

  • 在本节中,我们将讨论如何在 Python TensorFlow 中获取输入张量的长度。
  • 通过使用 tf.size() 函数,它将返回输入张量的大小,这个函数有三个参数。

语法:

下面是 Python TensorFlow 中 tf.size()函数的语法。

tf.size(
    input,
    out_type=tf.dtypes.int32,
    name=None
)
  • 它由几个参数组成
    • 输入:该参数定义了输入张量,可以是稀疏张量。
    • out_type :默认取 tf.dtypes.int32 ,指定非量化数值输出。
    • name :指定操作的名称,默认情况下不取值。

举例:

让我们举一个例子,了解我们如何显示输入张量的长度。

import tensorflow as tf

new_tens = tf.constant([[12, 25, 87],
      [18, 29, 28]])
print(tf.shape(new_tens).numpy())

你可以参考下面的截图。

TensorFlow tensor length

TensorFlow tensor length

还有,多看看一些 TensorFlow 教程。

在本 TensorFlow 教程中,我们学习了 如何在 Python 中将稀疏张量转换为张量。此外,我们还讨论了以下一组示例。

  • 张量流将稀疏张量转换为张量
  • 如何将张量转换为稀疏张量
  • 如何将张量流张量转换为 torch 张量
  • 将张量转换为数字
  • 将张量转换为维度
  • 张量流张量长度

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Tensorflow 将字符串转换为整型

原文:https://pythonguides.com/tensorflow-convert-string-to-int/

Python & Machine Learning training courses

这里我们将讨论在 Python TensorFlow 中将字符串转换成整数。我们还会看一些例子,看看如何在 TensorFlow 中将字符串转换成不同的数据类型。我们将讨论这些话题。

  • Tensorflow 将字符串转换为整型
  • TensorFlow 将字符串转换为 int
  • Tensorflow 将字符串转换为浮点型
  • 不支持将 TensorFlow 未实现的字符串转换为 int 64
  • 不支持将 TensorFlow 字符串转换为 int32

目录

Tensorflow 将字符串转换为整型

  • 在本节中,我们将讨论如何在 Python TensorFlow 中将字符串转换为整数。
  • 为了执行这个特定的任务,我们将使用 tf.strings.to_number() 函数,在这个函数中,我们将把字符串转换成一个整数,并给出一个数字类型。

语法:

让我们看一下语法,了解一下 Python TensorFlow 中 tf.strings.to_number() 函数的工作原理

tf.strings.to_number(
    input,
    out_type=tf.dtypes.float32,
    name=None
)
  • 它由几个参数组成
    • 输入:该参数定义了函数将要应用的输入张量。
    • out_type :默认情况下,它采用 df.dtypes.float32() 值,它是一个可选参数,是要分配给字符串张量中每个字符串的数字类型。
    • name :该参数指定操作的名称,默认情况下,取值为 none。

举例:

让我们举个例子,看看如何在 Python TensorFlow 中将字符串转换成整数。

源代码:

import tensorflow as tf

population_of_UnitedStates = tf.constant(['12','56','78','98'])

result= tf.strings.to_number(population_of_UnitedStates,tf.int32)
print(result)

在下面给出的代码中,我们使用 tf.constant() 函数创建了一个张量,该张量的名称为 population_of_UnitedStates,在这个函数中,我们为它分配了字符串值。现在我们想把这个字符串值转换成一个整数。为此,我们使用了 tf.strings.to_number() 函数。

下面是以下给定代码的实现

Tensorflow convert string to int in Python

Tensorflow convert string to int in Python

这是如何在 Python TensorFlow 中将字符串转换为整数。

阅读: Python TensorFlow 截断法线

TensorFlow 将字符串转换为 int

  • 让我们讨论一下如何在 Python TensorFlow 中将造型字符串转换成整数。
  • 为了执行这项任务,我们将使用 tf.cast() 函数。该函数用于将给定的输入张量转换为新的数据类型。该函数采用两个主要参数,即正在转换的输入张量。

语法:

下面是 Python TensorFlow 中 tf.cast() 函数的语法

tf.cast(
    x, dtype, name=None
)
  • 它由几个参数组成
    • x :该参数定义输入张量和数值型张量、稀疏张量或索引切片。它可能是一个 int8、int16、int32、int64、float16、float32、float64、complex64、complex128 或 bfloat16 。它也可能是一个 uint8、int8、int16、int32 或 int64
    • dtype :该参数指定输入张量的数据类型。
    • name :默认情况下,取 none 值,指定操作的名称。

举例:

import tensorflow as tf

input_tens = tf.constant(['18', '22'])
result=tf.cast(input_tens, tf.float32)
print(result)

你可以参考下面的截图

TensorFlow cast string to int

TensorFlow cast string to int

在本例中,我们已经将字符串值插入到张量中,并通过使用 tf.cast() 函数将其转换为整数,但是不支持将字符串转换为浮点型。

阅读: Python TensorFlow one_hot

Tensorflow 将字符串转换为浮点数

  • 在本节中,我们将讨论如何在 Python TensorFlow 中将字符串转换为浮点数。
  • 为了执行这个特定的任务,我们将使用 tf.strings.to_number() 函数,在这个函数中,我们将把字符串转换成一个整数,并给出一个数字类型。

举例:

import tensorflow as tf

whitest_state_in_USA= tf.constant(['78','92','189','45'])

result= tf.strings.to_number(whitest_state_in_USA,tf.float32)
print(result)

下面是以下给定代码的实现

Tensorflow converts a string to float in Python

Tensorflow converts a string to float in Python

正如你在截图中看到的,我们已经将字符串转换为浮点型。

阅读:Python tensor flow reduce _ mean

TensorFlow 不支持将未实现的字符串转换为 int 64

  • 这里我们将讨论 Python TensorFlow 中不支持将未实现的字符串转换为 int 64 的错误。
  • 为了执行这个特定的任务,我们将使用 tf.cast() 函数。这个函数用于将给定的输入张量转换为新的数据类型。
  • 该函数采用两个主要参数,即正在转换的输入张量。

举例:

import tensorflow as tf

input_tens = tf.constant(['78', '98','178'])
result=tf.cast(input_tens, tf.int64)
print(result)

下面是以下代码的截图

TensorFlow unimplemented cast string to int 64 is not supported

TensorFlow unimplemented cast string to int 64 is not supported

阅读: TensorFlow Tensor to numpy

不支持将 TensorFlow 字符串转换为 int 32

  • 在这个例子中,我们将讨论如何解决 TensorFlow 不支持将字符串转换为 int 32 的错误。
  • 通过使用 tf.cast() 函数,我们可以很容易地生成错误,这背后的原因是这个函数不支持字符串值。

举例:

import tensorflow as tf

input_tens = tf.constant(['167', '875','431'])
new_output=tf.cast(input_tens, tf.int32)
print(new_output)

你可以参考下面的截图

TensorFlow cast string to int32 is not supported

TensorFlow cast string to int32 is not supported

你可能也喜欢阅读下面的 Python 中的 TensorFlow 教程。

在本文中,我们已经讨论了如何在 Python TensorFlow 中将字符串转换为整数。我们还会看一些例子,看看如何在 TensorFlow 中将字符串转换成不同的数据类型。我们已经讨论了这些主题。

  • Tensorflow 将字符串转换为整型
  • TensorFlow 将字符串转换为 int
  • Tensorflow 将字符串转换为浮点型
  • 不支持将 TensorFlow 未实现的字符串转换为 int 64
  • 不支持将 TensorFlow 字符串转换为 int32

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流交叉熵损失

原文:https://pythonguides.com/tensorflow-cross-entropy-loss/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习如何在 Python TensorFlow 中计算交叉熵损失。此外,我们将涵盖以下主题。

  • logits 张量流交叉熵损失
  • 张量流交叉熵损失
  • 张量流交叉熵损失公式
  • 不带 softmax 的张量流交叉熵损失
  • 带掩模的张量流交叉熵损失
  • 张量流二元交叉熵损失
  • 张量流 Keras 交叉熵损失
  • 张量流加权交叉熵损失
  • 稀疏交叉熵损失张量流

目录

张量流交叉熵损失

  • 在本节中,我们将讨论如何在预测和标签之间产生交叉熵损失。
  • 为了执行这个特定的任务,我们将使用 tf。keras . loss . categoricalcrossentropy()函数,该方法将帮助用户获得预测值和标签值之间的交叉熵损失。

语法:

让我们看看语法,了解一下 tf 的工作原理。 Python TensorFlow 中的 keras . loss . categoricalcrossentropy()函数。

tf.keras.losses.CategoricalCrossentropy(
    from_logits=False,
    label_smoothing=0.0,
    axis=-1,
    reduction=losses_utils.ReductionV2.AUTO,
    name='categorical_crossentropy'
)
  • 它由几个参数组成。
    • from_logits: 该参数表示 logit 值,它包含概率值为[0,1]。
    • label_smoothing: 默认情况下,取 0.0 值,当大于 0 时,它将检查条件,并计算真实值之间的损失。
    • 轴:默认取-1 值和生成交叉熵所沿的轴。
    • name: 默认情况下,它采用‘分类 _ 交叉熵’值,并定义操作的名称。

举例:

让我们举个例子,检查如何生成预测和标签之间的交叉熵损失。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_true = [[1.,0.],
         [1.,1.]]
new_predict = [[0.9,1.0],
         [0.3,1.0]]

new_binar_cross = tf.keras.losses.CategoricalCrossentropy()

result=new_binar_cross(new_true,new_predict)
with tf.compat.v1.Session() as val:
  new_output=val.run(result)
print(new_output)

在上面的代码中,我们使用了TF . keras . loss . categoricalcrossentropy()函数,然后将实际值和预测值赋给它。

下面是下面给出的代码的截图。

TensorFlow cross entropy loss

TensorFlow cross-entropy loss

阅读:张量流乘法

带逻辑的张量流交叉熵损失

  • 在本节中,我们将借助 Python TensorFlow 中的交叉熵来计算 logits 值。
  • 为了执行这个特定的任务,我们将使用TF . nn . softmax _ cross _ entropy _ with _ logits()函数,这个方法计算标签和逻辑之间的 soft max 交叉熵。
  • 在这种方法中,标签和逻辑具有相同的数据类型,轴参数定义类维度。

语法:

下面是 Python TensorFlow 中TF . nn . soft max _ cross _ entropy _ with _ logits()的语法。

tf.nn.softmax_cross_entropy_with_logits(
    labels, logits, axis=-1, name=None
)
  • 它由几个参数组成
    • 标签:该参数表示类别维度,是一个有效的概率分布。
    • 对数:这些是典型的线性输出和非标准化对数概率。
    • 轴:默认情况下,取-1 值,指定最后一个维度。
    • name: 默认取 none 值,定义操作的名称。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中借助交叉熵计算 logits 值。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

new_logit_val = [[7.0, 8.0, 2.0], [1.0, 6.0, 8.0]]
new_label_val = [[3.0, 2.0, 1.0], [0.0, 1.0, 0.7]]
result=tf.nn.softmax_cross_entropy_with_logits(new_label_val,new_logit_val)
with tf.compat.v1.Session() as val:
  new_output=val.run(result)
print(new_output)

在以下代码中,我们导入了 TensorFlow 库,然后创建了 logit 和 label 值。之后,我们使用了TF . nn . soft max _ cross _ entropy _ with _ logits()函数,在这个函数中,我们分配了标签和逻辑。

下面是以下给定代码的实现。

TensorFlow cross entropy loss with logits

TensorFlow cross-entropy loss with logits

阅读:张量流均方误差

张量流交叉熵损失 nan

  • 在本节中,我们将讨论如何使用 Python TensorFlow 来检测交叉熵损失中的 nan。
  • 为了执行这个特定的任务,我们将使用实际张量中的 nan 值,然后我们将使用TF . keras . losses . categoricalcrossentropy()函数。

举例:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
new_true = [[1.0,np.nan],
         [np.nan,1.]]
new_predict = [[0.9,1.0],
         [0.3,1.0]]

new_binar_cross = tf.keras.losses.CategoricalCrossentropy()

result=new_binar_cross(new_true,new_predict)
with tf.compat.v1.Session() as val:
  new_output=val.run(result)
print(new_output)

下面是以下给定代码的执行。

TensorFlow cross entropy loss nan

TensorFlow cross-entropy loss nan

正如您在屏幕截图中看到的,输出显示了 nan 值。

阅读: Python TensorFlow 占位符

张量流交叉熵损失公式

  • 在 TensorFlow 中,损失函数用于在训练期间优化输入模型,并且该函数的主要目的是最小化损失函数。
  • 交叉熵损失是优化模型的成本函数,它还获取输出概率并计算与二进制值的距离。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中使用交叉熵。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_true = [[1.,0.],
         [1.,1.]]
new_predict = [[0.9,1.0],
         [0.3,1.0]]

new_binar_cross = tf.keras.losses.CategoricalCrossentropy()

result=new_binar_cross(new_true,new_predict)
with tf.compat.v1.Session() as val:
  new_output=val.run(result)
print(new_output)

通过使用 tf。keras . loss . categoricalcrossentropy()函数,在这个函数中,我们为它设置了 new_true 和 new_predict 值。

下面是下面给出的代码的截图。

TensorFlow cross entropy loss formula

TensorFlow cross-entropy loss formula

阅读: Tensorflow 迭代张量

无 softmax 的张量流交叉熵损失

  • 在本节中,我们将讨论如何在 Python TensorFlow 中不使用 softmax 的情况下使用损失交叉熵。
  • 为了执行这个特定的任务,我们将使用 tf。keras . loss . categoricalcrossentropy()函数,该方法将帮助用户获得预测值和标签值之间的交叉熵损失。

语法:

让我们看看语法,了解一下 tf 的工作原理。Python TensorFlow 中的 keras . loss . categoricalcrossentropy()函数。

tf.keras.losses.CategoricalCrossentropy(
    from_logits=False,
    label_smoothing=0.0,
    axis=-1,
    reduction=losses_utils.ReductionV2.AUTO,
    name='categorical_crossentropy'
)

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中不用 softmax 使用损失交叉熵。

源代码:

import tensorflow as tf

y_true = [1, 0, 1, 1]
y_pred = [-15.6, 2.27, 8.94, -13.8]
new_result = tf.keras.losses.BinaryCrossentropy(from_logits=True)
new_result(y_true, y_pred).numpy()

在上面的代码中,我们已经导入了 TensorFlow 库,然后使用了 tf。keras . loss . binary cross entropy()函数,在这个函数中,我们设置了 logits=True

之后,我们分配了 y_pred,y_true() 值,一旦您执行了这段代码,输出将显示随机值。

下面是下面给出的代码的截图。

TensorFlow cross entropy loss without softmax

TensorFlow cross-entropy loss without softmax

阅读: Python TensorFlow 截断法线

带掩模的张量流交叉熵损失

  • 本节我们将讨论如何在 Python TensorFlow 中用 mask 求交叉熵。
  • 为了执行这个特定的任务,我们将使用 tf.equal() 来返回给定张量值的布尔值张量,并使用 tf.compat.v1.to_float() 来转换掩码值。
  • 通过使用TF . compat . v1 . losses . soft max _ cross _ entropy(),这用于创建交叉熵损失。

语法:

下面是 Python TensorFlow 中TF . compat . v1 . loss . soft max _ cross _ entropy()函数的语法。

tf.compat.v1.losses.softmax_cross_entropy(
    onehot_labels,
    logits,
    weights=1.0,
    label_smoothing=0,
    scope=None,
    loss_collection=ops.GraphKeys.LOSSES,
    reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
  • 它由几个参数组成。
    • 独热标签:该参数表示独热编码标签。
    • 逻辑值:该参数指定逻辑值。
    • weights: 默认情况下,它取 1.0 值,该值被传输到 loss,它是一个可选的张量。
    • label_smoothing:默认情况下,它取 0 值,它将检查条件,如果大于 0 值,它将平滑标签。
    • scope: 它指定操作的范围,并执行损失计算。
    • loss_collection: 该参数表示将要添加损失的集合。

举例:

我们举个例子,查一下如何在 Python TensorFlow 中用 mask 求交叉熵。

源代码:

import tensorflow as tf

new_logit_val = [[0.0,1.0], [1.0,0.0]]
new_label_val = [[3.0, 2.0], [0.0, 1.0]]

mask = tf.equal(new_logit_val, 0)
weights = tf.compat.v1.to_float(mask) 
loss = tf.compat.v1.losses.softmax_cross_entropy(new_label_val, new_logit_val, weights)
print(loss)

在下面给定的代码中,我们使用了 tf.equal()函数,在这个函数中,我们使用 tf.compat.v1.to_float() 来分配 logit 值并将其转换为掩码。

下面是下面给出的代码的截图。

TensorFlowv cross entropy loss with mask

TensorFlow cross-entropy loss with mask

张量流二元交叉熵损失

  • 在本节中,我们将讨论如何在 Python TensorFlow 中计算二元交叉熵损失。这点可以参考我们的详细文章二元交叉熵张量流
  • 你会得到关于二元交叉熵损失的所有信息。

张量流 Keras 交叉熵损失

  • 在本节中,我们将讨论如何在 Keras 中测量交叉熵损失。
  • 为了执行这个特定的任务,我们将使用 tf。keras . losses . categoricalcrossentropy()函数,该方法将帮助用户获得预测值和标签值之间的交叉熵损失。

语法:

下面是 tf 的语法。Python TensorFlow 中的 keras . loss . categoricalcrossentropy()。

tf.keras.losses.CategoricalCrossentropy(
    from_logits=False,
    label_smoothing=0.0,
    axis=-1,
    reduction=losses_utils.ReductionV2.AUTO,
    name='categorical_crossentropy'
)

举例:

我们举个例子,检查一下如何测量 Keras 中的交叉熵损失。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

new_true_val = [[1.,1.],
         [0.,1.]]
new_predict_val = [[1.0,0.0],
         [1.0,0.0]]

new_binar_cross = tf.keras.losses.CategoricalCrossentropy()

result=new_binar_cross(new_true_val,new_predict_val)
with tf.compat.v1.Session() as val:
  new_output=val.run(result)
print(new_output)

下面是以下给定代码的实现

TensorFlow Keras cross entropy loss

TensorFlow Keras cross-entropy loss

阅读:Python tensor flow expand _ dims

张量流加权交叉熵损失

  • 在本节中,我们将通过 Python TensorFlow 讨论如何在交叉熵损失中使用权重。
  • 为了执行这个特定的任务,我们将使用 TF . nn . weighted _ cross _ entropy _ with _ logits()函数,这个函数将帮助用户找到加权交叉熵。

举例:

我们举个例子,通过使用 Python TensorFlow 来检查如何使用交叉熵损失中的权重。

源代码:

import tensorflow as tf

new_label = tf.constant([0.1, 1., 1.])
new_logit = tf.constant([1., -0, -9.])
result=tf.nn.weighted_cross_entropy_with_logits(
    labels=new_label, logits=new_logit, pos_weight=tf.constant(1.5))
print(result)

下面是以下给定代码的实现。

TensorFlow weighted cross entropy loss

TensorFlow weighted cross-entropy loss

阅读:Python tensor flow reduce _ mean

稀疏交叉熵损失张量流

  • 在本节目中,我们将讨论如何在 Python TensorFlow 中稀疏交叉熵损失。
  • 为了执行此特定任务,我们将使用 TF . keras . loss . sparsecategoricalcrossentropy()函数,此方法用于查找预测和标签之间的交叉熵损失。

语法:

我们先来看看语法,了解一下TF . keras . loss . sparsecategoricalcrossentropy()函数在 Python TensorFlow 中的工作原理。

tf.keras.losses.SparseCategoricalCrossentropy(
    from_logits=False,
    reduction=losses_utils.ReductionV2.AUTO,
    name='sparse_categorical_crossentropy'
)
  • 它由几个参数组成。
    • from_logits: 该参数表示 y_prediction 对概率分布进行编码,默认情况下,它采用一个假值。
    • 名称:默认情况下,它采用' sparse _ categorical _ crossentropy '并指定操作的名称。

举例:

让我们举个例子,看看如何在 Python TensorFlow 中稀疏交叉熵损失。

源代码:

import tensorflow as tf 

new_true = [2, 1]
new_prediction = [[0.1, 1.2, 1.2], [1.0, 2.1, 0.95]]
new_result = tf.keras.losses.SparseCategoricalCrossentropy()
new_result(new_true, new_prediction)

下面是以下给定代码的实现

sparse cross entropy loss TensorFlow

sparse cross-entropy loss TensorFlow

还有,多看看一些 TensorFlow 教程。

在这个 Python 教程中,我们学习了如何在 Python TensorFlow 中计算交叉熵损失。此外,我们还讨论了以下主题。

  • logits 张量流交叉熵损失
  • 张量流交叉熵损失
  • 张量流交叉熵损失公式
  • 不带 softmax 的张量流交叉熵损失
  • 带掩模的张量流交叉熵损失
  • 张量流二元交叉熵损失
  • 张量流 Keras 交叉熵损失
  • 张量流加权交叉熵损失
  • 稀疏交叉熵损失张量流

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流自定义损失函数

原文:https://pythonguides.com/tensorflow-custom-loss-function/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何使用 Python TensorFlow 中的自定义损失函数。此外,我们将涵盖以下主题。

  • 张量流自定义损失函数
  • Tensorflow custom loss function Keras
  • 张量流自定义损失函数多路输出
  • 张量流自定义损失函数梯度
  • 张量流自定义损失函数 numpy
  • 具有自定义损失函数的张量流负荷模型

目录

张量流自定义损失函数

  • 这里我们将使用 Python TensorFlow 中的自定义损失函数。
  • 损失函数是机器学习模型的主要部分。如果你在数据科学领域工作过,你一定听说过它。
  • 损失函数,也称为成本函数是一种特殊类型的函数,它帮助我们最小化误差,并获得期望输出的可能性。
  • 均方误差,该损失是用于回归问题的默认损失。通过在编译模型时声明' mse 或' mean_squared_error '作为损失函数,可以在 Keras 中使用均方误差损失函数。

语法:

下面是 tf 的语法。Keras . Sequential()tensor flow Keras 中的函数。

tf.keras.Sequential
                   (
                    layers=None,
                    name=None
                   )
  • 它由几个参数组成
    • 图层:该参数表示插入模型的图层列表。
    • name: 可选参数,指定操作的名称。

举例:

import keras
import numpy as np

new_true_val = np.array([[28.0,16.0]]) 
new_pred_val = np.array([[13.0, 28.0]])

new_tens = keras.losses.MSE(new_true_val, new_pred_val)

print(f'Mean squared value {new_tens.numpy()}')
model = keras.Sequential([
                     keras.layers.Dense(20, input_shape=(1,), activation='relu'),
                     keras.layers.Dense(1)

])
model.compile(loss='mse', optimizer='adam')
model.fit(np.array([[15.0],[25.0], [55.0],[65.0],[75.0],[85.0],[95.0], [85.0]]), np.array([3, 18, 12,42,36, 72,18, 16]), epochs=10)

在下面给出的代码中,我们首先导入了 Keras 和 NumPy 库。之后,我们使用*keras . losses . MSE()*函数,并分配真实值和预测值。

接下来,我们使用 Keras 创建了一个模型。Sequential()函数,在这个函数中,我们将输入形状和激活值设置为参数。创建模型后,我们编译并拟合了模型。

下面是以下代码的截图

Custom loss function in Tensorflow

Custom loss function in Tensorflow

阅读:tensor flow next _ batch+Examples

Tensorflow custom loss function Keras

  • 在本节中,我们将讨论如何在 Tensorflow Keras 中使用自定义损失函数。
  • 损失函数的主要目的是生成一个模型在训练期间应该寻求最小化的数量。损失函数是执行 Keras 模型所需的两个参数之一。
  • 损失函数由损失类声明(例如,keras . loss . sparsecategoricalcrossentropy)。所有损失也作为函数句柄给出(例如,keras . loss . sparse _ categorial _ cross entropy)。
  • 在 Keras 中,损失函数在编译阶段传递。在这个例子中,我们通过创建 loss 类的一个实例来定义 loss 函数。使用该类很简单,因为您可以传递一些附加参数。

举例:

我们举个例子,检查一下如何使用 TensorFlow Keras 中的自定义损失函数。

源代码:

import tensorflow as tf

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from tensorflow.keras.utils import plot_model
from tensorflow.keras import backend as K

new_arr1= np.array([-2.0, 1.0, 1.0, 1.0, 6.0, 3.0], dtype=np.float64)

new_arr2 = np.array([-6.0, -3.0, 2.0, 1.0, 0.0, 4.0], dtype=np.float64)
plt.scatter(new_arr1, new_arr2);

model = tf.keras.Sequential([
    tf.keras.layers.Dense(1, input_shape=[1])
])

model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(new_arr1, new_arr2, epochs=500, verbose=0)

new_mean_squ_val = model.predict([20])
new_mean_squ_val

plt.scatter(new_arr1, new_arr2)
plt.scatter(20, new_mean_squ_val, c='r');

def my_huber_loss(new_true_val, new_pred_val):
    new_thres_val = 1.
    error = new_true_val - new_pred_val
    smal_err = tf.abs(error) <= new_thres_val
    new_err_loss = tf.square(error) / 2
    max_err_loss = new_thres_val * (tf.abs(error) - new_thres_val / 2)
    return tf.where(smal_err, new_err_loss, max_err_loss)

model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1,])
])

model.compile(optimizer='sgd', loss=my_huber_loss)
model.fit(new_arr1, new_arr2, epochs=500, verbose=0)

new_predict_val = model.predict([20.0])
new_predict_val

plt.scatter(new_arr1, new_arr2);
plt.scatter(20.0, new_mean_squ_val, label='mse');
plt.scatter(20.0, new_predict_val, label='huber_loss');
plt.grid()
plt.legend();

下面是给定代码的实现。

custom loss function Tensorflow keras

custom loss function Tensorflow keras

阅读: TensorFlow 稀疏张量

带自定义损失函数的张量流负荷模型

  • 在这个例子中,我们将学习如何在 Python TensorFlow 中加载带有自定义损失函数的模型。
  • 为了执行这个特定的任务,我们将使用 mnist.load_data() 数据集,并将数据集分成训练和测试标签。
  • 接下来,我们将使用 tf。Keras.models.Sequential() 函数,该函数用于向 Keras 模型添加线性层堆栈。

举例:

import os
from tensorflow import keras
import tensorflow as tf
(new_train_imag, new_train_label), (test_images, new_test_label) = tf.keras.datasets.mnist.load_data()

train_labels = new_train_label[:2000]
new_test_label = new_test_label[:2000]

new_train_imag = new_train_imag[:2000].reshape(-2, 14 * 14) / 255.0
test_images = test_images[:2000].reshape(-1, 14 * 14) / 255.0
def declare_new_model():
  new_model = tf.keras.models.Sequential([
    keras.layers.Dense(256, activation='relu', input_shape=(784,)),
    keras.layers.Dropout(0.7),
    keras.layers.Dense(12)
  ])

  new_model.compile(optimizer='adam',
                loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
                metrics=[tf.metrics.SparseCategoricalAccuracy()])

  return new_model

new_model = declare_new_model()

new_model.summary()

在下面给出的代码中,我们使用了 tf。Keras.models.Sequential() 函数,在这个函数中,我们将激活和输入 _ 形状()值设置为参数。之后,我们使用了 model.compile()并使用了TF . losses . sparsecategoricalcrossentropy()

下面是下面给出的代码的截图。

model creation in custom loss function

model creation in the custom loss function

阅读: TensorFlow 全球平均池

Tensorflow 自定义损失函数梯度

  • 在本节中,我们将讨论如何在 Tensorflow 自定义损失函数中使用梯度带。
  • 在这个例子中,我们将使用 tf。GradientTape() 函数,该函数用于使用该模型中的操作来生成梯度。

语法:

让我们看一下语法并理解 Python TensorFlow 中的 tf.gradients() 函数的工作原理

tf.gradients
   (
    ys,
    xs,
    grad_ys=None,
    name='gradients',
    gate_gradients=False,
    aggregation_method=None,
    stop_gradients=None,
   )
  • 它由几个参数组成
    • ys: 该参数表示要微分的输入张量列表。
    • grad_ys: 可选参数,指定与 ys 大小相同的张量列表,在 ys 中计算每个 y。
    • name: 默认情况下,取渐变的值,指定操作的名称。
    • gate_gradients: 如果为真,那么它将添加一个元组,并且还将避免一些条件。默认情况下,它采用一个假值。
    • aggregation_method: 该函数用于合并渐变值。

举例:

import tensorflow as tf

def new_custom_loss(model, new_tensor):
    def cust_loss(new_true_val,new_pred_val):
        with tf.GradientTape() as t:
            t.watch(new_tensor)
            new_output = model(new_tensor)
        DyDX = t.gradient(new_output, new_tensor)
        new_val = DyDX[:, 5:6]
        new_r_prediction=new_val

        new_loss_pde = tf.reduce_mean(tf.square(new_r_prediction))
        return new_loss_pde
    return cust_loss
print(new_custom_loss)

在上面的代码中,我们定义了 cust_loss 函数,并分配了真实值和预测值。之后,我们创建了一个与 tf 的会话。GradientTape() 函数,并为其设置张量值。

下面是以下给定代码的实现。

Tensorflow custom loss function gradient

Tensorflow custom loss function gradient

阅读:二元交叉熵张量流

Tensorflow 自定义损失函数 numpy

  • 在本例中,我们将在自定义损失函数中使用 numpy 数组。
  • 为了完成这项任务,首先我们将创建一个包含样本数据的数组,并使用 numpy() 函数来查找均方值。
  • 接下来,我们将使用 tf.keras.Sequential() 函数,并为输入形状分配密集值。

语法:

下面是 Python TensorFlow 中 tf.keras.Sequential() 函数的语法

tf.keras.Sequential
                   (
                    layers=None,
                    name=None
                   )

举例:

import keras
import numpy as np

new_true = np.array([[76.0,65.0]]) #sample data
new_prediction = np.array([[23.0, 56.0]])

new_arr = keras.losses.MSE(new_true, new_prediction)

print(f'Mean squared error {new_arr.numpy()}')
new_model = keras.Sequential([keras.layers.Dense(20, input_shape=(1,), activation='relu'),keras.layers.Dense(1)

])
new_model.compile(loss='mse', optimizer='adam')
new_model.fit(np.array([[80.0],[40.0], [60.0],[90.0],[40.0],[10.0],[70.0], [50.0]]), np.array([4, 8, 12,16,20, 24,28, 30]), epochs=10)

下面是以下给定代码的执行过程

Tensorflow custom loss function numpy

Tensorflow custom loss function numpy

还有,多看看一些 TensorFlow 教程。

在本 Python 教程中,我们学习了如何使用 Python TensorFlow 中的自定义损失函数。此外,我们还讨论了以下主题。

  • Custom loss function TensorFlow Keras
  • 张量流自定义损失函数多路输出
  • 张量流自定义损失函数梯度
  • 张量流自定义损失函数 numpy
  • 具有自定义损失函数的张量流负荷模型

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流嵌入 _ 查找

原文:https://pythonguides.com/tensorflow-embedding_lookup/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何在 Python TensorFlow 中使用 tf.nn.embedding_lookup()函数。此外,我们将涵盖以下主题。

  • 张量流嵌入 _ 查找
  • Tensorflow 嵌入 _ 查找 _ 稀疏
  • Tensorflow 嵌入 _ 查找 _ 唯一
  • 张量流嵌入 _ 查找掩码
  • 张量流嵌入 _ 查找补零
  • 张量流嵌入 _ 查找集合
  • 张量流嵌入 _ 查找梯度

目录

TensorFlow 嵌入 _ 查找

  • 在本节中,我们将讨论如何在 Python TensorFlow 中嵌入张量列表。
  • 为了执行这个特定的任务,我们将使用 tf.nn.embedding_lookup() 函数,这个函数用于在张量列表上生成查找。
  • 简而言之,该函数定义了根据索引号恢复第一个参数的行的操作。

语法:

下面是 Python TensorFlow 中 tf.nn.embedding_lookup() 函数的语法。

tf.nn.embedding_lookup
                      (
                       params,
                       ids,
                       max_norm=None,
                       name=None
                      )
  • 它由几个参数组成
    • params: 该参数表示分片嵌入张量。
    • 默认情况下,它采用 int32 和 int64 位类型,并在 params 中查找。
    • max_norm:默认情况下,它没有值,并且大于它的值。
    • name:默认情况下,它采用 none 值并定义操作的名称。

举例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
tens = [
    [0.2783, 0.8762, -0.2789],
    [0.1923, 0.8823, -0.1892],
    [0.8567, -0.99234, 0.8123],
    [0.156, 0.8567, 0.9562]
]
result = tf.constant(tens, dtype=tf.float32)

with tf.compat.v1.Session() as val:
  new_index_val = [0, 2]
  new_output = tf.nn.embedding_lookup(result, new_index_val)

  print(val.run(new_output))

在下面的代码中,我们导入了 TensorFlow 库,然后通过导入TF . compat . v1 . disable _ eager _ execution()函数创建了一个会话。

之后,我们声明了一个变量并分配了索引值,并使用了 tf.nn.embedding_lookup() 函数。

下面是以下给定代码的实现。

TensorFlow embedding_lookup

TensorFlow embedding_lookup

阅读:张量流获取变量

Tensorflow 嵌入 _ 查找 _ 稀疏

  • 在本节中,我们将讨论如何在 Python TensorFlow 中查找权重和 id 的嵌入。
  • 为了执行这个特定的任务,我们将使用TF . nn . embedding _ lookup _ sparse()函数,这个函数将帮助用户嵌入来自输入张量列表的给定权重和 id。

语法:

我们先来看看语法,了解一下TF . nn . embedding _ lookup _ space在 Python TensorFlow 中的工作原理。

tf.nn.embedding_lookup_sparse
                             (
                              params,
                              sp_ids,
                              sp_weights,
                              combiner=None,
                              max_norm=None,
                              name=None
                             )
  • 它由几个参数组成
    • params: 该参数表示输入张量和相同形状的列表。
    • sp_ids: 该参数指定了 int64 ids 的稀疏张量。
    • sp_weights: 在这个参数中,我们要指定所有的权重,它必须取为 1。
    • combiner: 默认情况下,它接受 None 值,并为每行生成嵌入结果的加权和。
    • max_norm: 默认取 None 值,大于合并前的值。
    • 名称:默认为可选参数,指定操作的名称。

举例:

 import tensorflow as tf
import numpy as np
tf.compat.v1.disable_eager_execution()
tensor = tf.SparseTensor(indices=[[2], [3], [4]], values=[3, 6, 9], dense_shape=[4])

val_num = 10
val_size = 1
arr = np.array([15.0, 2.0, 5.0, 3.0, 2.0, 11.0, 7.0, 10.0, 15.0, 14.0])
result = tf.Variable(arr)

new_output = tf.nn.embedding_lookup_sparse(result, tensor, None)

with tf.compat.v1.Session() as sess:
    sess.run(tf.compat.v1.initialize_all_variables())
    print(sess.run(new_output))

在上面的代码中,我们使用了 tf。SparseTensor() 函数,并将索引值和密集形状作为参数赋值。之后,我们声明了变量,其中我们提到了给定输入张量的大小。

下面是以下给定代码的实现。

Tensorflow embedding_lookup_sparse

Tensorflow embedding_lookup_sparse

阅读: Python TensorFlow 占位符

Tensorflow 嵌入 _ 查找 _ 唯一

  • 在本节中,我们将讨论如何从 Python TensorFlow 中的嵌入式查找中获取唯一值。
  • 为了执行这个特定的任务,我们将使用TF . contrib . layers . embedding _ lookup _ unique(),这个函数只在 Tensorflow 1.15.0 版本中有效,并且这个函数避免了重复查找。

语法:

让我们看一下语法,了解一下TF . contrib . layers . embedding _ lookup _ unique()的工作原理

tf.contrib.layers.embedding_lookup_unique(
    params,
    ids,
    name=None
)

举例:

让我们举一个例子,看看如何从 Python TensorFlow 中的嵌入式查找中获得唯一值。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
tens = [
    [0.256, 0.134, -0.765],
    [0.843, 0.778, -0.281],
    [0.954, -0.1561, 0.1789],
    [0.167, 0.290, 0.178]
]
result = tf.constant(tens, dtype=tf.float32)

with tf.compat.v1.Session() as val:
  new_index_val = [0, 2]
  new_output = tf.contrib.layers.embedding_lookup_unique(result, new_index_val)

  print(val.run(new_output))

下面是以下给定代码的输出。

Tensorflow embedding_lookup_unique

Tensorflow embedding_lookup_unique

阅读: Tensorflow 迭代张量

Tensorflow 嵌入 _ 查找掩码

  • 在本节中,我们将讨论如何在 Python TensorFlow 中使用 embedding_lookup 来获取掩码值。
  • 为了执行这个特定的任务,我们将定义 CustomEmbedding() 函数,然后为输入张量创建输入和输出维度。
  • 接下来,我们将设置条件 self inputs,如果不是,那么self . mask _ zero()return None 如果不是,那么它将返回 0

举例:

让我们举个例子,检查一下如何通过 Python TensorFlow 中的嵌入式查找获得掩码值。

源代码:

import tensorflow as tf
import numpy as np
class CustomEmbedding(keras.layers.Layer):
    def __init__(self, new_inp_dim, new_out_dim, mask_zero=False, **kwargs):
        super(CustomEmbedding, self).__init__(**kwargs)
        self.input_dim = new_inp_dim
        self.output_dim = new_out_dim
        self.mask_zero = mask_zero

    def build(self, input_shape):
        self.embeddings = self.add_weight(
            shape=(self.input_dim, self.output_dim),
            initializer="random_normal",
            dtype="float32",
        )

    def call(self, inputs):
        return tf.nn.embedding_lookup(self.embeddings, inputs)

    def compute_mask(self, inputs, mask=None):
        if not self.mask_zero:
            return None
        return tf.not_equal(inputs, 0)

layer = CustomEmbedding(12, 36, mask_zero=True)
new_tens = np.random.random((2, 12)) * 9
new_tens = new_tens.astype("int32")

y = layer(new_tens)
mask = layer.compute_mask(new_tens)

print(mask)

在下面给出的代码中,我们通过使用 np.random.random() 函数创建了一个随机值,然后将数据类型指定为 int32 。一旦执行了这段代码,输出将显示布尔掩码值。

下面是下面给出的代码的截图。

Tensorflow embedding_lookup mask

Tensorflow embedding_lookup mask

阅读:将列表转换为张量张量流

Tensorflow 嵌入 _ 查找补零

  • 在这个程序中,我们将讨论如何在 embedding _ lookup Python tensor flow 中填充零值。
  • 为了完成这项任务,我们将使用TF . keras . preprocessing . sequence . pad _ sequences()函数,该函数用于获得给定张量的相同长度。

语法:

我们先来看看语法,了解一下 Python Tensorflow 中 TF . keras . preprocessing . sequence . pad _ sequences()函数的工作原理。

tf.keras.preprocessing.sequence.pad_sequences(
    sequences,
    maxlen=None,
    dtype='int32',
    padding='pre',
    truncating='pre',
    value=0.0
)
  • 它由几个参数组成
    • 序列:该参数表示序列列表。
    • maxlen: 默认情况下,它采用 none 值,并指定所有序列的最大长度。它将检查条件,如果没有提供序列,那么这个参数将用相同的长度填充。
    • dtype: 默认取 int32 值,可选参数,类型为输出序列。
    • 填充:默认情况下,它是一个前值,指定每个序列的前后。
    • 截断:这是一个可选参数,它从大于最大长度的序列中删除值。
    • 值:默认为 0,指定填充值。

举例:

让我们举个例子,检查如何在 embedding _ lookup Python tensor flow 中填充零值。

源代码:

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

new_tens = [
    [26, 12, 90],
    [167, 211, 976, 245, 912],
    [197, 278, 23, 67, 856, 179],
]

new_outputs = tf.keras.preprocessing.sequence.pad_sequences(
    new_tens, padding="post"
)
print(new_outputs)

在下面的代码中,我们导入了 numpy 和 TensorFlow 库,然后创建了一个张量。之后,我们使用了TF . keras . preprocessing . sequence . pad _ sequences()函数,在这个函数中,我们将填充和张量指定为一个参数。

下面是下面给出的代码的截图。

Tensorflow embedding_lookup zero padding

Tensorflow embedding_lookup zero padding

阅读:Python tensor flow expand _ dims

张量流嵌入 _ 查找道集

  • 在本节中,我们将讨论如何在 Python TensorFlow 中收集 embedding_lookup。
  • 为了执行这个特定的任务,我们将使用 tf.nn.embedding_lookup() 函数,这个函数用于在张量列表上生成查找。

语法:

tf.nn.embedding_lookup
                      (
                       params,
                       ids,
                       max_norm=None,
                       name=None
                      )

举例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
input_tens = [
    [1, 4, -7],
    [5, 2, -8],
    [6, -8, 1],
    [9, 2, 0]
]
result = tf.constant(input_tens, dtype=tf.int32)

with tf.compat.v1.Session() as val:
  new_index_val = [2, 3]
  new_output = tf.nn.embedding_lookup(result, new_index_val)

  print(val.run(new_output))

在下面的代码中,我们导入了 TensorFlow 库,然后通过导入TF . compat . v1 . disable _ eager _ execution()函数创建了一个会话。

之后,我们声明了一个变量并分配了索引值,并使用了 tf.nn.embedding_lookup() 函数。

下面是以下给定代码的实现。

Tensorflow embedding_lookup gather

Tensorflow embedding_lookup gather

阅读: Python TensorFlow one_hot

张量流嵌入 _ 查找梯度

  • 在本节中,我们将讨论 Python TensorFlow 中 embedding_lookup 中的梯度。
  • 为了完成这个任务,我们将使用 tf。GradientTape() 功能,该功能用于记录自动微分的操作。

语法:

让我们看看语法,了解一下 tf 的工作原理。Python TensorFlow 中的 GradientTape() 函数。

tf.GradientTape(
    persistent=False, watch_accessed_variables=True
)
  • 它由几个参数组成。
    • persistent: 默认情况下,它取一个假值,它指定声明了持久梯度带。
    • watch _ accessed _ variables:该参数表示梯度的真实含义,可以用读取训练变量得到的任何结果来表示。

举例:

我们举个例子,检查一下Python tensor flow 中 embedding_lookup 中的梯度是如何的。

源代码:

import tensorflow as tf

tens = tf.constant(7.0)
with tf.GradientTape() as m:
  m.watch(tens)
  with tf.GradientTape() as mm:
    mm.watch(tens)
    y = tens * tens
  new_result = mm.gradient(y, tens) 
new_result2 = m.gradient(new_result, tens)  
print(new_result2)

在下面给出的代码中,我们通过使用 tf.constant() 函数创建了张量,然后我们定义了内置函数 tf。GradientTape()

下面是下面给出的代码的截图。

Tensorflow embedding_lookup gradient

Tensorflow embedding_lookup gradient

你可能也喜欢阅读下面的 TensorFlow 教程。

在本 Python 教程中, 我们学习了如何在 Python TensorFlow 中使用 tf.nn.embedding_lookup()函数。此外,我们还讨论了以下主题。

  • 张量流嵌入 _ 查找
  • Tensorflow 嵌入 _ 查找 _ 稀疏
  • Tensorflow 嵌入 _ 查找 _ 唯一
  • 张量流嵌入 _ 查找掩码
  • 张量流嵌入 _ 查找补零
  • 张量流嵌入 _ 查找集合
  • 张量流嵌入 _ 查找梯度

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Python 张量流 expand_dims

原文:https://pythonguides.com/tensorflow-expand_dims/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何通过使用 TensorFlow 函数来扩展张量中的维度。此外,我们将讨论以下主题。

  • TensorFlow expand_dims 多次
  • 张量流 expand_dims reverse
  • 张量流 expand_dims 图层
  • 张量流 expand_dims pytorch
  • 张量流稀疏扩展 _dims
  • TensorFlow keras expand_dims

目录

Python tensor flow expand _ dims

  • 在本节中,我们将讨论如何在 TensorFlow Python 中扩展维度。
  • 为了执行这个特定的任务,我们将使用 tf.expand_dims() 函数,这个方法用于在张量中添加一个新维度,它总是返回一个具有新维度的张量。

语法:

下面是 tf.expand_dims() 函数的语法

tf.expand_dims
              (
               input,
               axis,
               name=None
              )

举例:

让我们举个例子,了解一下 tf.expand_dims() 函数的工作原理。

源代码:

import tensorflow as tf

tensor=tf.constant([[2,3,4],
                   [12,34,56]])
print(tensor)

result=tf.expand_dims(tensor,0)
print("Extend dimension:",result)

下面是下面给出的代码的截图。

Python TensorFlow expand_dims

Python TensorFlow expand_dims

另一种方法是通过使用 tf.new axis() 函数来扩展 TensorFlow Python 中的维度。

在本例中,我们将使用 tf.newaxis() 函数来扩展维度。在 Python TensorFlow 中,此函数用于向给定形状添加新维度。

举例:

import tensorflow as tf

tensor=tf.constant([[2,3,4],
                   [12,34,56]])
print(tensor)
result2 = tensor[:, tf.newaxis]
print("Extend dimension:",result2)

在上面的代码中,我们首先使用 tf.constant() 函数创建了一个输入张量,然后使用 tf.newaxis() 函数和切片方法。

下面是以下给定代码的执行。

TensorFlow expand_dims in Python

TensorFlow expand_dims in Python

阅读: TensorFlow Tensor to numpy

TensorFlow expand_dims 多次

  • 在本节中,我们将讨论如何在 Python TensorFlow 中多次扩展维度。
  • 为了执行这个特定的任务,我们将使用 tf.newaxis() 函数,这个函数将帮助用户使用切片方法在张量中多次扩展维度。
  • 在这个例子中,我们将使用 tf.constant() 函数创建一个三维张量,然后我们将使用 tf.newaxis() 函数中的切片方法。

举例:

import tensorflow as tf

inpu_tens=tf.constant([[[56,89,167],
                   [55,59,126],
                    [345,894,178]]])
print(inpu_tens)
new_result=inpu_tens[:,:,:,tf.newaxis]
print("Extend dimension multiple times:",new_result)

执行这段代码后,输出会多次显示新添加的维度。

下面是以下给定代码的执行。

Python TensorFlow expand_dims multiple times

Python TensorFlow expand_dims multiple times

阅读:张量流得到形状

tensor flow expand _ dims reverse

  • 这里我们要讨论的是如何利用 Tensorflow Python 中的 tf.expand_dims() 函数来扩展维度,逆序得到结果。
  • 为了执行这个特定的任务,我们将使用 tf.reverse() 函数,这个函数用于基于给定的特定轴来反转张量元素。

语法:

下面是 Python TensorFlow 中 tf.reverse() 函数的语法。

tf.reverse
          (
           tensor,
           axis,
           name=None
          )
  • 它由几个参数组成
    • 张量:该参数表示输入的张量。
    • 轴:该参数指定要反转的尺寸的索引。
    • name: 可选参数,指定操作的名称。

举例:

我们举个例子,了解一下 Python TensorFlow 中 tf.expand_dims()tf.reverse() 函数的工作原理。

源代码:

import tensorflow as tf

new_tensor=tf.constant([[56,89,167],
                       [78,92,67]])
print(new_tensor)#Display the tensor

result=tf.expand_dims(new_tensor,0)
print(result) # expand the dimension
dims=[-1]
new_output=tf.reverse(result, dims)
print(new_output)

在上面的代码中,我们通过使用 tf.constant() 函数创建了一个张量,然后我们应用了 tf.expand_dims() 函数来扩展给定形状中的维度。

在扩展维度之后,我们使用了 tf.reverse() 函数,在这个函数中,我们将结果和 dims 作为一个参数进行赋值。在本例中,‘结果’‘dims’变量表示展开的尺寸,倒数默认为 -1

下面是下面给出的代码的截图。

Python TensorFlow expand_dims reverse

Python TensorFlow expand_dims reverse

正如您在截图中看到的,输出显示了给定张量的反向元素。

阅读:导入错误没有名为 TensorFlow 的模块

TensorFlow expand_dims 图层

  • 在本期节目中,我们将讨论如何在 TensorFlow keras 层中扩展维度。
  • 为了完成这个任务,我们将使用TF . keras . layers . shape()函数,这个函数从给定的形状返回整形输入。

语法:

让我们看一下语法并理解 Python 中的TF . keras . layers . shape()函数的工作原理

tf.keras.layers.Reshape
                       (
                        target_shape,
                        **kwargs
                       )
  • 它由几个参数组成
    • 目标形状:该参数将被视为输入形状,且它必须是整数元组。
    • **kwargs: 这是一个附加层关键字参数。

举例:

让我们举个例子,检查如何在 TensorFlow Keras 层中扩展维度。

源代码:

import tensorflow as tf

new_tens = tf.keras.Sequential()
new_tens.add(tf.keras.layers.Reshape((4, 4), input_shape=(16,)))
print(new_tens.output_shape)

在上面的代码中,我们已经导入了 TensorFlow 库,然后使用了 tf。keras . layers . shape()函数,在该函数中,我们将输入形状指定为参数。一旦执行了这段代码,输出就会显示形状。

下面是以下给定代码的实现。

TensorFlow expand_dims layer

TensorFlow expand_dims layer

阅读:Python tensor flow reduce _ sum

tensor flow expand _ dims py torch

  • 在本期节目中,我们将讨论如何在 Python Pytorch 中扩展维度。
  • 为了执行这个特定的任务,我们将使用 tensor.expand() 函数,这个方法用于执行扩展维度,它总是在输出形状中返回一个单独的维度。

语法:

下面是 torch 的语法。张量. expand() 函数

Tensor.expand(*sizes)
  • 它只包含一个参数
    • 尺寸:该参数表示展开后的尺寸。

举例:

让我们来看看这个例子,看看如何在 Python Pytorch 中扩展维度。

源代码:

import tensorflow as tf
import torch

new_tensor = torch.tensor([[6],[16],[144]])
result=new_tensor.expand(3, 6)
print(result) 

在上面的代码中,我们导入了 torch 库,然后使用 torch.tensor() 函数创建了一个张量。创建张量后,我们使用了张量. expand() 函数,在这个函数中,我们传递了我们想要用给定的张量展开的新形状。

下面是以下给定代码的实现

Python TensorFlow expand_dims pytorch

Python TensorFlow expand_dims pytorch

正如您在截图中看到的,输出显示了张量的扩展维度。

阅读:Python tensor flow reduce _ mean

tensor flow sparse expand _ dims

  • 在本节中,我们将讨论如何在 TensorFlow Python 中使用 sparse expand_dims() 函数。
  • 通过使用 tf.sparse.expand_dims() ,我们可以很容易地在张量形状中添加一个长度为 1 的维度。

语法:

下面是 Python TensorFlow 中 tf.sparse.expand_dims() 函数的语法。

tf.sparse.expand_dims
                     (
                      sp_input,
                      axis=None,
                      name=None
                     )
  • 它由几个参数组成
    • sp_input: 该参数指定给定的稀疏张量。
    • 轴:默认取 -1 值,表示我们要对形状输入进行操作的尺寸索引。
    • 名称:该参数表示输出稀疏张量的名称。

举例:

我们举个例子,了解一下 tf.sparse.expand_dims() 函数的工作原理。

源代码:

import tensorflow as tf

new_tensor = tf.sparse.SparseTensor(indices=[[2,1,3]], values=[14,],
                            dense_shape=[4,4,6])
result=tf.sparse.expand_dims(new_tensor, axis=0)
print(result)

在下面给定的代码中,我们导入了 TensorFlow 库,然后通过使用TF . sparse . sparsesensor()函数创建了一个稀疏张量,在这个函数中,我们传递了索引dense_shape 作为参数。创建稀疏张量后,我们使用 tf.sparse.expand_dims() 来扩展维度。

下面是以下给定代码的实现。

Python TensorFlow sparse expand_dims

Python TensorFlow sparse expand_dims

正如你在截图中看到的,输出显示了给定张量的新大小。

阅读:模块“张量流”没有属性“会话”

TensorFlow keras expand_dims

  • 这里我们将讨论如何在张量流 keras 中扩展维度。
  • 为了执行这一特定任务,我们将使用TF . keras . back end . expand _ dims()函数,该方法用于在索引轴添加一维长度的维度。

语法:

让我们看一下语法,了解一下TF . keras . back end . expand _ dims()函数的工作原理。

tf.keras.backend.expand_dims(
    x,
    axis=-1
)
  • 它由几个参数组成
    • x: 该参数表示 inout 张量或输入变量。
    • 轴:默认取-1 值,这指定了我们要添加新轴的位置。

举例:

让我们举个例子,看看如何在 Python TensorFlow Keras 中扩展维度。

源代码:

import tensorflow as tf

tensor= tf.constant([[13,56,27],
                    [14,28,39]])
print(tensor)
new_output=tf.keras.backend.expand_dims(tensor,-1)
print("Expand dimension in keras backend:",new_output)

在上面的代码中,我们导入了 TensorFlow 库,然后通过使用 tf.constant() 函数创建了一个输入张量,在这个函数中,我们指定了一个二维张量。

创建张量后,我们使用了TF . keras . back end . expand _ dims()函数,并将张量和轴=-1 参数指定为参数。一旦执行了这段代码,输出就会通过增加 1 的长度来显示张量的新大小。

下面是下面给出的代码的截图。

Python TensorFlow keras expand_dims

Python TensorFlow Keras expand_dims

你可能也喜欢阅读下面的 TensorFlow 教程。

因此,在这个 Python 教程中,我们已经学习了如何使用 TensorFlow 函数来扩展张量中的维度。此外,我们将讨论以下主题。

  • TensorFlow expand_dims 多次
  • 张量流 expand_dims reverse
  • 张量流 expand_dims 图层
  • 张量流 expand_dims pytorch
  • 张量流稀疏扩展 _dims
  • TensorFlow keras expand_dims

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

TensorFlow feed_dict + 9 个示例

原文:https://pythonguides.com/tensorflow-feed_dict/

Python & Machine Learning training courses

你知道如何在 TensorFlow 占位符 中创建一个 feed_dict 吗?因此,在这个 Python 教程中,我们将学习 Python 中的 TensorFlow feed_dict ,我们还将涵盖与 TensorFlow feed_dict 相关的不同示例。我们将讨论这些话题。

  • TensorFlow feed_dict 多值
  • TensorFlow feed_dict numpy 数组
  • TensorFlow feed_dict 与数据集
  • TensorFlow feed_dict 张量
  • TensorFlow feed _ 字典列表
  • TensorFlow feed_dict batch
  • TensorFlow 会话运行时没有 feed_dict
  • TensorFlow 评估馈送 _ 字典
  • TensorFlow 无法将 feed_dict 键解释为张量

目录

TensorFlow feed_dict

  • 在本节中,我们将讨论如何使用 TensorFlow 在占位符中使用 feed_dict。
  • 在 TensorFlow 中,有一些占位符与任何人都可以声明的变量相同,即使是在运行时使用 feed_dict 参数。feed_dict 参数在 TensorFlow 中用于将值提供给这些占位符,以避免出现提示您为 TensorFlow 中的占位符提供值的错误。
  • 我们通过使用语法 feed_dict= {x:[2,20],b:[1,25]}),在每个会话中包含 feed dict pass 和 fetch。提要字典为该计算指定占位符值,而 fetches 参数指示我们想要计算的内容。
  • 在 TensorFlow 中,占位符是一个变量,它分配数据并将值输入计算图。这种方法允许用户提供操作数据并生成我们的计算图。
  • 在 Python 中,如果我们想要初始化一些数据,那么我们使用变量,但是在 placeholder 中,你可以将数据输入到计算图中。
  • 在 TensorFlow 的最新版本中,我们准备使用 tf.compat.v1.placeholder()函数,这个函数只会在 TensorFlow 2.x 版本中执行。

语法:

让我们看看语法并理解 Python TensorFlow 中的TF . compat . v1 . placeholder()函数的工作原理。

tf.compat.v1.placeholder
                       (
                        dtype,
                        shape=None,
                        name=None
                       )

现在让我们讨论一下我们将在示例中使用的这些参数

  • 它由几个参数组成
    • dtype: 该参数指定张量中的元素类型。
    • 形状:默认情况下,它没有值,如果你没有在张量中提到形状,那么你可以输入任何形状的张量。
    • 名称:该参数指定操作的名称,可选参数。

示例:

让我们举个例子,看看如何使用 TensorFlow 在占位符中创建一个 feed_dict。

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
input_tens_1 = tf.compat.v1.placeholder(tf.int32)
input_tens_2 = tf.compat.v1.placeholder(tf.int32)
result = tf.math.multiply(input_tens_1, input_tens_2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result, feed_dict={input_tens_1: 56, input_tens_2: 78})
    print(new_output)
  • 在下面的代码中,我们导入了别名为“tf”的 TensorFlow 库,然后声明了两个占位符,其数据类型为 tf.int32()
  • 之后,我们通过使用 tf.math.multiply 执行操作,然后通过导入TF . compat . v1 . disable _ eager _ execution()函数创建会话。
  • 创建会话时,我们将 feed_dict 指定为参数。

下面是以下代码的截图

Tensorflow feed_dict

Tensorflow feed_dict

这就是我们如何在 TensorFlow 占位符中使用 fee_dict

读取: Tensorflow 获取静态值

TensorFlow feed_dict 多值

  • 让我们通过 TensorFlow 来讨论如何使用占位符 fee_dict 中的多个值。
  • 为了执行这个特定的任务,我们将使用 tf.graph() 的概念,图指定了节点和一条边,而节点接受更多的张量作为输入,并生成给定的张量作为输出。在这个例子中,我们将使用 tf.compat.v1.graph() 。在 Tensorflow 中,如果你想在图形中添加变量,你可以很容易地调用构造函数,当创建一个张量时,我们有与初始值相同的数据类型。
  • 在 tf。 placeholder() 我们可以很容易地在稍后的会话中将该值存储为 feed_dict 。如果我们在运行会话时没有传递任何值,那么将会产生一个错误。

语法:

下面是 Python TensorFlow 中 tf.placeholder() 函数的语法

tf.compat.v1.placeholder
                       (
                        dtype,
                        shape=None,
                        name=None
                       )

示例:

让我们举一个例子,了解如何在 feed_dict 中使用多个值

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
# Build a graph
graph = tf.compat.v1.Graph()
with graph.as_default():
    # declare a placeholder that is 3 by 4 of type float32
    input_tens = tf.compat.v1.placeholder(tf.int32, shape=(2, 2), name='input_tensor')

    # Perform some operation on the placeholder
    result = input_tens * 3

# Create an input array to be fed
arr = np.ones((2,2))

# Create a session, and run the graph
with tf.compat.v1.Session(graph=graph) as val:
    # run the session up to node b, feeding an array of values into a
    new_output = val.run(result, feed_dict={input_tens: arr})
    print(new_output)
  • 在上面的代码中,我们导入了 TensorFlow 库,然后声明了一个 2 乘 2 张量的占位符,其值是 32 位整数(或者可以转换为 32 位整数)。
  • 一旦执行了这段代码,输出会显示 3 乘以 1 的值,这意味着输入数组被乘以了两倍。

下面是以下代码的截图

TensorFlow feed_dict multiple values

TensorFlow feed_dict multiple values

正如你在截图中看到的,我们已经在 feed_dict 中分配了输入张量和数组

阅读:张量流交叉熵损失

TensorFlow feed_dict numpy 数组

  • 在这一节中,我们将讨论如何在 feed_dict 中创建一个 numpy 数组。
  • 为了执行这个特定的任务,我们将使用TF . compat . v1 . placeholder()函数,并将数据类型、形状指定为参数。
  • 接下来,我们将使用 np.ones() 函数创建 numpy 数组,在这个函数中,我们提到了形状。

示例:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
new_tens= tf.compat.v1.placeholder(tf.int32,shape=(2, 2),name='tensor')

z = new_tens *2
new_arr= np.ones((2,2))

with tf.compat.v1.Session() as val:
    new_output=val.run(z, feed_dict={new_tens:new_arr})
    print(new_output)
    print(type(new_output))

你可以参考下面的截图

TensorFlow feed_dict numpy array

TensorFlow feed_dict numpy array

在给定的例子中,我们在 feed_dict 中分配了 numpy 数组

阅读:梯度下降优化器张量流

TensorFlow feed_dict 张量

  • 这里我们将讨论如何使用 TensorFlow 在 feed_dict 中创建张量。
  • 为了执行这个特定的任务,我们将使用TF . compat . v1 . placeholder()函数,占位符是一个变量,它分配数据并将值输入计算图。

示例:

我们举个例子,了解一下如何在 feed_dict 中创建张量。

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
input_tensor_1= tf.compat.v1.placeholder(tf.int32)
input_tensor_2 = tf.compat.v1.placeholder(tf.int32)
result = tf.add(input_tensor_1, input_tensor_2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result, feed_dict={input_tensor_1: 156, input_tensor_2: 278})
    print(new_output)
  • 在下面的代码中,我们导入了别名为“tf”的 TensorFlow 库,然后声明了两个占位符,其数据类型为 tf.int32()
  • 之后,我们通过使用 tf.add() 执行操作,然后通过导入TF . compat . v1 . disable _ eager _ execution()函数创建会话。
  • 创建会话时,我们将 feed_dict 指定为参数。

下面是以下代码的截图

TensorFlow feed_dict tensor

TensorFlow feed_dict tensor

这就是我们如何在 feed_dict 中分配输入张量

阅读:张量流 clip_by_value

TensorFlow feed_dict list

  • 在本节中,我们将讨论如何使用 TensorFlow 在 feed_dict 中声明一个列表。
  • 为了执行这个特定的任务,我们将在创建会话时使用 for-loop() 方法。
  • 在这个例子中,我们将使用TF . compat . v1 . placeholder()函数,然后通过使用 for 循环方法,我们可以很容易地迭代已经在 feed_dict() 中分配的占位符值,并且在其中,我们已经在其中分配了 list。

示例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

tens = tf.compat.v1.placeholder(tf.int32, shape=[4])
with tf.compat.v1.Session() as val:
    for i in range(4):
        print(val.run(tens[i], feed_dict={tens : [12,27,95,13]}))

在下面给出的代码中,我们导入了

你可以参考下面的截图

TensorFlow feed_dict list

TensorFlow feed_dict list

正如你在截图中看到的,我们已经在 feed_dict 中分配了列表

阅读:张量流乘法

TensorFlow feed_dict batch

  • 在本节中,我们将讨论如何使用 TensorFlow 在 feed_dict 中获取批处理。
  • 为了完成这个任务,我们将使用TF . data . dataset . from _ tensor slices()函数,在这个函数中,我们将设置 batch 和 epochs() 值。
  • 接下来,我们将声明大小和纪元值的变量,然后使用 tf.variable scope() 函数。该函数声明新的变量,并在禁用急切执行时按预期工作。

示例:

import tensorflow as tf
from __future__ import absolute_import
from __future__ import division

def ds_train(new_val_size, new_epochs):  
    new_val = (tf.data.Dataset.from_tensor_slices(([16.2,76.2,38.4,11.6,19.3], [-12,-15,-28,-45,-89]))
            .batch(new_val_size)
            .repeat(new_epochs)        
            )
    return new_val

new_val_size= 1
input_size = 1
new_epochs = 2

with tf.variable_scope("dataset"):       
    result= ds_train(new_val_size, new_epochs)

with tf.variable_scope("iterator"):
    val_iterate = result.make_initializable_iterator()
    new_iterate_handle = tf.placeholder(tf.string, shape=[])
    iterator = tf.data.Iterator.from_string_handle(new_iterate_handle, 
                                                val_iterate.output_types,
                                                val_iterate.output_shapes)

    def next_item():
        new_element = iterator.get_next(name="new_element")
        m, n = tf.cast(new_element[0], tf.float32), new_element[1]
        return m, n        

inputs = tf.Variable(tf.zeros(shape=[new_val_size,input_size]), dtype=tf.float32, name="inputs", trainable=False, use_resource=True)
target = tf.Variable(tf.zeros(shape=[new_val_size], dtype=tf.int32), dtype=tf.int32, name="target", trainable=False,use_resource=True)
is_new = tf.placeholder_with_default(tf.constant(False), shape=[], name="new_item_flag")

def new_data(new_val_size, input_size):

    next_inputs, next_target = next_item()
    next_inputs = tf.reshape(next_inputs, shape=[new_val_size, input_size])
    with tf.control_dependencies([tf.assign(inputs, next_inputs), tf.assign(target, next_target)]):
        return tf.identity(inputs), tf.identity(target)

def old_data():

    return inputs, target

next_inputs, next_target = next_item()

inputs, target =  tf.cond(is_new, lambda:new_data(new_val_size, input_size), old_data)

with tf.Session() as sess:
    sess.run([tf.global_variables_initializer(),tf.local_variables_initializer()])
    handle_t = sess.run(val_iterate.string_handle())
    sess.run(val_iterate.initializer)
    while True:
        try:
            print(sess.run([inputs, target], feed_dict={new_iterate_handle:handle_t, is_new: False}))
            print(sess.run([inputs, target], feed_dict={new_iterate_handle:handle_t, is_new: False}))
            print(sess.run([inputs, target], feed_dict={new_iterate_handle:handle_t, is_new: True}))
        except tf.errors.OutOfRangeError:
            print("End of training dataset.")
            break 

在下面给出的代码中,我们使用了TF . data . iterator . from _ string _ handle()函数,该函数指示了遍历数据集,然后使用 tf.variables() 函数声明张量的状态。

下面是以下代码的截图

TensorFlow feed_dict batch

TensorFlow feed_dict batch

这就是我们如何通过 Tensorflow 在 feed_dict 中使用批处理

阅读: Python TensorFlow 占位符

TensorFlow 会话在没有 feed_dict 的情况下运行

  • 这里我们可以在 TensorFlow 中不使用 feed_dict 创建一个正在运行的会话。
  • 在本例中,我们将使用 tf.compat.v1.Session()的概念,它是一个用于运行会话的类。为了完成这项任务,我们将首先导入带有 tf 别名的 TensorFlow 库,其中 tf 代表 TensorFlow ,它用于数值计算问题。接下来,我们将创建一个张量形式的变量,并分配一个 tf.constant() 函数。
  • 在 Python 中,这个函数采用一个常数值,表示不修改的值,它还初始化一个对象,如数组或列表。
  • 这里我们将在节点 new_output 应用数学运算 (*) 。为了运行这个会话,我们将使用 val.run() 语法。在这个参数中,我们将使用乘法运算。

语法:

下面是 Python TensorFlow 中 tf.compat.v1.Session() 函数的语法

tf.compat.v1.Session(
    target='', graph=None, config=None
)
  • 它由几个参数组成。
    • target:这是一个可选参数,默认情况下,它在流程引擎中使用。
    • graph:要开始的图形,是一个可选参数。
    • Config:默认情况下,它不接受任何值,并通过配置进行缓冲。

示例:

让我们举一个例子,了解一下 tf.compat.v1.Session() 函数创建任意会话的工作原理。

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
# Build a tensor
tens_1 = tf.constant(12.0)
tens_2= tf.constant(16.0)
result = tens_1 * tens_2

new_output = tf.compat.v1.Session()
# Display the Content
print(new_output.run(result))

你可以参考下面的截图

TensorFlow session run without feed_dict

TensorFlow session run without feed_dict

这就是我们不使用 feed_dict 运行会话的方式

阅读:将列表转换为张量张量流

张量流评估馈送 _ 字典

  • 在本节中,我们将讨论如何通过 TensorFlow 来使用 feed_dict 中的 eval。
  • 为了执行这个特定的任务,我们将使用 tf.graph() ,这个方法定义了在操作之间流动的数据单元。
  • 在这个例子中,我们将使用TF . compat . v1 . placeholder()函数,在这个函数中,我们将数据类型和形状指定为一个参数。

示例:

import tensorflow as tf
import numpy as np
tf.compat.v1.disable_eager_execution()

new_graph = tf.Graph()
with new_graph.as_default():

    new_tens = tf.compat.v1.placeholder(tf.int32, shape=(2, 2))
    new_tens2 = tf.compat.v1.placeholder(tf.int32, shape=(2, 2))
    b = tf.math.multiply(new_tens, new_tens2)

new_arr = np.zeros((2,2))

with tf.compat.v1.Session(graph=new_graph) as session:
    output = session.run(b, feed_dict={new_tens: new_arr,new_tens2: new_arr})
    print(output)

下面是以下给定代码的输出

TensorFlow eval feed_dict

TensorFlow eval feed_dict

阅读:Python tensor flow expand _ dims

TensorFlow 无法将 feed_dict 键解释为张量

  • 在本节中,我们将讨论“TensorFlow 无法将 feed_dict 键解释为张量”的错误消息。
  • 当我试图获取输入张量中的值时,输出引发了这个错误,并且无法将 feed_dict 解释为张量。在这个例子中,我们将使用 tf.placeholder() 创建一个张量,在这个张量中,我们已经指定了数据类型和操作名称。
  • 接下来,我们将运行会话,并为 feed_dict 分配张量值 {x: [34,78,18]})。

示例:

import tensorflow as tf
tens_1 = tf.placeholder(tf.float32, (None,), 'tens_1')
tens_2 = tf.reduce_sum(x)
sess = tf.Session()

sess.run(y, {x: [34, 78, 18]})
sess.run(y, {'tens_1': [34, 78, 18]})

TensorFlow cannot interpret the feed_dict key as tensor

TensorFlow cannot interpret the feed_dict key as tensor

此错误的解决方案

import tensorflow as tf
# Creation of tensor
tens_1 = tf.placeholder(tf.float32, (None,), 'x')
tens_2 = tf.reduce_sum(tens_1)
sess = tf.Session()
sess.run(tens_2, {tens_1: [14, 16, 18]})

下面是以下代码的截图

Solution of TensorFlow cannot interpret the feed_dict key as tensor

Solution of TensorFlow cannot interpret the feed_dict key as tensor

这就是我们如何解决 TensorFlow 无法解释 feed_dict 的错误

您可能也喜欢阅读以下 Python TensorFlow 教程。

在本教程中,我们已经学习了 Python 中的 TensorFlow feed_dict ,我们还介绍了与 TensorFlow feed_dict 相关的不同示例。我们将讨论这些话题。

  • TensorFlow feed_dict 多值
  • TensorFlow feed_dict numpy 数组
  • TensorFlow feed_dict 与数据集
  • TensorFlow feed_dict 张量
  • TensorFlow feed _ 字典列表
  • TensorFlow feed_dict batch
  • 张量流 feed-dict 数据集
  • TensorFlow 会话运行时没有 feed_dict
  • TensorFlow 评估馈送 _ 字典
  • TensorFlow 无法将 feed_dict 键解释为张量

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流全连通层

原文:https://pythonguides.com/tensorflow-fully-connected-layer/

Python & Machine Learning training courses

在本 Python 教程中,我们将重点介绍如何用 Python 构建 TensorFlow 全连通层。此外,我们将查看一些如何在 TensorFlow 中获得上一层输出的示例。我们将讨论这些话题。

  • 张量流全连通层
  • 张量流全连接层与卷积层
  • 张量流 CNN 全连接层
  • 稀疏全连通层张量流
  • 层的张量流列表
  • 张量流密集层示例
  • TensorFlow 按名称获取图层
  • TensorFlow remove layers
  • 张量流获取层权重

目录

TensorFlow 全连通层

  • 一组相互依赖的非线性函数构成了神经网络。神经元是每个特定功能(或感知)的基本单位。
  • 全连接层中的神经元使用权重矩阵线性变换输入向量。然后使用非线性激活函数 f 对产品进行非线性变换
  • 图层的输入和权重矩阵之间的点积由激活函数 f 包装。在训练模型时,权重矩阵的列将全部具有不同的值并被优化。

示例:

让我们举个例子,看看如何创建一个完全连接的层。

import tensorflow as tf 

from tensorflow.keras import datasets, layers, models 

import matplotlib.pyplot as plt 

(new_train_images, new_train_labels), (new_test_images, new_test_labels) = datasets.cifar10.load_data() 

new_train_images, new_test_images = new_train_images / 255.0, new_test_images / 255.0 

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 

               'dog', 'frog', 'horse', 'ship', 'truck'] 

plt.figure(figsize=(10,10)) 

for i in range(25): 

    plt.subplot(5,5,i+1) 

    plt.xticks([]) 

    plt.yticks([]) 

    plt.grid(False) 

    plt.imshow(new_train_images[i]) 

    plt.xlabel(class_names[new_train_labels[i][0]]) 

plt.show() 

model = models.Sequential() 

model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3))) 

model.add(layers.MaxPooling2D((2, 2))) 

model.add(layers.Conv2D(64, (3, 3), activation='relu')) 

model.add(layers.MaxPooling2D((2, 2))) 

model.add(layers.Conv2D(64, (3, 3), activation='relu')) 

model.add(layers.Flatten()) 

model.add(layers.Dense(64, activation='relu')) 

model.add(layers.Dense(10)) 

model.compile(optimizer='adam', 

              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), 

              metrics=['accuracy']) 

history = model.fit(new_train_images, new_train_labels, epochs=10,  

                    validation_data=(new_test_images, new_test_labels)) 

plt.plot(history.history['accuracy'], label='accuracy') 

plt.plot(history.history['val_accuracy'], label = 'val_accuracy') 

plt.xlabel('Epoch') 

plt.ylabel('Accuracy') 

plt.ylim([0.5, 1]) 

plt.legend(loc='lower right') 

test_loss, test_acc = model.evaluate(new_test_images,  new_test_labels, verbose=2) 

在下面的代码中,我们导入了 Tensorflow 和 matplotlib 库,然后使用命令datasets . cifar 10 . load _ data()加载数据集。接下来,我们将数据集分为训练和测试部分。

之后,我们创建了一个序列模型,使用 conv 2d 并提到输入图像形状 (32,32,3),,然后使用 model.compile() 并分配优化器‘亚当’

下面是下面给出的代码的截图。

TensorFlow Fully Connected Layer

TensorFlow Fully Connected Layer

这就是我们如何使用 TensorFlow 找到全连接层的损耗和精度值。

阅读:张量流自定义损失函数

TensorFlow 全连接层 vs 卷积层

  • 在本节中,我们将讨论什么是密集层,我们还将了解连接层和密集层之间的区别。
  • 在模型中,前一层中的每个神经元向密集层中的神经元发送信号,密集层中的神经元将矩阵和向量相乘。在矩阵向量乘法期间,来自先前层的输出的行向量等于密集层的列向量。
  • 行向量的列数必须与列向量的列数相等,才能将矩阵与向量相乘。
  • 完全链接的层中的神经元连接到它之前的层中的每个神经元,并且如果这些神经元中的任何一个发生变化,它也可以发生变化。然而,在卷积核的范围内,卷积层中的神经元仅连接到来自前一层的“附近”神经元。

示例:

import numpy as np
import tensorflow as tf
from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Dense, Flatten, Conv2D

np.random.seed(44)
tf.random.set_seed(44)

new_arr = np.random.rand(4, 32, 32, 3)

input_shape = Input(shape=new_arr.shape[1:])
convolution_layer = Conv2D(filters=8, kernel_size=(3, 3), activation='relu')(input_shape)
flatten = Flatten()(convolution_layer)
feature_map = Dense(8, activation='relu')(flatten)
new_output = Dense(2, activation='softmax')(flatten)
result = Model(inputs=input_shape, outputs=new_output)

result(new_arr)

在上面的代码中,我们已经导入了 numpy 和 TensorFlow 库。接下来,我们使用了 tf.random.set_seed() 函数。全局和操作级种子是操作使用的随机种子的来源。

当全局种子是预先确定的而操作种子不是预先确定的时,除了全局种子之外,系统确定性地选择一个操作种子来产生不同的随机序列。接下来,我使用了 conv2d() 图层,并用 kernel_size() 分配滤镜。

之后,我们添加具有输入形状 8 和激活函数‘relu’的密集层。

下面是下面给出的代码的截图。

TensorFlow fully connected layer vs convolutional layer

TensorFlow fully connected layer vs convolutional layer

在本例中,我们已经了解了全连接层和卷积层之间的区别。

阅读:tensor flow next _ batch+Examples

TensorFlow CNN 全连接层

  • 卷积神经网络(CNN),通常称为 CNN,是深度神经网络的一个子集,用于评估计算机视觉应用中的视觉数据。它被用于神经语言处理、视频或图片识别等程序中。
  • Cnn 和其他神经网络的主要区别在于,Cnn 的输入是二维数组,而其他神经网络的输入是 n 维数组。
  • 卷积层是模型中最重要的部分。该图层的主要目标是提高概化效果,并缩小权重较快部分的图像尺寸。

举例:

import tensorflow as tf

from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

train_images, test_images = train_images / 255.0, test_images / 255.0

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i])
    plt.xlabel(class_names[train_labels[i][0]])
plt.show()
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.summary()

你可以参考下面的截图。

TensorFlow CNN fully connected layer

TensorFlow CNN fully connected layer

这就是我们如何在全连接层中使用卷积神经网络。

阅读: TensorFlow 全球平均池

稀疏全连通层张量流

  • 本质上,我们随机初始化我们网络中的稀疏连接层,并开始用反向传播和其他常见的深度学习优化方法进行训练。
  • 在每个时期之后,“最弱”连接被消除,并且它们的位置被具有随机初始化的新创建的连接所取代。
  • 为了执行此任务,我们将使用 tf.sparse tensor() 函数索引、值和密集形状是 TensorFlow 用来表示稀疏张量的三个不同的密集张量。
  • 为了使用简单,这三个张量在 Python 中被组合成一个 SparseTensor 类。在将它们提供给下面的操作之前,将任何不同的密集形状、密集值和索引张量包装在 SparseTensor 对象中。

语法:

让我们看一下语法,了解一下TF . sparse . sparsesensor()函数的工作原理。

tf.sparse.SparseTensor(
                       indices, 
                       values, 
                       dense_shape
                     )
  • 它由几个参数组成
    • indexes:是形状的 2 维 int 64 张量。
    • values :任意类型和形状的一维张量。
    • dense_shape :指定稠密张量的形状。

举例:

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32,shape = [4,2],name = "x")

y = tf.placeholder(tf.float32,shape = [4,1],name = "y")
m = np.shape(x)[0]
n = np.shape(x)[1]
hidden_s = 2 
l_r = 1

theta1 = tf.SparseTensor(indices=[[0, 0],[0, 1], [1, 1]], values=[0.1, 0.2, 0.1], dense_shape=[3, 2])

theta2 = tf.cast(tf.Variable(tf.random_normal([hidden_s+1,1]),name = "theta2"),tf.float32)

a1 = tf.concat([np.c_[np.ones(x.shape[0])],x],1)

z1 = tf.matmul(a1,tf.sparse_tensor_to_dense(theta1)) 

a2 = tf.concat([np.c_[np.ones(x.shape[0])],tf.sigmoid(z1)],1)

z3 = tf.matmul(a2,theta2)

h3 = tf.sigmoid(z3)
cost_func = -tf.reduce_sum(y*tf.log(h3)+(1-y)*tf.log(1-h3),axis = 1)

optimiser = tf.train.GradientDescentOptimizer(learning_rate = l_r).minimize(cost_func)

X = [[0,0],[0,1],[1,0],[1,1]]
Y = [[0],[1],[1],[0]]

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

for i in range(200):
   sess.run(optimiser, feed_dict = {x:X,y:Y})
   if i%100==0:
      print("Epoch:",i)
      print(sess.run(theta1))

在下面的代码中,我们使用了 tf.placeholder() 函数来创建张量,在这个函数中,我们使用了 tf.float() 数据类型和形状。接下来,我们使用稀疏张量,其中我们已经传递了索引、值和密集形状。

你可以参考下面的截图

sparse fully connected layer tensorflow

sparse fully connected layer TensorFlow

这就是我们如何通过 TensorFlow 在全连接层中使用稀疏张量。

阅读:二元交叉熵张量流

层的张量流列表

  • 这里我们将使用 TensorFlow 来讨论图层列表。
  • 通过其 Keras Layers API,Keras 为各种神经网络拓扑和用途提供了各种各样的预构建层。这些随时可用的层通常适用于构建大多数深度学习模型,具有很大的灵活性,使它们非常有帮助。
  • 现在我们来讨论一些流行的 Keras 层。
    • 密集层:密集层是一个流行的 Keras 层,用于在神经网络中构建一个密集链接的层,其中每一层的神经元都从所有前面层的神经元获得输入。
    • 展平图层:使用展平将输入展平。例如,如果将展平应用于输入形状为(批量大小,2,2) 的层,则层的输出形状将为(批量大小,4)
    • 辍学层:机器学习的一个关键思想就是辍学。它被应用于解决过拟合问题。数据输入可能包含一些不需要的信息,通常称为噪声。Dropout 将尝试排除噪声数据,以避免过度拟合模型。
    • 重塑图层:可使用重塑命令改变输入形状。例如,如果层的输入形状是(批量大小,3,2) ,并且使用了带参数 (2,3) 的整形,则层的输出形状将是(批量大小,2,3)
    • Lambda 层:通过使用表达式或函数,使用 Lambda 层转换输入数据。
    • 池层:池层的主要目的是逐渐降低输入图像的空间大小,这将减少网络所需的计算次数。

密集层示例

它对卷积层提取的特征进行分类。

源代码:

from keras.models import Sequential 
from keras.layers import Activation, Dense 

new_model_var = Sequential() 
new_layer = Dense(20, input_shape = (5,)) 
new_model_var.add(new_layer) 
new_layer.input_shape  
new_layer.output_shape 

在下面给定的代码中,我们创建了模型 sequential() ,并使用输入形状的密集层。接下来,我们给模型添加了一个图层,得到了一个密集图层的形状。

下面是下面给出的代码的截图。

Dense layer in TensorFlow

Dense layer in TensorFlow

展平图层

我们展平卷积层的输出,以声明单个长特征向量。

源代码:

from keras.layers import Flatten
from keras.models import Sequential 
from keras.layers import Activation, Dense 

model = Sequential()
layer_1 = Dense(8, input_shape=(8,8)) 
model.add(layer_1) 
layer_2 = Flatten() 
model.add(layer_2) 
layer_2.input_shape
layer_2.output_shape

在上面的代码中,我们导入了扁平化的顺序模型。接下来,我们创建了顺序模型,并添加了第一个密集层。之后,我添加了 flatten layer() 并给它分配 layer2。

你可以参考下面的截图

flatten layer

flatten layer

脱落层

Dropout 是一种随机忽略部分神经元的训练方法。

源代码:

import keras

result= keras.layers.Dropout(0.5, noise_shape = None, seed = None)
print(result)

在上面的代码中,我们已经导入了 Keras 库,然后使用了 keras.layers.Dropout() 函数,并为其分配了 noise_shape 和 seed 参数。

下面是以下代码的截图

Dropout layer

Dropout layer

重塑图层

如果一个整形层有一个参数 (4,5) ,并且它被应用到一个输入形状为 (batch_size,5,4) 的层,那么该层的结果形状将变为 (batch_size,4,5)

from keras.models import Sequential 
from keras.layers import Activation, Dense, Reshape 

model = Sequential() 

layer_1 = Dense(36, input_shape = (6,6)) 
model.add(layer_1) 

layer_2 = Reshape((36, 6)) 
model.add(layer_2)
layer_2.input_shape 

你可以参考下面的截图

reshape layer

reshape layer

阅读:二元交叉熵张量流

TensorFlow 密集层示例

  • 在模型中,前一层中的每个神经元向密集层中的神经元发送信号,密集层中的神经元将矩阵和向量相乘。
  • 在矩阵向量乘法期间,来自先前层的输出的行向量等于密集层的列向量。
  • 行向量的列数必须与列向量的列数相等,才能将矩阵与向量相乘。
  • 密集层将背景中的矩阵和向量相乘。反向传播可用于训练和更新构成矩阵中使用的值的参数。
  • “m”维向量是致密层的结果。因此,密集层的主要目的是改变矢量的维度。密集层还对矢量执行操作,如旋转、缩放和平移。

语法:

下面是 TensorFlow 中稠密层的语法。

tf.keras.layers.Dense(
    units,
    activation=None,
    use_bias=True,
    kernel_initializer="glorot_uniform",
    bias_initializer="zeros",
    kernel_regularizer=None,
    bias_regularizer=None,
    activity_regularizer=None,
    kernel_constraint=None,
    bias_constraint=None,
    **kwargs
)
  • 它由几个参数组成
    • 单位:Keras 致密层最基本也是最重要的因素之一,决定了致密层输出的大小,就是单位。鉴于它表示输出向量的维数,它必须是一个正整数。
    • 激活:神经网络中的激活函数是转换神经元输入值的函数。本质上,它增加了神经网络的非线性,这样网络就可以计算出输入和输出值之间的关系。
    • use_bias :当选择是否在密集层中使用偏置矢量时,我们使用参数。在布尔参数中,如果未定义 use bias,它将被设置为 true。
    • kernel_initializer :使用该选项初始化内核权重矩阵。为了提取相关的特征核,将输入乘以权重矩阵,权重矩阵是权重矩阵。

致密层的例子

from keras.models import Sequential 
from keras.layers import Activation, Dense 

new_model_var = Sequential() 
new_layer = Dense(20, input_shape = (5,)) 
new_model_var.add(new_layer) 
new_layer.input_shape  
new_layer.output_shape 

在下面给出的代码中,我们创建了模型 sequential() 并使用了输入形状的密集层。接下来,我们给模型添加了一个图层,得到了一个密集图层的形状。

你可以参考下面的截图。

dense layer in tensorflow

dense layer in Tensorflow

正如您在截图中看到的,我们在顺序模型中使用了密集层。

阅读:张量流 clip_by_value

TensorFlow 按名称获取图层

  • 在这个例子中,我们将讨论如何在 TensorFlow 中按名称获取图层。
  • 为了完成这个任务,我们将使用 sequential() 函数,然后使用输入形状和 kernel _ regularizer 添加密集层。

举例:

from keras.models import Sequential 
from keras.layers import Activation, Dense 
from keras import initializers 
from keras import regularizers 
from keras import constraints 

model = Sequential() 

model.add(Dense(32, input_shape=(16,), 
   kernel_regularizer = None, kernel_constraint = 'MaxNorm', activation = 'relu')) 
model.add(Dense(16, activation = 'relu')) 
model.add(Dense(8))
print(model)

在上面的代码中,我们从 keras 模块中导入了初始化器、正则化器和约束。接下来,我们使用序列模型()并添加了输入形状的密集层和没有值的 kernel _ regularizer。

下面是以下给定代码的输出。

TensorFlow get layer by name

TensorFlow get layer by name

这就是我们如何使用 TensorFlow 按名称获取图层。

阅读:模块“张量流”没有属性“日志”

张量流移除图层

  • 在本节中,我们将讨论如何在 TensorFlow 中移除图层。
  • 为了执行这个特定的任务,我们将使用 model.layers.pop() 函数来移除模型的最后一层。
  • 使用 hidden = Dense(120,activation='relu') 删除先前的密集层,并添加您的新层。模型。层层[-1]。输出(型号。层[-2]]

举例:

import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Dense, Input, Layer
from tensorflow.keras.models import Model

new_input_tens = Input(shape=(10,))
new_hidden_layer = Dense(100, activation='relu')(new_input_tens)
new_output = Dense(10, activation='relu')(new_hidden_layer)
model = Model(new_input_tens, new_output)
model.compile(loss="mse", optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=0.001))
model.summary()
model.layers.pop()
model.layers.pop()
model.summary()
new_hidden = Dense(120, activation='relu')(model.layers[-1].output)
new_output = Dense(5, activation='softmax')(new_hidden)
model = Model(new_input_tens, new_output )
model.summary()

你可以参考下面的截图

TensorFlow remove layers

TensorFlow remove layers

这就是我们如何移除 TensorFlow 中的图层。

阅读:张量流均方误差

TensorFlow 获取层权重

  • 我们使用 TensorFlow 函数“随机正态初始化器”来初始化权重,这将使用正态分布随机初始化权重。权重的状态包含为张量变量。‘init’将用于初始化这些状态。
  • 重量值将以‘float 32’格式显示。由于设置为“可训练”,每次运行后,起始重量将根据损失函数和优化程序进行修改。
  • 它被贴上标签“内核”,以便以后可以很容易地找到它。

举例:

import tensorflow as tf

model = tf.keras.Sequential([
        tf.keras.layers.Dense(5, activation="relu", name="first_layer"),
        tf.keras.layers.Dense(6, activation="tanh", name="second_layer"),
        tf.keras.layers.Dense(5, name="last_layer"),
])
new_input_val = tf.random.normal((1,4))
new_output_val = model(new_input_val)
for new_layer in model.layers:
    print(new_layer.name, new_layer)
print(model.layers[0].weights)
print(model.layers[0].bias.numpy())
print(model.layers[0].bias_initializer)

在这个例子中,我们使用了 tf.keras.Sequential()模型,在这个模型中,我添加了三个密集层,并为输入形状分配了激活函数。接下来,我们使用了 tf.random.normal() 函数,并提到了形状 (1,4) 。现在我们要提取第一层,为此我使用了命令 (model.layers[0])。砝码)。

下面是以下代码的截图

TensorFlow get layers weights

TensorFlow get layers weights

正如你在截图中看到的,我们已经学会了如何在层中使用权重。

还有,多看看一些 Python 中的 TensorFlow 教程。

所以,在这个 Python 教程中,我们学习了如何在 TensorFlow 中构建一个 全连通层。此外,我们将查看一些如何在 TensorFlow 中获得上一层输出的示例。我们已经讨论了这些主题。

  • 张量流全连通层
  • 张量流全连接层与卷积层
  • 张量流 CNN 全连接层
  • TensorFlow 超薄全连接层
  • 稀疏全连通层张量流
  • 层的张量流列表
  • 张量流密集层示例
  • TensorFlow 按名称获取图层
  • TensorFlow remove layers
  • 张量流获取层权重

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

TensorFlow get shape

原文:https://pythonguides.com/tensorflow-get-shape/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何在 Python 中找到张量流的形状。此外,我们将涵盖以下主题。

  • 张量流得到张量的形状
  • 张量流获取数据集的形状
  • 张量流以列表形式获取形状
  • 张量流获取形状无
  • 张量流获取占位符的形状
  • Tensorflow x.get_shape()。as_list()

目录

TensorFlow get shape

  • 在本节中,我们将学习如何在 TensorFlow Python 中获取形状。
  • 要得到张量的形状,可以很容易地使用 tf.shape() 函数。这种方法将帮助用户返回给定张量的形状。例如,假设您有一个用整数填充的张量,并且您想要检查给定输入张量的形状。
  • 为了完成这个任务,我们可以很容易地使用 tf.shape() 函数,它返回 shape 属性作为 scaler 输入值。

语法:

让我们看一下语法,了解一下 tf.shape() 函数的工作原理。

tf.shape
        (
         input,
         out_type=tf.dtypes.int32,
         name=None
        )
  • 它由几个参数组成
    • 输入:该参数表示我们想要操作的输入张量
    • out_type =默认取 tf.dtypes.int32 值。这是一个可选参数,定义输出类型。
    • 名称:该参数表示操作的名称。

举例:

我们举个例子,看看如何在 TensorFlow Python 中获取形状。

源代码:

#Tensor
import tensorflow as tf

tensor = tf.constant([[[15, 67, 89], [34, 27, 89]], 
                [[45, 89, 189], [68, 91, 46]]])

result=tf.shape(tensor)
result

在上面的代码中,首先,我们导入 TensorFlow 库,然后使用 tf.constant() 函数创建张量。之后,我们声明了一个变量“result ”,并指定了 tf.shape() 函数来获取给定张量的形状。

下面是下面给出的代码的截图。

TensorFlow get shape of Tensor in Python

TensorFlow get shape

另外,检查:Python tensor flow reduce _ sum

TensorFlow 得到张量的形状

  • 让我们看看如何在 TensorFlow Python 中得到张量的形状。
  • 为了执行这个特殊的任务,我们将使用 tf.shape() 函数来获取张量的形状。
  • 接下来,我们将使用TF . compat . v1 . disable _ eager _ execution()来运行会话,它将显示数组大小。

举例:

我们举个例子,检查一下如何在 TensorFlow Python 中得到张量的形状。

源代码:

#Tensor
import tensorflow as tf

tf.compat.v1.disable_eager_execution()
tensor = tf.constant([[18, 29], [34, 78]])
result = tf.shape(tensor) 
print(result)    #shape of tensor
with tf.compat.v1.Session() as val:
   new_output=val.run(result)
new_output   #Display rows and columns dimension

在下面给出的代码中,我们通过使用 tf.constant() 函数创建了一个张量,忘记了张量的形状,我们应用了 tf.shape() 函数。

在这个方法中,我们传递张量作为参数。一旦执行了这段代码,输出将显示张量的形状。之后,我们已经应用了函数TF . compat . v1 . disable _ eager _ execution()

下面是以下给定代码的实现。

Python get shape in TensorFlow

TensorFlow get the shape of Tensor in Python

阅读:Python tensor flow reduce _ mean

TensorFlow 获取数据集的形状

  • 在本节中,我们将学习如何在 TensorFlow Python 中获取数据集的形状。
  • 为了完成这项任务,我们将使用 tfds 数据集的概念,它指定了 TensorFlow 中数据集的集合。
  • 在 Python 中, tfds 基本上是配合机器学习和 TensorFlow 框架使用的。
  • 要在您的机器上安装这个包,使用 pip install tfds-nightly 命令。

举例:

import numpy as np
import tensorflow as tf

import tensorflow_datasets as tfds
tensor=tfds.list_builders()
print(tensor)
result=tf.shape(tensor)
result

在上面的代码中,我们首先使用 tensorflow_datasets 作为 tfds 导入了 tfds 库。之后,我们使用了名为“list_builders”的数据集,它将显示可用构建器的列表。现在,我们想要得到给定数据集的形状,为此我们使用了 tf.shape() 函数。

下面是下面给出的代码的截图。

Python get shape of dataset in TensorFlow

TensorFlow get the shape of a dataset in Python

阅读: Python TensorFlow one_hot

TensorFlow 获取形状作为列表

  • 在这里,我们将看到如何在 Python 中以列表形式获得 TensorFlow 张量形状。
  • 为了执行这个特定的任务,我们将使用 shape.as_list() 函数。
  • 此方法返回指示数组形状和维度的整数值列表。

语法:

下面是 TensorFlow Python 中 as_list() 函数的语法。

as_list()

举例:

import tensorflow as tf

tensor = tf.constant([[[15, 67, 89], [34, 27, 89]], 
                [[45, 89, 189], [68, 91, 46]]])
new_output = tensor.shape.as_list()
new_output

在下面给出的代码中,我们导入了 TensorFlow 库,然后使用 tf.constant() 函数创建了一个张量。之后,我们使用函数 shape.as_list() 在列表中显示张量的形状。

下面是以下给定代码的实现。

 Tensorflow get shape as list in Python

Python Tensorflow get the shape as a list

阅读:tensor flow next _ batch+Examples

张量流获取形状无

  • 在本节中,我们将学习如何在 TensorFlow Python 中获得 none 形状。
  • 为了完成这个任务,我们将使用 tf.keras.layers.Input() 函数,这个方法是来自底层后端的张量对象。

语法:

下面是 tf 的语法。Keras.layers.input() 方法。

tf.keras.layer.Input
                    (
                     shape=None,
                     batch_size=None,
                     name=None,
                     dtype=None,
                     sparse=False,
                     tensor=None,
                     **kwargs
                    )

举例:

import tensorflow as tf

var = tf.keras.layers.Input((None,None))
var.shape

另外,你可以参考下面的截图。

Python TensorFlow get shape none

Python TensorFlow get shape none

读取: Tensorflow 获取静态值

TensorFlow 获取占位符的形状

  • 在这个程序中,我们将学习如何在 TensorFlow Python 中获取占位符的形状。
  • 为了完成这个任务,我们将使用TF . compat . v1 . placeholder()方法,这个方法允许我们声明我们的操作,它总是提供数据。

语法:

我们先来看看语法,了解一下TF . com apt . v1 . placeholder()的工作原理。

tf.compat.v1.placeholder
                        (
                         dtype,
                         shape=None,
                         name=None
                        )

举例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
tens=tf.compat.v1.placeholder(dtype=tf.int32,shape=(300,300))
tens

在上面的代码中,我们导入了 numpy 库,然后使用了TF . compat . v1 . disable _ eager _ execution()函数。之后,我们使用了 tf.compat.v1.placeholder ,在这个函数中,我们传递了 shape=( 300,300)) 作为参数。

下面是以下给定代码的执行。

Python TensorFlow get shape of placeholder

Python TensorFlow get a shape of a placeholder

阅读: TensorFlow 稀疏张量

Tensorflow x.get_shape()。as_list()

  • 让我们看看如何使用 th e x.get_shape()得到 TensorFlow 的形状。Python 中的 as_list() 函数。
  • 为了执行这个特定的任务,我们将使用 tensor.get_shape.as_list() 函数。此方法返回指示数组形状和维度的整数值列表。

举例:

import tensorflow as tf

new_tens = tf.constant([[[78, 92, 167], [98, 178, 94]], 
                [[178, 236, 345], [109, 256, 345]]])
new_result = new_tens.get_shape().as_list()
new_result

下面是下面给出的代码的截图。

Python Tensorflow x.get_shape as_list

Python Tensorflow x.get_shape as_list

还有,多看看一些 Python 相关的教程。

在本教程中,我们学习了如何在 Python 中找到张量流的形状。此外,我们还讨论了以下主题。

  • 张量流得到张量的形状
  • 张量流获取数据集的形状
  • 张量流以列表形式获取形状
  • 张量流获取形状无
  • 张量流获取占位符的形状
  • Tensorflow x.get_shape()。as_list()

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流获取静态值

原文:https://pythonguides.com/tensorflow-get-static-value/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何获取 Python TensorFlow 中的静态值。此外,我们将涵盖以下主题。

  • 张量流获取静态值
  • TensorFlow 获取值的索引
  • Tensorflow 从 tf 变量获取值
  • 张量流得到一个常量张量值
  • 模块“TensorFlow”没有属性“获取静态值”

目录

TensorFlow 获取静态值

  • 在本节中,我们将讨论如何在 Python TensorFlow 中获取静态值。
  • 为了执行这个特定的任务,我们将使用*TF . get _ static _ value()*函数,这个函数用于显示来自输入张量的常数值。
  • 在 TensorFlow 中,静态值意味着常量值,如果静态值无法测量,则它将返回 none 值。

语法:

让我们看一下语法,了解一下 Python TensorFlow 中 tf.get_static_value() 函数的工作原理。

tf.get_static_value(
                    tensor,
                    partial=False
                   )
  • 它由几个参数组成。
    • 张量:该参数指定输入张量。
    • partial: 默认情况下,它接受一个 false 值,如果为 true,那么它将返回一个部分求值的数组,如果为 none,则不能求值。

Return: 该方法返回 NumPy 个 n 维数组,值为常量。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取静态值。

源代码:

import tensorflow as tf

new_tens = tf.constant([[45, 26, 16], [22, 18, 29], [13, 28, 90]])
new_output = tf.get_static_value(new_tens)
print("Static value:",new_output)

在下面给出的代码中,我们使用 tf.constant() 函数创建了输入张量,然后使用 tf.get_static_value() 函数,并将输入张量变量‘new _ tens’作为参数传递。

下面是下面给出的代码的截图。

tensorflow get static value

TensorFlow get static value

阅读:tensor flow next _ batch+Examples

TensorFlow 获取索引的值

  • 这里我们要了解如何在 Python TensorFlow 中获取值的索引。
  • 通过使用 tf。其中()函数,我们可以很容易地得到指标的值。该功能将帮助用户获得 yx 的复用索引。
  • 该函数根据给定的条件返回来自第二个输入张量或第一个张量的值。

语法:

下面是 Python TensorFlow 中 tf.where() 函数的语法。

tf.where(
        condition,
        x=None, 
        y=None, 
        name=None
)
  • 它由几个参数组成
    • 条件:该参数指定条件,必须是 dtype bool 或整数值。
    • x 和 y: 如果给定了,那么同类型的输入张量具有条件和 y 允许的形状。
    • 名称:默认不取值,指定操作的名称。

Returns: 这个方法将返回张量的值。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取值的索引。

源代码:

import tensorflow as tf

m = tf.constant([False, False, True, True])  

result= tf.where(m).numpy()
print("Get index of value:",result)
  • 首先,我们将导入 TensorFlow 库,然后使用 tf.constant() 函数创建一个输入张量。
  • 在这个函数中,我们将布尔值作为一个参数。
  • 之后,我们使用了 tf.where() 函数从张量中获取索引值。

下面是以下给定代码的实现。

Tensorflow get index of value

Tensorflow get the index of the value

阅读:梯度下降优化器张量流

TensorFlow 从 tf.variable()中获取值

  • 在这个例子中,我们将讨论如何从 Python TensorFlow 中的 tf.variable() 函数获取值。
  • 为了完成这项任务,我们将使用 tf.variable() 函数作为输入张量,并从参数中获取值。
  • 在 Python Tensorflow 中,变量用于存储参数或值,这些值在训练期间会不断修改。

举例:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
new_tensor = tf.Variable([167, 876,567])
tens_init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as val:
    val.run(tens_init)
    new_output=val.run(new_tensor)
    print(new_output)

在下面给出的代码中,我们创建了TF . compat . v1 . global _ variables _ initializer()函数,并通过使用 tf.compat.v1.Session() 函数运行会话。一旦执行了这段代码,输出将显示输入张量的值。

你可以参考下面的截图。

get value from tf.variable()

TensorFlow get the value from the tf.variable()

阅读:二元交叉熵张量流

TensorFlow 得到一个常量张量值

  • 在本节中,我们将讨论如何在 Python TensorFlow 中获得一个常量张量值。
  • 为了执行这个特定的任务,我们将使用 tf.constant() 函数从输入张量中获取常数值。
  • 这个函数用于声明一个给定对象的常数张量。

语法:

下面是 Python TensorFlow 中 tf.constant() 函数的语法

tf.constant(
            value, 
            dtype=None, 
            shape=None, 
            name='Const'
           )
  • 它由几个参数组成
    • 值:该参数指定我们想要转换成张量的值。
    • dtype: 默认情况下,它不取任何值,并定义输出张量的类型。
    • shape: 它指定了结果张量的维数。
    • name: 默认取常数值,指定张量的名称。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取一个常张量值。

源代码:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
new_tensor = tf.constant([34, 29,134,178])
get_val = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as val:
    val.run(get_val)
    new_output=val.run(new_tensor)
    print(new_output)

下面是下面给出的代码的截图。

Tensorflow get constant value

Tensorflow get constant value

阅读: Tensorflow 嵌入 _ 查找

模块“TensorFlow”没有属性“获取静态值”

这里我们要讨论的是错误模块‘tensor flow’没有属性‘get static value’。

原因:旧版 1。 x, tf.get 静态值已被移除,如果您使用的是 TensorFlow 的最新版本,那么它可以在复杂程序中工作。

举例:

import tensorflow as tf

new_tens = tf.constant([[15, 27, 45], [109, 278, 145], [234, 189, 289]])
new_output = tf.get_static_value(new_tens)
print("Static value:",new_output)

下面是以下给定代码的实现。

module TensorFlow has no attribute get static value

module TensorFlow has no attribute get static value

解决方案:

以下是此错误的解决方案。

在这个例子中,我们将使用 TensorFlow 2.x 版本。

import tensorflow as tf

new_tens = tf.constant([[15, 27, 45], [109, 278, 145], [234, 189, 289]])
new_output = tf.get_static_value(new_tens)
print("Static value:",new_output)

在上面的代码中,我们导入了 TensorFlow 库,然后使用 tf.constant() 函数创建了一个输入张量。之后,我们使用 tf.get_static_value() ,并指定输入张量作为参数。一旦执行了这段代码,输出将显示给定张量的常数值。

下面是以下给定代码的输出。

Solution of module tensorflow attribute get static error

Solution of module TensorFlow attribute get static error

你可能也喜欢阅读下面的 TensorFlow 教程。

在本 Python 教程中,我们学习了如何在 Python TensorFlow 中获取静态值。此外,我们还讨论了以下主题。

  • 张量流获取静态值
  • TensorFlow 获取值的索引
  • TensorFlowget 从 tf 变量中获取值
  • 张量流得到一个常量张量值
  • 模块“TensorFlow”没有属性“获取静态值”

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

TensorFlow 获取变量+示例

原文:https://pythonguides.com/tensorflow-get-variable/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何获取 Python TensorFlow 中的 变量。此外,我们将涵盖以下主题。

  • TensorFlow 通过名称获取变量
  • 张量流获取变量值
  • TensorFlow 获取变量范围
  • TensorFlow 获取变量初始值
  • TensorFlow 获取变量列表

目录

张量流获取变量

  • 在本节中,我们将讨论如何在 Python TensorFlow 中获取变量。
  • 为了执行这个特定的任务,我们将使用TF . compat . v1 . get _ variable()函数,这个函数用于获取带有这些参数的给定变量。
  • 在这个例子中,我们将创建一个简单的变量 'tens' 并分配给TF . compat . v1 . get _ variable()函数,在这个函数中,我们将为它分配 namedtype 参数。

语法:

我们来看一下语法,了解一下 Python TensorFlow 中TF . compat . v1 . get _ variable()函数的工作原理。

tf.compat.v1.get_variable
                         (
                          name,
                          shape=None,
                          dtype=None,
                          initializer=None,
                          regularizer=None,
                          trainable=None,
                          collections=None,
                          caching_devices=None,
                          partitioner=None,
                          validate_shape=true,
                          use_resource=None,
                          custom_getter=None,
                          constraint=None,
                          synchronization=tf.variableSynchronization.AUTO,
                          aggregation=tf.compat.v1.variableAggregation.None
                         )
  • 它由几个参数组成
    • 名称:该参数表示给定变量的名称。
    • 形状:该参数定义了给定或现有变量的形状。
    • dtype: 默认取 tf.float32() 值,存在于给定变量中。
    • 默认情况下,它接受 none 值,并指定它是否可以是一个进程或初始化器。
    • 正则化:该参数用于正则化。
    • 可训练:默认情况下,它不取值,它将检查条件,如果为真,它将给定的变量添加到图形集合中。
    • 集合:它定义了图形集合的列表,默认情况下,它不取值。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取变量。

源代码:

import tensorflow as tf
tens = tf.compat.v1.get_variable(name='tens',shape=[1],dtype=tf.int32)
print(tens)

在下面的代码中,我们导入了 TensorFlow 库,然后创建了一个变量,并在其中分配了函数TF . compat . v1 . get _ variable()。在这个函数中,我们传递了名称、形状和数据类型作为参数。一旦执行了这段代码,输出将显示变量的名称。

下面是下面给出的代码的截图。

TensorFlow get variable in Python

TensorFlow get variable in Python

阅读: TensorFlow Tensor to NumPy

TensorFlow 按名称获取变量

  • 在这个程序中,我们将讨论如何在 Python TensorFlow 中按名称获取变量。
  • 为了完成这项任务,我们将使用TF . compat . v1 . get _ variable()函数,该函数将帮助用户获得带有该参数的给定或现有变量。在这个例子中,我们将只提到名称形状参数。

语法:

下面是TF . compat . v1 . get _ variable()函数的语法

tf.compat.v1.get_variable
                         (
                          name,
                          shape=None,
                          dtype=None,
                          initializer=None,
                          regularizer=None,
                          trainable=None,
                          collections=None,
                          caching_devices=None,
                          partitioner=None,
                          validate_shape=true,
                          use_resource=None,
                          custom_getter=None,
                          constraint=None,
                          synchronization=tf.variableSynchronization.AUTO,
                          aggregation=tf.compat.v1.variableAggregation.None
                         )

举例:

让我们举一个例子,检查如何在 Python TensorFlow 中通过名称获取变量。

源代码:

import tensorflow as tf

with tf.compat.v1.variable_scope("tens1"):
    result = tf.compat.v1.get_variable("tens2", shape=[1])
    print(result)

在上面的代码中,我们已经导入了 TensorFlow 库,然后使用了TF . compat . v1 . get _ variable()函数,在这个函数中,我们分配了变量名和形状参数。

下面是以下给定代码的实现。

TensorFlow get variable by name

TensorFlow get variable by name

阅读:张量流得到形状

TensorFlow 获取变量值

  • 在本节中,我们将讨论如何在 Python TensorFlow 中从变量中获取值。
  • 通过使用 tf。Variable() 函数,我们可以很容易地创建变量并给它赋值。接下来我们将使用TF . compat . v1 . global _ variables _ initializer()函数,这个方法用于初始化一个全局变量。
  • 接下来,我们将创建类似于 tf.compat.v1.session() 的会话,并使用 tf.session() 作为 Val 启动会话,其中 Val 是会话名称。

语法:

让我们看一下语法,了解一下 Python TensorFlow 中的 tf.variable() 函数的工作原理。

tf.variable
           (
            initial_value=None,
            trainable=None,
            validate_shape=True,
            caching_device=None,
            name=None,
            variable_def=None,
            dtype=None,
            import_scope=None,
            constraint=None,
            synchronization=tf.VariableSynchronization.AUTO,
            aggregation=tf.compat.v1.variableAggregation.NONE
           )

举例:

让我们举个例子,看看如何在 Python TensorFlow 中从变量中获取值。

源代码:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
tens = tf.Variable([25, 29])
tens_init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as val:
    val.run(tens_init)
    result=val.run(tens)
    print(result)

下面是以下给定代码的执行。

TensorFlow get variable value in Python

TensorFlow get variable value in Python

正如您在屏幕截图中看到的,输出显示了给定变量的值。

阅读:Python tensor flow reduce _ sum

TensorFlow 获取变量范围

  • 在本期节目中,我们将讨论如何在 Python TensorFlow 中获取变量作用域。
  • 通过使用TF . compat . v1 . variable _ scope()函数,我们可以很容易地得到变量的作用域。在 Python 中,这个函数用于定义声明变量(层)的操作。

语法:

让我们看一下语法,了解一下 Python TensorFlow 中TF . compat . v1 . variable _ scope()函数的工作原理。

tf.compat.v1.variable_scope
                           (
                            name_or_scope,
                            default_name=None,
                            values=None,
                            intializer=None,
                            regularizer=None,
                            caching_device=None,
                            partitioner=None,
                            custom_getter=None,
                            reuse=None,
                            dtype=None,
                            use_resource=None,
                            constraint=None,
                            auxiliary_name_scope=True
                           )

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取变量作用域。

源代码:

import tensorflow as tf

with tf.compat.v1.variable_scope('tens1'):
    result = tf.zeros((), name='tens2')
    print(result)

下面是以下给定代码的输出。

TensorFlow get variable scope in Python

TensorFlow get the variable scope in Python

阅读:Python tensor flow reduce _ mean

TensorFlow 获取变量初始值

  • 本节我们将讨论如何在TF . compat . v1 . get _ variable()函数中使用 initializer 参数。
  • 为了完成这个任务,我们将使用TF . compat . v1 . get _ variable()函数,在这个函数中,我们将把初始化器设置为一个参数
  • 这个初始化器指定了张量或对象,如果它是张量,那么给定的形状 validate_shape 将为假。

语法:

下面是 Python TensorFlow 中TF . compat . v1 . get _ variable()函数的语法。

tf.compat.v1.get_variable
                         (
                          name,
                          shape=None,
                          dtype=None,
                          initializer=None,
                          regularizer=None,
                          trainable=None,
                          collections=None,
                          caching_devices=None,
                          partitioner=None,
                          validate_shape=true,
                          use_resource=None,
                          custom_getter=None,
                          constraint=None,
                          synchronization=tf.variableSynchronization.AUTO,
                          aggregation=tf.compat.v1.variableAggregation.None
                         )

举例:

我们举个例子,检查一下如何在TF . compat . v1 . get _ variable()函数中使用初始化器参数。

源代码:

import tensorflow as tf
import numpy as np

tens=np.random.rand(4,5)
result=tf.compat.v1.get_variable('var_name',initializer=tens)
print(result)

下面是以下给定代码的实现

TensorFlow get variable initializer

TensorFlow get variable initializer

阅读: Python TensorFlow 随机均匀

TensorFlow 获取变量列表

  • 这里我们要讨论的是如何在 Python TensorFlow 中获取变量列表。
  • 为了完成这项任务,我们将使用TF . compat . v1 . get _ collection()函数,该函数用于默认图形。

语法:

下面是TF . compat . v1 . get _ collection()函数的语法。

tf.compat.v1.get_collection
                           (
                            key,
                            scope=None,
                           )
  • 它由几个参数组成
    • Key: 该参数表示集合的 Key。
    • scope: 这是一个可选参数。结果列表被过滤以仅包括元素。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取变量列表。

源代码:

import tensorflow as tf

with tf.compat.v1.variable_scope('my_scope'):
    tens = tf.Variable(0)

print (tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, scope='my_scope'))

在上面的代码中,我们已经导入了 TensorFlow 库,然后使用了TF . compat . v1 . variable _ scope()函数 ('my_scope')

下面是下面给出的代码的截图。

TensorFlow get variable list

TensorFlow get a variable list

你可能也喜欢阅读下面的 TensorFlow 教程。

在本 Python 教程中,我们学习了如何获取 Python TensorFlow 中的 变量。此外,我们还讨论了以下主题。

  • TensorFlow 通过名称获取变量
  • 张量流获取变量值
  • TensorFlow 获取变量范围
  • TensorFlow 获取变量初始值
  • TensorFlow 获取变量列表

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

TensorFlow 全球平均池

原文:https://pythonguides.com/tensorflow-global-average-pooling/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习如何在 Python TensorFlow 中进行全局平均池化。此外,我们将涵盖以下主题。

  • TensorFlow 全球平均池 1d
  • TensorFlow 全球平均池 3d
  • TensorFlow 全球平均池减少 _ 平均
  • 全局平均池层张量流

还有,看看最新的相关教程: Tensorflow 将稀疏张量转换为张量

目录

TensorFlow 全球平均池

  • 在本节中,我们将讨论如何在 Python TensorFlow 中进行全局平均池化。
  • 为了执行这个特定的任务,我们将使用 tf。keras . layers . globalaaveragepooling2d()函数,该函数用于对给定数据进行全局平均池操作。
  • 例如,假设我们有一个高度(h)、宽度和深度维度的输入特征图。当我们将此输入层传递到全局平均池操作中时,它将计算每个单独地图的平均值,并将平均值返回到输出节点。

语法:

让我们看看语法,了解一下 tf 的工作原理。Python TensorFlow 中的 keras . layers . globalaveragepooli2d()

tf.keras.layers.GlobalAveragePooling2D(
    data_format=None, keepdims=False, **kwargs
)
  • 它由几个参数组成
    • data_format: 该参数指定输入通道中尺寸的顺序,默认情况下,它采用 Keras 中的图像 data_format 值。
    • Keepdims: 默认情况下,它取一个 false 值,指定张量的秩被降低,如果为 true,则空间维度保留长度 1。

举例:

让我们举个例子,看看如何在 Python TensorFlow 中进行全局平均池化。

源代码:

import tensorflow as tf
import numpy as np

new_tens = (12,23,45,6)
tens1 = tf.random.normal(new_tens)
tens2 = tf.keras.layers.GlobalAveragePooling2D()(tens1)
print(tens2.shape)
  • 在上面的代码中,我们创建了一个张量,然后使用了 tf.random.normal() 函数,并在函数内部将该张量指定为一个参数。
  • 之后,我们使用了TF . keras . layers . globalavergepooling2d()函数,该函数返回输出节点。

下面是下面给出的代码的截图。

TensorFlow global average pooling

TensorFlow global average pooling

阅读:张量流 clip_by_value

TensorFlow 全球平均池 1d

  • 在这个例子中,我们将讨论如何在 Python TensorFlow 中进行全局平均池 1d。
  • 对于这个执行,我们将使用 tf。keras . layers . globalaveragepooling1d()函数。此函数用于操作时态数据的全局平均池。

语法:

我们先来看看语法,了解一下 Python TensorFlow 中的工作TF . keras . layers . globalaveragepooling1d()

tf.keras.layers.GlobalAveragePooling1D(
    data_format='channels_last', **kwargs
)
  • 它由几个参数组成。
    • data_format:该参数表示输入中尺寸的顺序,默认情况下,它采用与形状输入相对应的‘channels _ last’值。
    • keepdims: 默认情况下,它取一个 false 值,指定张量的秩被降低,如果为 true,则空间维度保留长度 1。

举例:

import tensorflow as tf
import numpy as np

tens_shape = (12, 34, 78)
tens1 = tf.random.normal(tens_shape)
tens2 = tf.keras.layers.GlobalAveragePooling1D()(tens1)
print(tens2.shape)

在下面的代码中,我们使用了 tf。keras . layers . globalaveragepooling1d()函数,该函数将返回输入张量的值。

下面是以下给定代码的实现。

TensorFlow global average pooling 1d

TensorFlow global average pooling 1d

阅读: Tensorflow 嵌入 _ 查找

TensorFlow 全球平均池 3d

  • 在本节中,我们将讨论如何在 Python TensorFlow 中使用TF . keras . layers . averagepool3d函数。
  • 该函数用于操作三维数据的全局平均池,它采用一个带形状的 5D 张量。

语法:

让我们看看语法,了解一下 tf 的工作原理。Python TensorFlow 中的 keras . layers . averagepool3d()函数

tf.keras.layers.GlobalAveragePooling3D(
    data_format=None, keepdims=False, **kwargs
)
  • 它由几个参数组成
    • data_format: 该参数表示输入中尺寸的顺序,默认情况下,它采用“无”值,对应于带形状的输入。
    • Keepdims: 默认情况下,它取一个 false 值,指定张量的秩被降低,如果为 true,则空间维度保留长度 1。

举例:

让我们举个例子,检查一下如何使用 tf。Python TensorFlow 中的 keras . layers . averagepool3d()函数。

源代码:

import tensorflow as tf
import numpy as np

new_dept = 20
new_length = 20
new_width = 20
input_channels = 2

new_input_val = tf.keras.Input(shape=(new_dept, new_length, new_width, input_channels))
layer = tf.keras.layers.AveragePooling3D(pool_size=2)
new_output = layer(new_input_val)
print(new_output)

在上面的代码中,我们已经为 tf 中的平均池步幅创建了高度、宽度和深度值。Keras.Input() 函数,然后我们使用了 tf。keras . averagepool3d()函数并指定给定输入层的尺寸。

下面是以下给定代码的执行。

TensorFlow global average pooling 3d

TensorFlow global average pooling 3d

阅读:张量流乘法-有用指南

TensorFlow 全球平均池减少 _ 平均

  • 这里我们要讨论的是如何在全局平均池张量流中使用 reduce_mean。
  • 如果没有为平均池定义高度和宽度,那么我们也可以使用 tf.reduce_mean() 函数,当您沿着轴【1,2】进行缩减时,它会指定张量的第二维和第一维以及一些过滤器。

语法:

下面是 Python TensorFlow 中 tf.reduce_mean() 函数的语法。

tf.reduce_mean(
    input_tensor,
    axis=None,
    keepdims=None,
    name=None,
    reduction_indices=None,
    keep_dims=None
)
  • 它由几个参数组成
    • input_tensor: 该参数表示我们想要减少的张量,它应该始终是一个数字类型。
    • 轴:默认情况下,它不取值,一旦您在函数中使用它,默认情况下所有维度都将减少。
    • keepdims: 该参数将检查条件,如果为真,则减少秩张量的长度。默认情况下,它采用一个假值。
    • 名称:可选参数,表示操作的名称。

举例:

让我们举个例子,看看如何在全局平均池张量流中使用 reduce_mean

源代码:

import tensorflow as tf

new_tens = (12,23,45,6)
tens1 = tf.random.normal(new_tens)
output = tf.reduce_mean(tens1, [1, 2], name='global_pool') 
print(output) 

在上面的代码中,我们使用了 tf.reduce_mean() 函数,而不是使用高度和宽度。我们使用了【1,2】轴,它指定了第一和第二维度。

下面是以下给定代码的实现。

TensorFlow global average pooling reduce_mean

TensorFlow global average pooling reduce_mean

阅读: TensorFlow 获取变量+示例

全局平均池层张量流

  • 在这个例子中,我们将讨论如何在 Python TensorFlow 中使用平均池层。
  • 为了完成这个任务,我们将使用 tf。keras . layers . average pooling 2d()函数,该函数用于空间数据的平均池化操作。

语法:

下面是 tf 的语法。Python TensorFlow 中的 keras . layers . average pooling 2d()

tf.keras.layers.AveragePooling2D(
    pool_size=(2, 2),
    strides=None,
    padding='valid',
    data_format=None,
    **kwargs
)
  • 它由几个参数组成
    • pool_size: 该参数指定池的大小,必须是 (2,2) 和两个空间维度输入的整数。
    • 步幅:默认情况下,它采用 none 值,并指定步幅值。
    • 填充:默认情况下,它采用‘有效’,这意味着没有填充,如果该值为‘相同’,则导致在输入的右侧/左侧均匀填充。
    • data_format: 该参数表示输入中尺寸的排序,默认情况下,取与形状输入相对应的‘无’值。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中使用平均池层。

源代码:

import tensorflow as tf

new_tens = tf.constant([[2., 2., 1.],
                 [6., 7., 2.],
                 [1., 2., 5.]])
new_tens = tf.reshape(new_tens, [1, 3, 3, 1])
new_result_avg = tf.keras.layers.AveragePooling2D(pool_size=(2, 2),
   strides=(1, 1))
new_result_avg(new_tens)

下面是以下给定代码的输出。

global average pooling layer TensorFlow

global average pooling layer TensorFlow

你可能也喜欢读下面的张量流。

在这个 Python 教程中, 我们学习了如何在 Python TensorFlow 中进行全局平均池化。此外,我们还讨论了以下主题。

  • TensorFlow 全球平均池 1d
  • TensorFlow 全球平均池 3d
  • TensorFlow 全球平均池减少 _ 平均
  • 全局平均池层张量流

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流图——详细指南

原文:https://pythonguides.com/tensorflow-graph/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何在 Python TensorFlow 中制作图形。此外,我们将涵盖以下主题。

  • 张量流图与渴望
  • 张量流图和会话
  • Tensorflow graph to keras model
  • 带回路的张量流图
  • 默认为图形的张量流
  • 张量流图 _ 替换
  • 张量流没有属性' reset_default_graph '
  • Tensorflow graph input name
  • tensor flow graph . get _ operation _ by _ name
  • 张量流图并行化
  • 张量流图所有变量
  • Tensorflow add_graph
  • 张量流分裂张量
  • 张量流图形最终确定
  • 张量流图获取所有张量名称
  • 张量流获取输入和输出
  • 张量流获取输入形状
  • 张量流获取权重
  • 张量流获取操作
  • TensorFlow get layers
  • TensorFlow graph list

目录

Python 张量流图

  • Python TensorFlow 中,图指定了节点和一条边,而节点以更多的张量作为输入,生成给定的张量作为输出。
  • 边缘被表示为张量,并且它将生成新的张量,并且它总是依赖于单独的操作。
  • 如果我们在 Tensorflow 中举一个例子,那么图就是这个例子的主干,简单地说,我们可以说图是定义模型中操作的节点的组合。
  • 张量流图类似于存储一组张量流操作对象的数据结构,这些对象指示计算单位,其中对象将是指定数据单位的张量。

举例:

现在让我们看看这个例子,并检查如何在 Python TensorFlow 中创建和执行一个图形。

源代码:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
var1 = 5
var2 = 8
result= tf.add(var1, var2, name='Add')
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

在下面给出的代码中,我们导入了 tensorflow 库和TF . compat . v1 . disable _ eager _ execution()函数来运行会话。

创建变量后,我们使用了基本的操作方法来显示图形,即 tf.add() 函数,在该函数中,我们用‘名称’参数为变量赋值。

下面是下面给出的代码的截图。

Python TensorFlow Graph

Python TensorFlow Graph

阅读: TensorFlow Tensor to NumPy

张量流图 vs 渴望

  • 在这个程序中,我们将讨论 Python TensorFlow 中图形和急切执行的区别。
  • 在 Python TensorFlow 中,急切执行会准备好模型,并执行操作以添加到图表中。而在图形的情况下,它表示计算的数据流。

举例:

让我们举个例子,检查一下 Python TensorFlow 中的图和急切执行之间的区别。

源代码:

import tensorflow as tf

def eager_function(y):
  new_output = y ** 2
  print(new_output)
  return new_output

y = tf.constant([13, 16, 18, 19, 21])

eager_function(y)

new_graph = tf.Graph()
with new_graph.as_default():
  result = tf.constant(16)
  print(result)

在上面的代码中,我们导入了 TensorFlow 库,然后定义了 eager_function() ,在这个函数中,我们使用了 ** 运算符并返回值。

下面是以下给定代码的实现。

TensorFlow graph vs eager

TensorFlow graph vs eager

阅读:张量流得到形状

张量流图和时段

  • 在本节中,我们将讨论如何在 Python TensorFlow 图中使用会话。
  • 为了执行这个特定的任务,我们将使用TF . compat . v1 . disable _ eager _ execution()函数,这个函数将创建会话。
  • 接下来,我们将通过使用 tf.math.multiply() 方法来声明变量和操作函数,在这个函数中,我们已经将变量和名称数据类型指定为参数。
  • 为了创建一个会话,我们将使用 tf.compat.v1.session() ,为了运行会话,我们将使用 val.run()

举例:

让我们举个例子,看看如何在 Python TensorFlow 图中使用会话。

源代码:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
x = 6
y = 7
result= tf.math.multiply(x, y, name='mult')
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

在下面给定的代码中,我们导入了 TensorFlow 库,然后为操作符值创建了变量。之后,我们已经使用了 tf。math.multiply() 函数,在这个函数中,我们传递了带有 name 参数的 xy 变量。运行会话后,输出将显示该值。

下面是下面给出的代码的截图。

TensorFlow graph and session

TensorFlow graph and session

阅读:Python tensor flow reduce _ sum

带回路的张量流图

  • 在本节中,我们将讨论如何在 Python TensorFlow 图中使用循环。
  • 为了执行这个特定的任务,我们将使用 tf.while_loop() 函数,这个函数将检查条件,如果为真,那么它将重复主体。

语法:

让我们看一下语法,了解一下 Python TensorFlow 中的 tf.while_loop() 函数的工作原理。

tf.while_loop
             (
              cond,
              body,
              loop_vars,
              shape_invariants=None,
              parallel_iterations=10,
              back_prop=True,
              swap_memory=False,
              maximum_iterations=None,
              name=None
             )
  • 它由几个参数组成
    • cond: 该参数表示循环的执行条件。
    • 主体:该参数指定循环主体。
    • loop_vars: 这是一个张量对象和 numpy 数组的列表。
    • shape_invariants: 默认情况下,它不取值,并指定变量的形状。
    • Parallel_iterations: 默认取 10 值,必须是正整数。
    • back_prop: 可选参数,支持反向传播。
    • 名称:该参数表示操作的名称。

举例:

让我们举个例子,检查一下如何在 Python TensorFlow Graph 中使用循环。

源代码:

import tensorflow as tf

tens = tf.constant(20)
tens1 = lambda tens: tf.less(tens, 10)
tens2 = lambda tens: (tf.add(tens, 1), )
result = tf.while_loop(tens1, tens2, [tens])
print(result)

在下面的代码中,我们导入了 TensorFlow 库,然后使用 tf.constant() 函数声明了一个变量。之后,我们使用了 tf.while_loop() 函数,在这个函数中,我们传递了十进制的函数。一旦执行了这段代码,输出将显示 numpy 数组。

下面是以下给定代码的执行。

TensorFlow graph with loop

TensorFlow graph with loop

阅读:Python tensor flow reduce _ mean

张量流图 _ 替换

  • 在本节中,我们将讨论如何在 Python TensorFlow 中替换图形。
  • 为了执行这个特定的任务,首先,我们将定义 build() 函数,在这个函数中,我们使用了 tf.placeholder() 函数来创建张量,并在 tf.add() 函数中提到了张量。
  • 接下来,我们将使用 tf.get_default_graph() 函数,该函数将返回默认的图形会话,然后我们将使用 ge.graph_replace() 函数。

语法:

下面是 Python TensorFlow 中TF . compat . v1 . get _ default _ graph()函数的语法。

tf.compat.v1.get_default_graph()

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中替换图形。

源代码:

 import tensorflow as tf
import tensorflow.contrib.graph_editor as ge
tf.compat.v1.disable_eager_execution()
def build():
    tens1 = tf.placeholder(dtype=tf.int32)
    tens2 = tf.placeholder(dtype=tf.int32)
    result= tf.add(tens1, tens2)

build() 

new_result1 = tf.constant(2.0, shape=[2, 3])
new_result2 = tf.constant(4.0, shape=[2, 3])

tens1 = tf.get_default_graph().get_tensor_by_name("a:0")
tens2 = tf.get_default_graph().get_tensor_by_name("b:0")
result = tf.get_default_graph().get_tensor_by_name("c:0")

new_output = ge.graph_replace(result, {tens1: new_result1, tens2: new_result2})

with tf.compat.v1.Session() as sess:

    print(sess.run(new_output))

在上面的代码中,我们导入了 tensor flow . contrib . graph _ editor 作为 get 来替换图形,然后我们定义了函数 build() ,在这个函数中,我们使用 tf.placeholder() 函数分配了张量。

之后,我们使用了 ge.graph_replace() 函数,在这个函数中,我们传递了带有值的张量作为参数。一旦执行了这段代码,输出就会显示值。

下面是以下给定代码的执行。

TensorFlow graph_replace in Python

TensorFlow graph_replace in Python

阅读: Python TensorFlow 随机均匀

张量流没有属性‘重置 _ 默认 _ 图形’

  • 在本程序中,我们将讨论 Python TensorFlow 中的错误 TensorFlow 没有属性‘reset _ default _ graph’
  • 基本上,当 tf.reset_default_graph() 函数在最新版本的 TensorFlow 中不可用时,就会出现此错误声明。

举例:

在这个例子中,我们刚刚使用了 tf.reset_default_graph() 函数。

TensorFlow has no attribute reset_default_graph

TensorFlow has no attribute reset_default_graph

注意:如果你在 Tensorflow 中使用的是 1.x 版本,那么这个函数将很容易在例子中工作。

现在让我们来看看这个错误的解决方案。

解决方案:

为了执行这个特定的任务,我们将使用更新的函数TF . compat . v1 . reset _ default _ graph()。此功能仅在最新版本 2.8x 中有效

源代码:

import tensorflow as tf

result=tf.compat.v1.reset_default_graph()
print(result)

下面是以下给定代码的实现。

Solution of TensorFlow has no attribute reset_default_graph

Solution of TensorFlow has no attribute reset_default_graph

阅读: Python TensorFlow one_hot

张量流图所有变量

  • 在这个程序中,我们将讨论如何获取张量流图中的所有变量。
  • 为了完成这个任务,首先,我们将通过使用 tf.constant()tf.variable() 函数来操作一些操作,在这个函数中,我们将分配值和 name 参数。
  • 接下来,为了获取所有变量,我们将使用TF . compat . v1 . get _ default _ graph()函数,该函数将帮助用户从图中返回变量名。

语法:

我们先来看看语法,了解一下TF . compat . v1 . get _ default _ graph()函数在 Python TensorFlow 中的工作原理。

tf.compat.v1.get_default_graph()

举例:

我们举个例子,检查一下如何得到张量流图中的所有变量。

源代码:

import tensorflow as tf

tens1 = tf.constant(2.6, name='const_tens1')
tens2 = tf.Variable(4.8, name='variable_tens2')
tens3 = tf.add(tens1, tens2, name='new_add')
tens4 = tf.multiply(tens3, tens1, name='new_mult')

for new_op in tf.compat.v1.get_default_graph().get_operations():
    print(str(new_op.name))

在下面给定的代码中,我们导入了 TensorFlow 库,并使用 tf.constant()tf.variable() 函数创建了一个变量,用于从 TensorFlow 中获取所有变量。

下面是以下代码的截图

TensorFlow graph all variables

TensorFlow graph all variables

阅读:Python tensor flow expand _ dims

TensorFlow 获取输入形状

  • 在本节中,我们将讨论如何在 Python TensorFlow 中获取输入形状。
  • 为了完成这项任务,我们将使用 cifar10() load dataset 从张量中获取输入形状。
  • 在 Python TensorFlow 中,该方法用于加载 CIFAR10 数据集。

语法:

下面是 tf 的语法。keras . datasets . cifar 10 . load _ data()

tf.keras.datasets.cifar10.load_data()

举例:

我们举个例子,检查一下如何在 TensorFlow 中获取输入形状。

源代码:

import tensorflow as tf
import keras
from keras.models import Sequential
from keras.datasets import cifar10

new_dt = cifar10.load_data()

(input_train, target_train), (input_test, target_test) = new_dt
print("Input shape of trainning data:",input_train.shape)
print("Input shape of testing data:",input_test.shape)

在上面的代码中,我们通过使用 Keras.datasets() 库导入了 cifar10 模块,然后我们使用了 input _traininput_test 图像数据。一旦执行了这段代码,输出将显示输入名称

下面是以下给定代码的执行。

TensorFlow get input shape in Python

TensorFlow get input shape in Python

阅读: TensorFlow 稀疏张量+例题

TensorFlow 获取权重

  • 在本节中,我们将讨论如何在 Python Tensorflow 中获取权重。
  • 为了执行这个特定的任务,我们将使用 tf.keras.layers.Dense() 函数的概念,在这个函数中,我们将把激活值传递给它。

语法:

让我们看看语法,了解一下 tf 的工作原理。Keras.layers.Dense() 函数。

tf.keras.layers.Dense
                     (
                      units,
                      activation=None,
                      use_bias=true,
                      kernel_initializer='glorat_uniform',
                      bias_intializer='zeros',
                      kernel_regularizer=None,
                      bias_regularizer=None,
                      activity_regularizer=None,
                      kernel_constraint=None,
                      bias_constraint=None
                     )
  • 它由几个参数组成
    • 单位:该参数表示输出形状的给定尺寸。
    • 激活:该参数指定如果不提及该值,则不应用激活。
    • use_bias: 默认情况下,它采用真值,并指定偏差向量。
    • Kernel _ initializer:它定义了内核权重矩阵,默认情况下采用“glorat_uniform”。
    • bias _ regulator:该参数表示偏置向量。
    • activity_regulaeizer: 该参数指定给定层的输出。
    • kernel_constraint: 默认情况下,它不取值,并指定矩阵的权重。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取权重。

源代码:

import tensorflow as tf

new_model = tf.keras.Sequential([
        tf.keras.layers.Dense(2, activation="relu"),
        tf.keras.layers.Dense(3, activation="tanh"),
        tf.keras.layers.Dense(4),
])
new_input = tf.random.normal((2,3))
output = new_model(new_input)
print(new_model.layers[0].weights)

在下面给定的代码中,我们导入了 TensorFlow 库,然后使用了 tf。Keras.layers.Dense() 函数,在这个函数中,我们将激活值赋值为‘relu’‘tanh’

之后,我们应用了 tf.random.normal() 函数,在这个函数中我们提到了值的形状。

下面是以下给定代码的实现。

Python TensorFlow get weights

Python TensorFlow get weights

阅读: Python TensorFlow 截断法线

张量流获取操作

  • 在本节中,我们将讨论如何在张量流图中定义运算。
  • 为了完成这项任务,我们将使用 tf.math.divide() 操作,并从给定的张量中获取值。

语法:

下面是 Python TensorFlow 中 tf.math.divide() 函数的语法。

tf.math.divide
              (
               x,
               y,
               name=None
              )
  • 它由几个参数组成
    • x: 该参数表示输入张量。
    • 名称:该参数指定操作的名称。

举例:

我们举个例子,检查一下如何在张量中使用 tf.math.divide() 运算。

源代码:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
tens1 = 6
tens2 = 7
result= tf.math.divide(tens1, tens2, name='divide')
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

在下面给定的代码中,我们使用了 tf.math.divide() 函数,在这个函数中,我们将张量指定为一个参数。之后,我们使用了 tf.compat.v1.Session() 函数来运行会话。

下面是以下给定代码的执行。

Python TensorFlow get operation

Python TensorFlow get operation

阅读:将列表转换为张量张量流

TensorFlow get layers

  • 在本节中,我们将讨论如何在 Python TensorFlow 中获取图层。
  • 为了执行这个特定的任务,我们将使用 tf.keras.layers.Dense() 函数,在这个函数中,我们将把激活值传递给它。

语法:

下面是 tf 的语法。Python 中的 Keras.layers.Dense() 函数。

tf.keras.layers.Dense
                     (
                      units,
                      activation=None,
                      use_bias=true,
                      kernel_initializer='glorat_uniform',
                      bias_intializer='zeros',
                      kernel_regularizer=None,
                      bias_regularizer=None,
                      activity_regularizer=None,
                      kernel_constraint=None,
                      bias_constraint=None
                     )
  • 它由几个参数组成
    • 单位:该参数表示输出形状的给定尺寸。
    • 激活:该参数指定如果不提及该值,则不应用激活。
    • use_bias: 默认情况下,它采用真值,并指定偏差向量。
    • Kernel _ initializer:它定义了内核权重矩阵,默认情况下采用“glorat_uniform”。
    • bias _ regulator:该参数表示偏置向量。
    • activity_regulaeizer: 该参数指定给定层的输出。
    • kernel_constraint: 默认情况下,它不取值,并指定矩阵的权重。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取图层。

源代码:

import numpy
import tensorflow as tf

new_val = numpy.array([[[4., 5., 6.], [16., 25., 31.]], [[28., 99., 16.], [25., 81., 55.]]])

tens1 =  3
tens2 = 2
model = tf.keras.Sequential([
    tf.keras.layers.Dense(tens2 * tens1, input_shape=(tens2, tens1), activation='relu'),
    tf.keras.layers.Dense(45, input_shape=(tens2, tens1), activation='sigmoid'),
    tf.keras.layers.GlobalAveragePooling1D(),
    tf.keras.layers.Dense(3, input_shape=(0, 1), activation='softmax')
])

model.build(input_shape=(tens2, tens1))

result=model(new_val)
print(result)

在下面给定的代码中,我们使用 numpy.array() 函数创建了一个数组,然后声明了两个指定输入形状的变量。

之后,我们已经应用了 tf。Keras.layers.Dense() 函数,在这个函数中,我们将给定的张量相乘,并将激活值设置为 relu

下面是下面给出的代码的截图。

TensorFlow get layers in Python

TensorFlow get layers in Python

正如您在屏幕截图中看到的,输出显示了顺序层。

阅读: Tensorflow 迭代张量

TensorFlow graph list

  • 在本节中,我们将讨论如何在 Python TensorFlow 中获取图列表。
  • 为了执行这个特定的任务,我们将使用TF . compat . v1 . get _ default _ graph()函数,这个函数用于返回输出张量中的图形。

语法:

下面是 Python TensorFlow 中TF . compat . v1 . get _ default _ graph()函数的语法。

tf.compat.v1.get_default_graph()

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取图列表。

源代码:

import tensorflow as tf

new_tens = tf.Variable(3)
new_tens2 = tf.Variable(8)
new_tens3 = tf.Variable(2)
result = (new_tens + new_tens2) * new_tens3

for result in tf.compat.v1.get_default_graph().get_operations():
    print (result.name)

在下面给出的代码中,我们已经导入了 TensorFlow 库,然后使用 tf.variable() 函数创建了操作。之后,我们使用了TF . compat . v1 . get _ default _ graph()函数并将结果变量存储为参数。

你可以参考下面的截图。

TensorFlow graph list in Python

TensorFlow graph list in Python

阅读:梯度下降优化器张量流

张量流分裂张量

  • 在本节中,我们将讨论如何在 Python TensorFlow 中拆分张量。
  • 为了执行这个特定的任务,我们将使用 tf.split() 函数,这个函数用于将一个张量值划分为一个子张量。

语法:

让我们看一下语法并理解 Python 中的 tf.split() 函数的工作原理。

tf.split
        (
         value,
         num_or_size_splits,
         axis=0,
         num=None,
         name='split'
        )
  • 它由几个参数组成
    • 值:该参数表示我们要分割的张量。
    • 数量或尺寸分割:该参数指定沿轴的分割数量。
    • 轴:默认取 0 值,定义维度,范围为 [- rank(value),rank(value))
    • name: 可选参数,指定操作的名称。

举例:

让我们举一个例子,检查如何在 Python TensorFlow 中拆分张量。

源代码:

import tensorflow as tf

tensor = tf.Variable(tf.random.uniform([6, 30], -1, 1))

result = tf.split(tensor,2,1)
tf.shape(result).numpy()

在上面的代码中,我们导入了 TensorFlow 库,然后使用了 tf.variable() 函数,在这个函数中,我们提到了 tf.random.uniform() 函数,然后使用了 tf.split() 函数,它将拆分张量。

下面是下面给出的代码的截图。

TensorFlow split tensor in Python

TensorFlow split tensor in Python

TensorFlow 获取输入和输出

  • 在本节中,我们将讨论如何在 Python TensorFlow 中获取输入和输出张量的名称。
  • 为了执行这个特定的任务,我们将使用 tf.keras.layers.Dense() 函数,在这个函数中,我们将设置激活和输入张量值。
  • 接下来,我们将使用 tf.keras.model() 函数,该函数将帮助用户获得输入张量的输入和输出名称。

语法:

让我们看看语法,了解一下 tf 的工作原理。Keras.model() 函数。

tf.Keras.model
              (
               *args,
               **kwargs
              )

举例:

import tensorflow as tf

new_input = tf.keras.layers.Input(shape=(3000,))
tensor = tf.keras.layers.Dense(324, activation="relu")(new_input)
new_output = tf.keras.layers.Dense(20, activation="sigmoid")(tensor)
model = tf.keras.Model(inputs=new_input, outputs=new_output)
print('new_input_tensor:', new_input.name)
print('new_output_tensor:', new_output.name)

在这个例子中,我们已经导入了 TensorFlow 库,然后使用了 tf。Keras.layers.Input() 函数,在这个函数中,我们已经分配了激活和输入张量值。

下面是以下给定代码的执行。

TensorFlow get input and output

TensorFlow get input and output

tensor flow graph . get _ operation _ by _ name

  • 本节我们将讨论如何在 Python TensorFlow 中使用 get_operation_by_name() 函数。
  • 为了完成这个任务,我们首先将使用 new_graph.as_default() 函数定义一个函数‘get _ graph’,在这个函数中,我们将把 tf.constant() 函数指定为一个操作符。
  • 接下来,我们将使用 tf.session() 函数来运行会话,并分配sess . graph . get _ operation _ by _ name()方法。

注意:在给定的例子中,我们使用了张量流 1。x 版本。

语法:

下面是 TF . get _ operation _ by _name()函数的语法。

tf.get_operation_by_name()

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中使用 get_operation_by_name() 函数。

源代码:

import tensorflow as tf

def get_graph():
  new_graph = tf.Graph()
  with new_graph.as_default():
    tens = tf.constant(7.0, name='tensor')
  return new_graph, tens 

if __name__ == '__main__':
  new_graph, tens = get_graph()
  with tf.Session(graph=new_graph) as sess:
    print(sess.run(tens))
    a = sess.graph.get_operation_by_name('tensor')
    print(sess.run(tens))

下面是以下给定代码的实现。

TensorFlow graph get_operation_by_name

TensorFlow graph get_operation_by_name

张量流图并行化

  • 在本节中,我们将讨论如何在 Python TensorFlow 中并行化 TensorFlow。
  • 为了执行这个特定的任务,我们将使用 tf.parallel_stack() 函数,这个函数将帮助用户将一个等级列表堆叠成一个等级。

语法:

下面是 Python TensorFlow 中 tf.parallel_stack() 函数的语法。

tf.parallel_stack
                 (
                  values,
                  name='parallel_stack'
                 )
  • 它由几个参数组成。
    • 值:该参数表示输入张量列表以及给定的形状和数据类型。
    • name: 默认取 parallel_stack 参数,可选参数,定义操作名称。

示例:

让我们举个例子,看看如何在 TensorFlow Python 中并行化一个 Tensor i。

源代码:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

tens1 = tf.constant([16, 27])
tens2 = tf.constant([34, 56])
tens3 = tf.constant([98, 77])
result=tf.parallel_stack([tens1, tens2, tens3])
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

在上面的代码中,我们导入了 TensorFlow 库,然后通过使用 tf.constant() 函数创建了张量,然后使用了 tf.parallel_stack() 函数,在这个函数中,我们将张量作为参数传递。

之后,我们通过使用 tf.compat.v1.Session() 函数创建了一个会话,并将‘result’变量指定为参数,一旦您执行此代码,输出将显示并行化的值。

下面是以下给定代码的实现。

TensorFlow graph parallelization

TensorFlow graph parallelization

TensorFlow 将图形写到 tensorboard

  • 在本节中,我们将讨论如何在 Python TensorFlow 中向 tensorboard 写一个图。
  • 为了完成这个任务,我们将使用TF . compat . v1 . get _ default _ graph()函数来定义图形。
  • 接下来,我们将把文件模式下的 graphpb.txt() 文件应用为 f.write(graphpb_txt) 。一旦执行了这段代码,输出将显示随机值。

举例:

我们举个例子,检查一下如何用 Python TensorFlow 写一个图到 tensorboard。

源代码:

import tensorflow as tf

graph_def = tf.compat.v1.get_default_graph().as_graph_def()
graphpb_txt = str(graph_def)
with open('graphpb.txt', 'w') as f: f.write(graphpb_txt)
print(graphpb_txt)

下面是以下给定代码的实现。

TensorFlow write graph to tensorboard

TensorFlow write graph to tensorboard

Tensorflow add_graph

  • 在本节中,我们将讨论如何在 Python TensorFlow 中添加图表。
  • 为了执行这个特定的任务,我们将使用TF . summary . create _ file _ writer()函数,这个函数用于声明一个摘要文件编写器。

语法:

让我们看一下语法,了解一下 Python TensorFlow 中TF . summary . create _ file _ writer()函数的工作原理。

tf.summary.create_file_writer
                             (
                              logdir,
                              max_queue=None,
                              flush_millis=None,
                              filename_suffix=None,
                              name=None,
                              experimental_trackable=False,
                             )
  • 它由几个参数组成。
    • logdir: 这个参数表示我们可以轻松写入文件的目录。
    • max_queue: 默认情况下,它采用 none 值,并指定要保留在队列中的摘要的最大值。
    • flush_millis: 默认情况下,它采用 120,000 的值,它定义了两次刷新之间的最大间隔。
    • filename_suffix :可选参数,默认取. v2 值,定义事件文件名。
    • 名称:该参数表示操作的名称。
    • experimental _ tractable:默认情况下,它接受 false 值,并将返回可跟踪的资源。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中添加图形。

源代码:

import tensorflow as tf
import numpy as np

new_tens = tf.summary.create_file_writer("/tmp/tf2_summary_example")
for step in range(20):
  result = np.random.normal(loc=step, scale=1, size=[100])
  with new_tens.as_default(step=step):
    print(tf.summary.histogram(name='distribution', data=result))

在下面给定的代码中,我们导入了 TensorFlow 和 numpy 库,然后使用函数TF . summary . create _ file _ writer()并在该函数中附加了示例摘要文件。

之后,我们使用了 for 循环方法,在该方法中,我们应用了 np.random.normal() 函数,并且在该函数中,我们指定了大小和比例值。

下面是以下给定代码的实现。

TensorFlow add_graph in Python

TensorFlow add_graph in Python

Tensorflow graph input name

  • 在本节中,我们将讨论如何用 Python 从 TensorFlow 图中获取输入名称。
  • 为了执行这个特定的任务,我们将使用 tf.keras.layers.Dense() 函数,在这个函数中,我们将设置激活和输入张量值。
  • 接下来,我们将使用 tf.keras.model() 函数,该函数将帮助用户获得输入张量的输入和输出名称。

举例:

import tensorflow as tf

new_tensor = tf.keras.layers.Input(shape=(2000,))
tensor = tf.keras.layers.Dense(324, activation="relu")(new_tensor)
new_output = tf.keras.layers.Dense(20, activation="sigmoid")(tensor)
model = tf.keras.Model(inputs=new_tensor, outputs=new_output)
print('new_input_tensor:', new_tensor.name)

下面是以下给定代码的实现。

Tensorflow graph input name

Tensorflow graph input name

所以,在这个 Python 教程中,我们学习了如何在 Python TensorFlow 中制作图形。此外,我们还讨论了以下主题。

  • 张量流图与渴望
  • 张量流图和会话
  • Tensorflow graph to keras model
  • 带回路的张量流图
  • 默认为图形的张量流
  • 张量流图 _ 替换
  • 张量流没有属性' reset_default_graph '
  • Tensorflow graph input name
  • tensor flow graph . get _ operation _ by _ name
  • 张量流图并行化
  • 张量流图所有变量
  • Tensorflow add_graph
  • 张量流分裂张量
  • 张量流图形最终确定
  • 张量流图获取所有张量名称
  • 张量流获取输入和输出
  • 张量流获取输入形状
  • 张量流获取权重
  • 张量流获取操作
  • TensorFlow get layers
  • TensorFlow graph list

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流在张量上迭代

原文:https://pythonguides.com/tensorflow-iterate-over-tensor/

Python & Machine Learning training courses

在本 Python 教程中,我们将使用 Python 中的一些例子来研究如何在 Python TensorFlow 中迭代张量。此外,我们还将涉及这些主题。

  • 张量流在张量上迭代
  • 不允许在 tf.tensor 上进行 TensorFlow 迭代
  • TensorFlow 无法在标量张量上迭代

目录

Python TensorFlow 迭代张量

  • 在本节中,我们将讨论如何在 Python TensorFlow 中迭代张量。
  • 要在 Python 中迭代张量,我们可以很容易地使用 for 循环方法,它将直接迭代张量。
  • 迭代张量定义了我们必须打印一个新的线张量,并且它将返回张量中元素的数量。这个方法实际上会迭代张量中的每个值,并显示在屏幕上。
  • 为了完成这个任务,首先,我们将使用 tf.constant() 函数创建一个张量。

语法:

下面是 Python TensorFlow 中 tf.constant() 函数的语法。

tf.constant
           (
            value,
            dtype=None,
            shape=None,
            name='Const'
           )
  • 它由几个参数组成
    • value: 该参数表示常数值,必须是数组形状。
    • dtype :默认情况下,它取 none 值,指定元素的类型。
    • shape: 这是一个可选参数,表示张量的维数。
    • name: 该参数表示操作的名称,默认情况下取“Const”。

举例:

让我们举个例子,看看如何在 Python TensorFlow 中迭代张量。

源代码:

import tensorflow as tf

tensor=tf.constant([16,27,78,99,189])
for tensor in tensor:
    print("Iterate tensor:",tensor)

在上面的代码中,我们首先导入了 TensorFlow 库,然后使用 tf.constant() 函数来创建一个张量,在这个函数中,我们指定了整数值。

创建张量后,我们使用 for 循环方法直接迭代张量。一旦执行了这段代码,输出将显示元素张量。

下面是下面给出的代码的截图。

Python TensorFlow iterate over Tensor

Python TensorFlow iterate over Tensor

例 2: 通过使用 tf.data.iterator() 方法

在 Python 中,这个函数被定义为通过使用 for 循环方法来迭代数据。

让我们看看这个例子,了解一下 Python TensorFlow 中的 tf.data.iterator() 函数的工作原理

源代码:

import tensorflow as tf

tensor = tf.data.Dataset.range(4)
for z in tensor:
  print("Iterate tensor:",z)

在下面给定的代码中,我们使用了 tf.data.Dataset.range() 函数来创建张量,在该函数中,我们设置了范围值 4 ,它指示了输出中显示的张量的迭代次数。

下面是以下给定代码的输出。

TensorFlow iterate over Tensor in Python

TensorFlow iterate over Tensor in Python

正如你在截图中看到的,输出显示迭代张量。

阅读: TensorFlow Tensor to numpy

不允许在 tf.tensor 上进行 TensorFlow 迭代

这里我们要讨论的是错误“ TensorFlow 迭代 tf.tensor()在 Python 中是不允许的”。基本上,这个错误声明是因为我们使用了列表理解方法,而这个方法在图形执行中不受支持。

举例:

import tensorflow as tf

tens = tf.random.uniform(shape=(2,50, 60, 400))
result = tf.shape(tens)
tens = [tens[0][m][n] - tf.reduce_mean(tens[0][m][n]) for n in tf.range(result[2]) for m in tf.range(result[1])]

在上面的代码中,我们已经导入了 TensorFlow 库,然后使用了 tf.random.uniform() 函数。在这个函数中,我们描述了随机形状。之后,我们使用了列表理解方法,并使用了 for 循环和 tf.reduce_mean() 函数。

下面是以下给定代码的执行。

TensorFlow iterating over tf.tensor is not allowed

TensorFlow iterating over tf.tensor is not allowed

正如您在截图中看到的,输出显示在图形执行中不允许使用 tf.tensor()

让我们来看看这个错误的解决方案。

import tensorflow as tf

tens = tf.random.uniform(shape=(2,50, 60, 400))
result = tf.shape(tens)
tens = tens - tf.expand_dims(tf.reduce_mean(tens, axis=3), -1)
print(tens)

在上面的例子中,我们使用了 tf.expand_dims() 函数来代替列表理解方法,并且在这个函数中,我们分配了 tf.reduce_mean() 函数。一旦执行了这段代码,输出将显示张量的形状。

下面是以下给定代码的输出。

TensorFlow iterating over tf.tensor is not allowed

TensorFlow iterating over tf.tensor is not allowed

阅读:模块“张量流”没有属性“会话”

TensorFlow 无法迭代标量张量

在本节中,我们将讨论 Python 中的错误“tensor flow 无法在 scaler“tensor”上迭代 。基本上,当我们在 tf.constant() 函数中使用了 scaler 值来创建张量时,就会出现这个错误声明。

举例:

import tensorflow as tf

tensor=tf.constant(1)
for tensor in tensor:
    print("Iterate tensor:",tensor)

在上面的代码中,我们导入了 TensorFlow 库,然后使用了 tf.constant() 函数,在这个函数中,我们将【T2 1】设置为一个标量值,然后使用 for 循环方法迭代一个张量。

下面是下面给出的代码的截图。

TensorFlow cannot iterate over a scaler tensor

TensorFlow cannot iterate over a scaler tensor

正如您在屏幕截图中看到的,输出显示无法在标量张量上迭代。

让我们来看看这个错误的解决方案。

举例:

import tensorflow as tf

tensor=tf.constant([27,34,67,89])
for tensor in tensor:
    print("Iterate tensor:",tensor) 

在下面给定的代码中,我们导入了 TensorFlow 库,然后使用 tf.constant() 函数来创建张量,在这个函数中,我们在 list 中赋值并迭代张量。

下面是以下给定代码的实现

TensorFlow cannot iterate over a scaler tensor in Python

TensorFlow cannot iterate over a scaler tensor in Python

你可能也喜欢阅读下面的 TensorFlow 教程。

在这个 Python 教程中,我们已经学习了如何使用 Python 中的一些例子在 Python TensorFlow 中迭代张量。此外,我们已经讨论了这些主题。

  • 张量流在张量上迭代
  • 不允许在 tf.tensor 上进行 TensorFlow 迭代
  • TensorFlow 无法在标量张量上迭代

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

TensorFlow 学习率计划程序

原文:https://pythonguides.com/tensorflow-learning-rate-scheduler/

Python & Machine Learning training courses

本 Python 教程将重点介绍使用 TensorFlow 的机器学习模型的学习率计划。此外,我们将看一些如何在 TensorFlow 中学习学习率计划的例子。我们将讨论这些话题。

  • TensorFlow 学习率计划程序
  • TensorFlow 学习率计划程序 adam
  • TensorFlow 学习率计划程序余弦
  • TensorFlow 获取学习率
  • 张量流自适应学习速率

目录

TensorFlow 学习率调度器

  • 在 Keras API 中,其中一个回调被称为 learning rate scheduler(tensor flow)。回调是那些基于每个单独回调的服务,在训练期间的特定点被调用。
  • 每次我们训练我们的神经网络完成各自的职责时,都会调用这些回调。在我们的示例中,LearningRateScheduler 回调从我们在训练之前预先定义的 schedule 函数中接收更新后的学习率值,以及当前时期和当前学习率,并将修改后的学习率应用于优化器。
  • 学习率计划的目标是在整个培训过程中按照预定义的计划降低学习率。学习率计划包括四种类型
    • 恒定学习率:Keras 中 SGD 优化器的默认学习率计划是恒定学习率。动量和衰减率的默认设置为零。选择合适的学习速度是困难的。Lr=0.1 这可以作为我们测试各种学习率策略的起点。
    • 基于时间的衰减:基于时间的衰减公式是 lr = lr0/(1+kt) 这里 lr 和 k 是超参数,t 是迭代次数。当衰减为零时,学习率不受此影响。当衰减被设置时,来自前一时期的学习率将减少所提供的固定量。
    • 步长衰减:这是一个流行的学习速率表,它指定了训练过程中的次数,其中 epoch 是当前的 epoch 数,drop rate 是学习速率每次改变时修改的量,initial lr 是初始学习速率,例如 0.01,initial lr 是初始学习速率,epochs drop 是改变学习速率的频率,例如 10 个 epoch。
    • 指数衰减:它有一个数学公式 lr = lr0 * e^(−kt)其中在这种情况下 lr 和 k 是 ar 超参数,t 是迭代次数。我们可以通过指定指数衰减函数并将其传递给学习率调度器来轻松执行。

示例:

import tensorflow as tf 

mnist = tf.keras.datasets.mnist 

(X_train, y_train), (X_test, y_test) = mnist.load_data() 

X_train, X_test = X_train / 255.0, X_test / 255.0 

model = tf.keras.models.Sequential([ 

   tf.keras.layers.Flatten(input_shape=(28, 28)), 

   tf.keras.layers.Dense(512, activation='relu'), 

   tf.keras.layers.Dropout(0.2), 

   tf.keras.layers.Dense(10, activation='softmax')]) 

sgd = tf.keras.optimizers.SGD(learning_rate=0.01)
model.compile(optimizer='sgd',  

   loss='sparse_categorical_crossentropy', 

   metrics=['accuracy'])
model.fit(X_train, y_train, 

          epochs=10, 

          validation_split=0.2)
model.summary()

在这个例子中,我将使用*TF . keras . datasets*下的 mnist 数据集,然后我将训练和测试数据加载为(*x _ train*&*y _ train*)。因为输入特征在 0 到 255 之间。我会把它除以 255 来归一化。

之后,我将创建一个新的序列模型,其中有一个单独的图层,名为 model =*TF . keras . models . sequential*,因此在第一个图层中,我创建了一个展平图层,它将采用 shape (28,28)的输入图像。在第二层中,我创建了一个具有 512 个神经元的密集层,激活函数为 relu,它被 drop_out rate =0.2 的层丢弃,最终输出层创建了一个具有 10 个神经元的密集层,激活函数为 SoftMax。

现在我们将使用 model.summary() 来显示摘要。

你可以参考下面的截图。

TensorFlow Learning rate Scheduler

TensorFlow Learning rate Scheduler

这就是我们如何通过 TensorFlow 在优化器 SGD 中使用学习率。

阅读:批量归一化张量流

TensorFlow 学习率调度器 adam

  • 在本例中,我们将在编译模型时使用“adam”优化器。
  • Adam 是一种不同的优化算法,可用于训练深度学习模型,而不是随机梯度下降。
  • Adam 创造了一种优化技术,通过结合 AdaGrad 和 RMSProp 算法的最佳特性,可以在嘈杂的情况下处理稀疏梯度。
  • Adam 的配置相当简单,默认的配置设置对大多数问题都很有效。
  • Adam 这个名字来自自适应矩估计。为了在训练期间调整网络权重,这种优化方法是随机梯度下降的进一步扩展。
  • Adam optimizer 会分别修改每个网络权重的学习率,这与 SGD 培训不同,SGD 培训保持单一的学习率。Adam 优化算法的设计者知道 AdaGrad 和 RMSProp 算法的优点,这是另外两种随机梯度下降扩展。
  • 因此,Adagrad 和 RMS prop 算法的特性都被 Adam 优化器继承。Adam 使用梯度的一阶和二阶矩来调整学习率,而不是像 RMS Prop 那样只使用一阶矩(均值)。

示例:

在本例中,我们将使用“adam”优化,然后我们将使用优化。

 import tensorflow as tf 

mnist = tf.keras.datasets.mnist 

(X_train, y_train), (X_test, y_test) = mnist.load_data() 

X_train, X_test = X_train / 255.0, X_test / 255.0 

model = tf.keras.models.Sequential([ 

   tf.keras.layers.Flatten(input_shape=(28, 28)), 

   tf.keras.layers.Dense(512, activation='relu'), 

   tf.keras.layers.Dropout(0.2), 

   tf.keras.layers.Dense(10, activation='softmax')]) 

sgd = tf.keras.optimizers.SGD(learning_rate=0.01)
model.compile(optimizer='adam',  

   loss='sparse_categorical_crossentropy', 

   metrics=['accuracy'])
model.fit(X_train, y_train, 

          epochs=10, 

          validation_split=0.2)
model.summary()

下面是下面给出的代码的截图。

TensorFlow learning rate scheduler adam

TensorFlow learning rate scheduler adam

正如你在截图中看到的,我们通过 TensorFlow 使用了“sgd”优化器。

阅读:张量流自定义损失函数

TensorFlow 学习率调度余弦

  • 这里我们将通过 TensorFlow 在学习率调度器中使用余弦优化器。
  • 这是一种学习率时间表,其效果是以高学习率开始,快速下降到一个较低的数字,然后又快速上升。

语法:

下面是TF . compat . v1 . train . cosine _ decay()函数的语法

tf.keras.optimizers.schedules.CosineDecay(
                                          initial_learning_rate,
                                          decay_steps, 
                                          alpha=0.0,
                                          name=None
                                         )
  • 它由几个参数组成
    • initial_learning_rate :它是一个定标器浮点 64 或浮点 32,它定义初始学习速率
    • decay_steps :指定了衰减的步数,是一个 scaler int 32。
    • alpha :默认情况下,取值为 0.0,它会检查最小学习率值始终是初始 learning_rate 的一个分数的情况。
    • 名称:定义操作的名称,默认为无。

示例:

import matplotlib.pyplot as plt
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
empty_val = []
second_empty_val = []
number_of_iteration = 100

with tf.compat.v1.Session() as sess:
    sess.run(tf.compat.v1.global_variables_initializer())
    for global_step in range(number_of_iteration):

        new_rate_1 = tf.compat.v1.train.cosine_decay(
            learning_rate=0.1, global_step=global_step, decay_steps=150,
            alpha=0.0)

        new_learing_rate_2 = tf.compat.v1.train.cosine_decay(
            learning_rate=0.1, global_step=global_step, decay_steps=150,
            alpha=0.3)
        lr1 = sess.run([new_rate_1])
        lr2 = sess.run([new_learing_rate_2 ])

        empty_val.append(lr1[0])
        second_empty_val.append(lr2[0])

x = range(number_of_iteration)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(x, second_empty_val,'r-', linewidth=2)
plt.plot(x, empty_val,'g-', linewidth=2)
plt.title('cosine_decay')
ax.set_xlabel('step')
ax.set_ylabel('learing rate')
plt.show()

在下面给定的代码中,我们导入了 TensorFlowmatplotlib 库,然后使用了*TF . compat . v1 . train . cosine _ decay()*函数,在这个函数中,我们指定了学习速率和衰减步长。

你可以参考下面的截图。

TensorFlow learning rate scheduler cosine

TensorFlow learning rate scheduler cosine

这就是我们如何通过 TensorFlow 使用余弦速率调度程序。

阅读: TensorFlow 全球平均池

TensorFlow 获取学习率

  • 在本节中,我们将学习如何使用 TensorFlow 获得学习率。
  • 为了执行这个特定的任务,我们将使用的概念TF . keras . optimizer . Adam()函数。
  • 在这个函数中,我们将学习率设置为 0.1,并且*learning rate scheduler*回调从我们在训练之前预先定义的调度函数接收更新的学习率值。

语法:

让我们看看语法,了解一下TF . keras . optimizer . Adam()函数的工作原理。

tf.keras.optimizers.Adam(
    learning_rate=0.001,
    beta_1=0.9,
    beta_2=0.999,
    epsilon=1e-07,
    amsgrad=False,
    name='Adam',
    **kwargs
)
  • 它由几个参数组成。
    • learning_rate :默认情况下,它取值为 0.001,这是一个不带参数并返回实际值的功能。
    • beta_1 :要使用的实际值、浮点值、常量浮点张量或不接受参数的可调用函数。第一时刻的估计指数下降率。默认情况下,0.9。
    • beta_2 :要使用的实际值、浮点值、常量浮点张量或不接受参数的可调用函数。二阶矩的估计指数下降率。默认情况下,0.999。
    • epsilon :数字稳定性的名义常数,默认取 1e-07。
    • amsgrad :是关于 Adam 和 beyond 收敛的布尔值。

举例:

import tensorflow as tf

new_optimize_val = tf.keras.optimizers.Adam(0.1)
new_var_val = tf.Variable(20.0)
new_loss_val = lambda: (new_var_val ** 2)/2.0   
step_count = new_optimize_val.minimize(new_loss_val, [new_var_val])

print(step_count)

下面是以下代码的截图

TensorFlow get learning rate

TensorFlow get la earning rate

如你所见,我们将获得所有关于 adam optimizer 的信息。

阅读:二元交叉熵张量流

张量流自适应学习率

  • Adagrad、Adadelta、RMSprop 和 Adam 是自适应梯度下降算法的示例,它们提供了传统 SGD 的替代方案。这些每参数学习率方法提供了一种启发式方法,而不需要耗时的手动超参数。
  • 此外,Keras 有几个基本的随机梯度下降扩展,支持可变的学习率。经常需要小的配置,因为每种技术修改学习率,通常每个模型权重一个学习率。
  • 它允许训练算法跟踪模型的性能,并自动更改学习率以获得最佳性能。

示例:

让我们举个例子,了解一下自适应学习率的工作原理。

import tensorflow as tf 

mnist = tf.keras.datasets.mnist 

(X_train, y_train), (X_test, y_test) = mnist.load_data() 

X_train, X_test = X_train / 255.0, X_test / 255.0 

model = tf.keras.models.Sequential([ 

   tf.keras.layers.Flatten(input_shape=(28, 28)), 

   tf.keras.layers.Dense(512, activation='relu'), 

   tf.keras.layers.Dropout(0.2), 

   tf.keras.layers.Dense(10, activation='softmax')]) 

sgd = tf.keras.optimizers.SGD(learning_rate=0.01)
model.compile(optimizer='sgd',  

   loss='sparse_categorical_crossentropy', 

   metrics=['accuracy'])
model.fit(X_train, y_train, 

          epochs=10, 

          validation_split=0.2)
model.summary()

你可以参考下面的截图

TensorFlow adaptive learning rate

TensorFlow adaptive learning rate

你可能也喜欢阅读下面的 TensorFlow 教程。

在本 Python 教程中,我们重点介绍了使用 TensorFlow 的机器学习模型的学习率计划。此外,我们将看一些如何在 TensorFlow 中学习学习率计划的例子。我们已经讨论了这些主题。

  • TensorFlow 学习率计划程序
  • TensorFlow 学习率计划程序 adam
  • TensorFlow 学习率计划程序余弦
  • TensorFlow 获取学习率
  • 张量流自适应学习速率

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流均方误差

原文:https://pythonguides.com/tensorflow-mean-squared-error/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何在 Python TensorFlow 中求 均方误差。此外,我们将讨论以下主题。

  • 张量流均方误差
  • 张量流矩阵均方误差
  • 张量流均方对数误差
  • 张量流加权均方误差
  • 张量流均方根误差
  • 张量流减少均方误差
  • 张量流计算均方误差
  • 平均成对平方误差张量流

目录

张量流均方误差

  • 在本节中,我们将讨论如何在 Python TensorFlow 中找到均方误差。
  • 为了执行这个特定的任务,我们将使用TF . compat . v1 . losses . mean _ squared _ error()函数,该函数用于插入给定标签和预测的平方和。

语法:

我们先来看看语法,了解一下TF . compat . v1 . losses . mean _ squared _ error()函数在 Python TensorFlow 中的工作原理。

tf.compat.v1.losses.mean_squared_error
                                      (
                                       labels,
                                       prediction,
                                       weights=1.0,
                                       scope=None,
                                       loss_collection=tf.graphkeys.Losses,
                                       reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
                                      )
  • 它由几个参数组成
    • 标签:该参数表示输出张量,类似于预测参数。
    • 预测:该参数指定输出的预测。
    • weights: 默认取 1.0 值,指定 rank 将为 0 或类似 rank 作为标签,也是可选参数。
    • scope: 缺省情况下,取 none 值,表示我们可以在损失函数中执行的操作的范围。
    • loss_collection: 该参数指定了我们要插入到损失函数中的集合,默认情况下它采用TF . graph . keys . loss()

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中求均方误差。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_true = [15, 56, 77]
new_val_predict = [89, 26, 108]
weights = [45, 189, 0.34]

result=tf.compat.v1.losses.mean_squared_error(labels=new_true,predictions=new_val_predict,weights=weights)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

在上面的代码中,我们导入了 TensorFlow 库,然后初始化了预测和权重值。

之后,我们使用了TF . compat . v1 . losses . mean _ squared _ error()函数,在这个函数中,我们将预测和权重作为一个参数。一旦执行了这段代码,输出将显示均方误差。

下面是以下给定代码的实现。

TensorFlow mean squared error

TensorFlow mean squared error

阅读: TensorFlow Tensor to numpy

张量流矩阵均方误差

  • 在本节目中,我们将讨论如何在 Python TensorFlow 中找到度量均方误差。
  • 为了执行此特定任务,我们将使用TF . compat . v1 . metrices . mean _ squared _ error()函数,此函数用于计算给定预测和标签之间的均方误差。在此示例中,我们将标签视为‘new _ true’变量,预测视为‘new _ val _ predict’

语法:

下面是TF . compat . v1 . metrices . mean _ squared _ error()函数的语法。

tf.compat.v1.metrics.mean_squared_error
                                       (
                                        labels,
                                        predictions,
                                        weights=None,
                                        metrices_collections=None,
                                        update_collections=None,
                                        name=None
                                       )
  • 它由几个参数组成
    • 标签:该参数表示与我们在预测中提到的形状相似的张量。
    • 预测:该参数指定了张量的形状。
    • weights: 默认取值为 none,可选参数,秩值为 0
    • 度量集合:这是一个可选的集合列表,我们必须添加一个均方误差。
    • name: 默认情况下,取 none 值,是可选的作用域名称。

举例:

让我们举个例子,看看如何在 Python 中找到 metrices 均方误差。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_true = [15, 56, 77]
new_val_predict = [89, 26, 108]

result=tf.compat.v1.metrics.mean_squared_error(labels=new_true,predictions=new_val_predict)
print(result)

在创建标签和预测值之后,我们使用了TF . compat . v1 . metrices . mean _ squared _ error()函数,在这个函数中,我们将标签和预测作为一个参数传递。

下面是下面给出的代码的截图。

TensorFlow metrices mean squared error

TensorFlow metrices mean squared error

阅读:张量流得到形状

张量流均方对数误差

  • 这里我们要讨论的是如何在 Python TensorFlow 中求均方对数误差。
  • 为了完成这项任务,我们将使用 tf。keras . loss . meansqualdlogithmic()函数,该函数用于计算 y_predy_true 值之间的均方对数误差差。

语法:

下面是 tf 的语法。Python TensorFlow 中的 keras . loss . mean squared 对数错误

tf.keras.losses.MeanSquaredLogarithmicError
                                           (
                                            reduction=losses_utils.ReductionV2.AUTO,
                                            name='mean_squared_logarithmic_error'
                                           )
  • 它由几个参数组成
    • 减少:默认情况下,它采用自动值,该值指定减少选项并决定 contxt 的使用。
    • 名称:该参数表示操作的名称。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中求均方对数误差。

源代码:

import tensorflow as tf

y_true = [[12., 8.], [3., 2.]]
y_pred = [[13., 12.], [4., 2.]]

new_result = tf.keras.losses.MeanSquaredLogarithmicError()
new_result(y_true, y_pred)

在下面的代码中,我们导入了 TensorFlow 库,然后声明了两个变量“y_true”和“y_pred”。之后,我们使用了TF . keras . loss . meansqualdlogarithmicerror(),在这个函数中,我们分配了这些给定值。

下面是下面给出的代码的截图。

TensorFlow mean squared logarithmic error

TensorFlow mean squared logarithmic error

阅读:Python tensor flow reduce _ sum

张量流加权均方差

  • 在本节中,我们将讨论如何在 Python TensorFlow 中计算加权均方误差。
  • 为了执行这一特定任务,我们将使用TF . keras . loss . meansquaderror()函数,该函数将帮助用户生成预测值和标签值之间的均方误差。
  • 在本例中,我们提到了列表' y_true '和' new_val_predict' 形式的标签和预测。

语法:

下面是 tf 的语法。Python TensorFlow 中的 keras . loss . meansquadererror

tf.keras.losses.MeanSquaredError
                               (
                                reduction=losses_utils.ReductionV2.AUTO,
                                name='mean_squared_error'
                               )

举例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
y_true = [0, 1],[1,1]
new_val_predict = [0,0],[1,0]

result=tf.keras.losses.MeanSquaredError()
result(y_true, new_val_predict)

创建变量后,我们使用了 tf。keras . losses . mean squarederror()函数,在该函数中,我们指定了‘y _ true’和‘new _ val _ predict’值。

你可以参考下面的截图。

TensorFlow weighted mean squared error

TensorFlow weighted mean squared error

阅读:Python tensor flow reduce _ mean

张量流均方根误差

  • 在本节中,我们将讨论如何在 Python TensorFlow 中计算均方根误差。
  • 为了执行此特定任务,我们将使用TF . compat . v1 . metrices . root _ mean _ squared _ error()函数,此函数用于将均方根误差生成预测和标签参数。

税:

我们先来看看语法,了解一下TF . compat . v1 . metrices . root _ mean _ squared _ error()函数在 Python TensorFlow 中的工作原理。

tf.compat.v1.metrices.root_mean_squared_error
                                            (
                                             labels,
                                             predictions,
                                             weights=None,
                                             metrices_collection=None
                                             update_collections=None,
                                             name=None
                                            )
  • 它由几个参数组成
    • 标签:该参数表示我们在预测中提到的相似形状的张量。
    • 预测:该参数指定了张量的形状。
    • 权重:默认情况下不取值。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中求均方根误差。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_true = [65, 289, 198]
new_val_predict = [567, 118, 290]
weights = [345, 93, 45]

result=tf.compat.v1.metrics.root_mean_squared_error(labels=new_true,predictions=new_val_predict,weights=weights)
print(result)

下面是下面给出的代码的截图。

TensorFlow root mean squared error

TensorFlow root mean squared error

阅读: Python TensorFlow 随机均匀

张量流减少均方误差

  • 在本节中,我们将讨论如何减少 Python TensorFlow 中的均方误差。
  • 在本例中,我们使用了TF . compat . v1 . losses . mean _ squared _ error()函数,并在该函数中传递了张量 1 和张量 2 的值。
  • 一旦执行了这段代码,输出将显示给定张量的平均值。

举例:

让我们举个例子,检查如何在 Python TensorFlow 中减少均方误差。

源代码:

import tensorflow as tf

new_tens1 = tf.constant([[15.2, 2.8, 13.4],
                      [15.3,17.8,13.1]])
new_tens2 = tf.constant([[14.4, 13.2, 17.9],
                      [14.2,17.3,13.6]])

new_output=tf.compat.v1.losses.mean_squared_error(new_tens1,new_tens2)
print("Reduce mean squared error:",new_output)

下面是下面给出的代码的截图。

TensorFlow reduce mean squared error

TensorFlow reduce mean squared error

阅读: Python TensorFlow one_hot

张量流计算均方误差

这里我们要讨论如何在 Python TensorFlow 中计算均方误差。

均方误差用于计算给定变量的估计值预测值之间的差值。

均方误差公式:

MSE = (1/n)∑i=1n(Yi-Yi)² 

定义变量:

  • ∑:求和表示估计误差的所有已知值的相加。
  • n:这个变量指定样本大小。
  • 易:实际的或者我们可以说是变量的观测值。

现在我们将取一些随机值,并测量每对实际值和预测值之间的差异。接下来,我们将平方这些差值,然后获得平均值。

举例:

让我们举个例子,用数学的方法计算均方误差。

假设我们有以下一组数字

random values for MSE

random values for MSE

现在我们将计算均方误差

MSE calculation

MSE calculation

现在我们将使用张量流方法计算均方误差

源代码:

import tensorflow as tf

y_true = [3,4,6]
new_val_predict = [2.5,5,6]

result=tf.keras.losses.MeanSquaredError()
result(y_true, new_val_predict)

下面是以下给定代码的实现

Tensorflow calculate mean squared error

Tensorflow calculate mean squared error

阅读:模块“张量流”没有属性“会话”

平均成对平方误差张量流

  • 在本节中,我们将讨论如何在 Python 中找到平均成对平方误差张量流。
  • 为此,我们将使用TF . compat . v1 . losses . mean _ pairwise _ squared _ error()函数,该函数用于在 Python TensorFlow 中插入一个成对平方误差。

语法:

我们先来看看语法,了解一下TF . compat . v1 . losses . mean _ pairwise _ squared _ error()函数的工作原理。

tf.compat.v1.losses.mean_pairwise_squared_error
                                               (
                                                labels,
                                                predictions,
                                                weights=1.0,
                                                scope=None,
                                                loss_collection=tf.GraphKeys.LOSSES
                                               )

举例:

import tensorflow as tf
y_true = [2,5,7]
new_val_predict = [3,2,1]

result=tf.compat.v1.losses.mean_pairwise_squared_error(y_true, new_val_predict)
print(result)

下面是以下给定代码的执行过程

mean pairwise squared error tensorflow

mean pairwise squared error TensorFlow

还有,多看看一些 TensorFlow 教程。

所以,在这个 Python 教程中,我们学习了如何在 Python TensorFlow 中求 均方误差。此外,我们还讨论了以下主题。

  • 张量流均方误差
  • 张量流度规均方误差
  • 张量流均方对数误差
  • 张量流加权均方误差
  • 张量流均方根误差
  • 张量流减少均方误差
  • 张量流计算均方误差
  • 平均成对平方误差张量流

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流乘法——有用指南

原文:https://pythonguides.com/tensorflow-multiplication/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何得到 Python TensorFlow 中张量的乘法。此外,我们将涵盖以下主题。

  • tensorflow 乘法
  • 张量流倍增层
  • 张量流乘法矩阵
  • 张量流乘法运算
  • 张量流乘标量张量
  • 沿轴张量流倍增
  • 张量流用向量乘矩阵
  • 张量流乘以整型和浮点型
  • 张量流乘以不同的形状
  • 张量流多重权重
  • 张量流乘元素方式
  • 张量流逐行乘法
  • 张量流减少倍数
  • TensorFlow multiply 3d tensor
  • 张量流乘张量列表
  • TensorFlow keras multiply layer
  • 矩阵乘法张量流与 numpy

目录

张量低乘法

  • 本节我们将讨论如何在 Python TensorFlow 中得到张量的乘法。
  • 为了执行这个特定的任务,我们将使用 tf.math.multiply() 函数,这个函数将帮助用户以 x*y 的形式乘以元素值。
  • 如果你想建立机器学习模型,乘法将很容易帮助你,因为当我们将输入数据作为图像或声音时,它将以张量的形式表示。

语法:

我们先来看看语法,了解一下 tf.math.multiply() 函数在 Python TensorFlow 中的工作原理。

tf.math.multiply
                (
                 x,
                 y,
                 name=None
                )
  • 它由几个参数组成。
    • x: 该参数表示输入张量,必须是整数和浮点数据类型。
    • y: 该参数表示输入张量,必须是整数和浮点数据类型。
    • name: 默认情况下,它不取值,并指定操作的名称。

示例:

我们举个例子,查一下如何在 Python TensorFlow 中得到张量的乘法。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

tens1 = tf.constant(189,dtype="int32",name="tens1")
tens2 = tf.constant(78,dtype="int32",name="tens2")
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

在上面的代码中,我们导入了 TensorFlow 库,然后使用 tf.constant() 函数创建了张量,在这个函数中,我们将值和数据类型指定为参数。

之后,我们使用 tf.math.multiply() 方法进行运算,这个函数将返回给定张量的乘积。

下面是下面给出的代码的截图。

TensorFlow multiplication

TensorFlow multiplication

另外,阅读:张量流均方误差

张量流倍增层

  • 在这个例子中,我们将在 Python TensorFlow 中增加张量层。
  • 为了执行这个特殊的任务,我们将使用 tf。Keras.layers.Multiply() 函数这个函数会很容易地将输入张量列表中的层相乘,并且输入张量必须是相同的形状。

语法:

让我们看看语法,了解一下 tf 的工作原理。Python TensorFlow 中的 Keras.layers.Multiply() 函数。

tf.keras.layers.Multiply
                       (
                        **kwargs
                       )

注意:这个方法只接受一个参数,即 ** ,它总是返回一个张量。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中实现张量的层层相乘。

源代码:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()

result=tf.keras.layers.Multiply()([np.arange(6).reshape(6, 1),
                            np.arange(6, 12).reshape(6, 1)])
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two layers tensors:",new_output)

在下面的代码中,我们导入了 TensorFlow 和 NumPy 库,然后使用TF . compat . v1 . disable _ eager _ execution()函数创建了一个会话。

之后,我们已经使用了 tf。在这个函数中,我们将 np.arange() 函数作为参数传递。

下面是以下给定代码的实现

Flow multiplication layer

TensorFlow multiplication layer

阅读: Python TensorFlow 占位符

张量流乘法矩阵

  • 在本节中,我们将讨论如何在 Python TensorFlow 中找到乘法矩阵。
  • 为了完成这项任务,我们将使用 tf.matmul() 函数,该函数将帮助用户将给定输入的矩阵与另一个矩阵 (x*y) 相乘。简单来说,我们可以说这个函数基本上用于点积矩阵。

语法:

下面是 Python TensorFlow 中 tf.matmul() 函数的语法

tf.matmul
         (
          a,
          b,
          transpose_a=False,
          transpose_b=False,
          adjoint_a=False,
          adjoint_b=False,
          a_is_sparse=False,
          b_is_sparse=False,
          name=None
         )

举例:

下面举个例子,如何在 Python TensorFlow 中求乘法矩阵。

源代码:

import tensorflow as tf
import numpy as np

new_arrays = np.array([(25,78,18),(99,27,18),(45,28,99)],dtype = 'int32')
new_arr2 = np.array([(14,18,16),(45,29,18),(24,19,55)],dtype = 'int32')
new_tens1 = tf.constant(new_arrays)
new_tens2 = tf.constant(new_arr2)
result = tf.matmul(new_tens1, new_tens2)
print((result))

在下面给定的代码中,我们导入了 TensorFlow 和 NumPy 库,然后通过使用 np.array() 函数创建了一个 NumPy 数组,并在该函数中分配了整数值。

之后,我们使用了 tf.constant() 函数来创建张量,在这个函数中,我们为数组赋值。一旦执行了这段代码,输出将显示乘法矩阵。

下面是以下给定代码的执行过程

TensorFlow multiplication matrix

TensorFlow multiplication matrix

阅读: Tensorflow 迭代张量

张量流乘法运算

  • 在本节中,我们将讨论如何使用 * 运算符函数对 Python TensorFlow 中的张量进行乘法运算。
  • 在这个例子中,我们将使用 tf.constant() 函数来创建张量,然后我们将使用 * 运算符来创建乘法张量。

举例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

tens1 = tf.constant([16,27,98])
tens2 = tf.constant([78,178,289])
result= tens1*tens2
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

你可以参考下面的截图

TensorFlow multiplication operation

TensorFlow multiplication operation

阅读: Python TensorFlow 截断法线

张量流乘张量乘标量

  • 在本节中,我们将讨论如何在 Python TensorFlow 中将张量乘以 scaler。
  • 为了完成这个任务,我们将使用 tf.multiply() 函数,这个函数将帮助用户用标量乘张量。简单地说,scaler 是一个单值。

语法:

下面是 Python TensorFlow 中 tf.multiply() 函数的语法

tf.math.multiply
                (
                 x,
                 y,
                 name=None
                )

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中用 scaler 乘以张量。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

input_tensor = tf.constant([[17, 37], [89, 45]])
result = tf.multiply(input_tensor, 67)

with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of tensor by scaler:",new_output)

下面是以下代码的截图

TensorFlow multiply tensor by scaler

TensorFlow multiply tensor by scaler

阅读:将列表转换为张量张量流

张量流沿轴倍增

  • 在本节中,我们将讨论如何在 Python TensorFlow 中沿轴乘以张量。
  • 为了完成这个任务,我们将使用 tf.math.multiply() 函数,这个函数用于获得乘法。

举例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

tens1 = tf.constant([12,34,56])
tens2 = tf.constant([83,24,67])
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

下面是以下代码的截图

TensorFlow multiply along axis

TensorFlow multiply along an axis

阅读: Python TensorFlow one_hot

张量流乘矩阵乘向量

  • 在本节中,我们将讨论如何在 Python TensorFlow 中将矩阵乘以一个向量。
  • 为了完成这项任务,首先,我们将讨论 Python 中的矢量。向量可以定义为一维数组。为了创建一个向量,我们将使用 numpy.array() 函数。
  • 在这个例子中,我们将在 Python TensorFlow 中将矩阵乘以一个向量。

举例:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
#matrix
new_matrix= np.array([[1,2,3,4],
                       [62,34,5,6]])
tens1 = tf.constant(new_matrix)
new_vector = np.array([83,24,67,5])
# vector array
tens2=tf.constant(new_vector)
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

下面是以下给定代码的实现。

TensorFlow multiply matrix by vector

TensorFlow multiply matrix by a vector

阅读:Python tensor flow expand _ dims

TensorFlow 乘 int 和 float

  • 在本节中,我们将讨论如何在 Python TensorFlow 中将整数和浮点数据类型值相乘。
  • 为了完成这个任务,首先,我们将创建一个包含整数值的数组,并在函数 tf.constant() 中指定一个数组作为参数。该函数指定张量的创建。
  • 接下来,我们将创建另一个具有浮点数据类型的数组,并在 tf.constant() 函数中指定一个数组作为参数,然后我们将使用 tf.compat.v1.Session() 函数创建会话。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中把整数和浮点数据类型值相乘。

源代码:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
#matrix
new_matrix= np.array([[1,2,3,4],
                       [62,34,5,6]])
tens1 = tf.constant(new_matrix)
new_vector = np.array([83.2,24.5,67.8,5.2])
# vector array
tens2=tf.constant(new_vector)
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication of two tensors:",new_output)

你可以参考下面的截图。

TensorFlow multiply int and float

TensorFlow multiply int and float

正如您在屏幕截图中看到的,输出显示了类型错误:“Mul”Op 的输入“y”的类型 float64 与参数“x”的类型 int64 不匹配。

这个错误背后的原因是‘tens 1’数据类型是一个整数,而在 tens2 数据类型的情况下是浮动的,并且在 Python tensor flowTF . multiply()方法中,默认情况下不转换其变量的类型。

现在,这个错误的解决方案是,我们可以很容易地在输入张量中创建相同的数据类型

源代码:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
#matrix
new_matrix= np.array([[1,2,3,4],
                       [62,34,5,6]])
tens1 = tf.constant(new_matrix)
new_vector = np.array([[2,4,5,6],
                      [56,7,8,9]])
# vector array
tens2=tf.constant(new_vector)
result= tf.math.multiply(tens1,tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

下面是以下代码的截图

Python TensorFlow multiply int and float

Python TensorFlow multiply int and float

阅读: Python TensorFlow 随机均匀

张量流乘以不同的形状

  • 在这一节中,我们将讨论如何在 Python TensorFlow 中将不同的形状相乘。
  • 为了执行这个特定的任务,我们将使用TF . compat . v1 . random _ normal(),这个函数将从正态分布中生成。
  • 接下来,我们将使用带有浮点值的 tf.constant() 函数,并通过使用 tf.expand_dims( )函数来扩展形状。

语法:

让我们看一下语法,了解一下 Python TensorFlow 中的 tf.expand_dims() 函数的工作原理。

tf.expand_dims
              (
               input,
               axis,
               name=None
              )
  • 它由几个参数组成。
    • 输入:该参数表示输入张量。
    • 轴:该参数表示扩展输入的形状。
    • name: 默认情况下,它不取值,并指定操作的名称。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中把不同的形状相乘。

源代码:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()
tens1 = tf.compat.v1.random_normal([3, 3, 2])
tens2 = tf.constant([[1., 0., 0.], [0., 1., 0.], [1., 0., 1.]])

tens2 = tf.expand_dims(tens2, 2) 
new_result = tf.math.multiply(tens1, tens2)
with tf.compat.v1.Session() as val:
    new_output=val.run(new_result)
    print(new_output)

在下面给定的代码中,我们使用 tf.math.multiply() 函数乘以给定的张量,然后使用 tf.compat.v1.Session() 函数创建会话。

下面是下面给出的代码的截图。

TensorFlow multiply different shapes

TensorFlow multiply different shapes

阅读:Python tensor flow reduce _ mean

张量流倍增权重

  • 在本节中,我们将讨论如何在 Python TensorFlow 中乘以权重。
  • 为了执行这个特定的任务,我们将使用TF . keras . layers . multiply()函数
  • 这个函数可以很容易地将输入张量列表中的层相乘,并且输入张量必须是相同的形状。

语法:

下面是 tf 的语法。Python TensorFlow 中的 Keras.layers.Multiply() 函数。

tf.keras.layers.Multiply
                       (
                        **kwargs
                       )

举例:

我们举个例子,检查一下 Python TensorFlow 中的权重如何相乘。

源代码:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()

result=tf.keras.layers.Multiply()([np.arange(6).reshape(6, 1),
                            np.arange(6, 12).reshape(6, 1)])
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

在下面给出的代码中,我们已经导入了 TensorFlow 和 NumPy 库。之后,我们已经使用了 tf。Keras.layers.Multiply() 函数,在这个函数中,我们用 reshape 方法给 np.arange() 函数赋值。

下面是以下代码的截图

TensorFlow multiply weights

TensorFlow multiply weights

阅读:Python tensor flow reduce _ sum

张量流乘元素方式

  • 在本节中,我们将讨论如何在 Python TensorFlow 中进行元素级乘法。
  • 在这个例子中,我们将使用 tf.constant() 函数来创建张量,然后我们将使用 * 运算符来创建乘法张量。

举例:

让我们举一个例子,检查一下如何在 Python TensorFlow 中逐元素相乘。

源代码:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

tens1 = tf.constant([27,18,27])
tens2 = tf.constant([190,278,189])
result= tens1*tens2
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication element wise:",new_output)

在上面的代码中,我们导入了 TensorFlow 库,然后使用 tf.constant()函数创建张量。之后,我们使用了*运算符,将两个张量相乘。

下面是以下给定代码的执行。

TensorFlow multiply element wise

TensorFlow multiply elementwise

阅读: TensorFlow Tensor to NumPy

张量流逐行乘法

  • 在本节中,我们将讨论如何在 Python TensorFlow 中对行元素进行乘法运算。
  • 为了执行这个特定的任务,我们将初始化输入张量,然后使用 tf.constant() 函数创建另一个 1d 张量。
  • 接下来,我们将使用 t f.math.multiply() 函数,在该函数中,我们将使用 tf.newaxis() 函数来分配张量,该函数用于在张量中多次扩展维度。

举例:

让我们举个例子,检查一下如何在 Python TensorFlow 中按行乘 元素。

源代码:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
# Initializing the input tensor
tens1 = tf.constant([[[78, 56], 
                 [19, 21],
                 [15,19]]])
tens2=tf.constant([13,19,21])
result=tf.math.multiply(tens1, tens2[:, tf.newaxis])
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Multiplication row wise:",new_output)

在上面的代码中,我们刚刚创建了简单的张量,现在我们想通过使用 tf.constant() 函数按行显示两个张量的乘积。

一旦执行了这段代码,输出将显示输入张量的乘积。

下面是以下给定代码的实现

TensorFlow row wise multiplication

TensorFlow row-wise multiplication

阅读:模块“张量流”没有属性“会话”

张量流减少乘

  • 在本节中,我们将讨论如何在 Pythn TensorFlow 中乘以输入张量的同时减少张量。
  • 为了完成这项任务,我们将使用 tf.reduce_prod()函数,该函数将帮助用户生成输入张量的各维值的乘积。

语法:

让我们看一下语法,了解一下 Python TensorFlow 中 tf.reduce_prod()函数的工作原理。

tf.math.reduce_prod
                   (
                    input_tensor,
                    axis=None,
                    Keepdims=False,
                    name=None
                   )
  • 它由几个参数组成
    • 输入张量:该参数表示要减少的输入张量。
    • 轴:默认情况下,它采用 none 值,并指定要减少的尺寸,它将检查条件,如果是 none,则所有尺寸将减少。
    • Keepdims: 默认情况下,它采用 false 值,如果为 true,则它将保留缩减的维度。
    • 名称:该参数表示操作的名称。

举例:

我们举个例子,检查一下在 Python TensorFlow 中,如何在乘以输入张量的同时减少张量。

源代码:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
tens = tf.constant([
    [17, 29, 18],
    [56, 96, 19],
    [23, 28, 39]
])
result = tf.reduce_prod(tens, 0)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print("Reduce multiply:",new_output)

在下面的代码中,我们导入了 TensorFlow 库,然后使用 tf.constant()函数创建了一个张量。之后,我们使用了 tf.reduce_prod()函数,在这个函数中,我们指定了输入张量和轴=0。

下面是以下给定代码的输出

TensorFlow reduce multiply

TensorFlow reduce multiply

阅读: TensorFlow 获取变量+示例

张量流乘 3d 张量

  • 在本节中,我们将讨论如何在 Python TensorFlow 中乘以 3 维输入张量。
  • 为了完成这项任务,我们将使用 tf.matmul() 函数,该函数将帮助用户将给定输入的矩阵与另一个矩阵(x*y)相乘。简单来说,我们可以说这个函数基本上用于点积矩阵。

举例:

我们举个例子,检查一下 Python TensorFlow 中的 3 维输入张量如何相乘。

源代码:

import tensorflow as tf
import numpy as np

# Initialize 3D tensor
new_arrays = np.array([[[45,23,13],
                       [15,16,18],
                       [19,16,11]]])
new_arr2 = np.array([[[26,32,56],
                       [19,28,16],
                       [13,22,29]]])
new_tens1 = tf.constant(new_arrays)
new_tens2 = tf.constant(new_arr2)
result = tf.matmul(new_tens1, new_tens2)
print("Multiplication of 3D Tensors:",result)

在上面的代码中,我们导入了 TensorFlow 库并创建了一个三维数组。之后,我们将数组插入到一个 tf.constant() 函数中,它将被视为一个张量。

一旦执行了这段代码,输出将显示新的三维张量。

下面是下面给出的代码的截图。

TensorFlow multiply 3d tensor

TensorFlow multiply 3d tensor

阅读: TensorFlow feed_dict

张量流乘张量列表

  • 在本节中,我们将讨论 Python TensorFlow 中的张量列表相乘。
  • 在这个例子中,我们通过使用 tf.stack() 函数创建了一个张量列表,这个函数用于堆叠一个等级列表。
  • 创建张量列表后,我们将应用 tf.math.multiply() 函数对输入列表张量进行乘法运算。

语法:

下面是 Python TensorFlow 中 tf.stack() 函数的语法。

tf.stack
        (
         values,
         axis=0,
         name='stack'
        )
  • 它由几个参数组成
    • 值:该参数表示同类型同形状的张量列表。
    • 轴:默认取 0 值,指定第一维度。
    • name: 它定义了操作的名称,默认情况下取‘stack’值。

举例:

import tensorflow as tf
import numpy as np

x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
result=tf.stack([x, y, z])
print("Created first list of tensors:",result)
a = tf.constant([5, 6])
b = tf.constant([8, 9])
c = tf.constant([1, 2])
result2=tf.stack([a, b, c])
print("Created second list of tensors:",result2)
result3 = tf.math.multiply(result,result2)
print("Multiplication of list Tensors:",result3)

下面是下面给出的代码的截图。

TensorFlow multiply list of tensors

TensorFlow multiply list of tensors

TensorFlow keras multiply layer

  • 在本节中,我们将讨论如何在 Python TensorFlow 中使用 keras multiply layer 函数。
  • 为了执行这个特定的任务,我们将使用TF . keras . layers . multiply()函数,这个函数将轻松地将输入张量列表中的层相乘,并且输入张量必须是相同的形状。

语法:

让我们看看语法,了解一下 tf 的工作原理。Python TensorFlow 中的 Keras.layers.Multiply() 函数。

tf.keras.layers.Multiply
                       (
                        **kwargs
                       )

举例:

让我们举个例子,看看如何在 Python TensorFlow 中使用 Keras multiply layer 函数。

源代码:

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()

new_result=tf.keras.layers.Multiply()([np.arange(4).reshape(4, 1),
                            np.arange(4, 8).reshape(4, 1)])
with tf.compat.v1.Session() as val:
    new_output=val.run(new_result)
    print(new_output)

下面是以下给定代码的实现。

TensorFlow keras multiply layer

TensorFlow Keras multiply layer

矩阵乘法 tensorflow vs numpy

  • 在本节中,我们将讨论 TensorFlow 和 numpy 中的矩阵乘法。
  • 为了完成这项任务,我们将使用 tf.matmul() 函数,该函数将帮助用户将给定输入的矩阵与另一个矩阵 (x*y) 相乘。简单来说,我们可以说这个函数基本上用于点积矩阵。
  • 接下来,我们将通过使用 np.matmul() 函数来计算两个 numpy 数组的矩阵乘积,该函数用于计算给定两个数组的矩阵乘法。

举例:

import tensorflow as tf
import numpy as np

new_arrays = np.array([(25,78,18),(99,27,18),(45,28,99)],dtype = 'int32')
new_arr2 = np.array([(14,18,16),(45,29,18),(24,19,55)],dtype = 'int32')
new_tens1 = tf.constant(new_arrays)
new_tens2 = tf.constant(new_arr2)
result = tf.matmul(new_tens1, new_tens2)
print((result))
#Matrix Multiplication of NumPy
import numpy as np

new_array = np.array([[56, 18],
                 [97, 25]])
new_array2 = np.array([[17, 28],
                 [98, 26]])
new_output = np.matmul(new_array, new_array2)

print("Matrix Multiplication of NumPy array:",new_output)

在上面的代码中,我们导入了 TensorFlow 库来创建张量,并使用 tf.matmul() 函数将两个给定的张量相乘。

之后,我们导入了 NumPy 库来创建数组,并使用 np.matmul() 函数对两个给定张量进行乘法运算。

下面是以下给定代码的执行。

matrix multiplication tensorflow vs numpy

matrix multiplication TensorFlow vs NumPy

在本 Python 教程中,我们学习了如何在 Python TensorFlow 中得到张量的乘法。此外,我们还讨论了以下主题。

  • tensorflow 乘法
  • 张量流倍增层
  • 张量流乘法矩阵
  • 张量流乘法运算
  • 张量流乘标量张量
  • 沿轴张量流倍增
  • 张量流用向量乘矩阵
  • 张量流乘以整型和浮点型
  • 张量流乘以不同的形状
  • 张量流多重权重
  • 张量流乘元素方式
  • 张量流逐行乘法
  • 张量流减少倍数
  • TensorFlow multiply 3d tensor
  • 张量流乘张量列表
  • TensorFlow keras multiply layer
  • 矩阵乘法张量流与 numpy

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

张量流自然语言处理

原文:https://pythonguides.com/tensorflow-natural-language-processing/

Python & Machine Learning training courses

在这个 Python 教程中,我们将重点介绍如何使用 TensorFlow 部署一个自然语言处理模型,并且我们还将看一些如何在 TensorFlow 中学习自然语言处理的例子。我们将讨论这些话题。

  • 张量流自然语言处理
  • 自然语言处理的好处是什么
  • 自然语言处理的优势是什么
  • 自然语言处理的缺点是什么

目录

TensorFlow 自然语言处理

  • 自然语言处理是理解和解释当今大量非结构化数据的重要工具。
  • 由于深度学习算法在各种困难的任务中取得了令人印象深刻的结果,如图片分类、语音识别和逼真的文本制作,深度学习最近被广泛用于许多 NLP 应用。
  • 目前使用的最人性化、最有效的深度学习框架是 TensorFlow。
  • 自然语言处理有许多实际应用。具有大量 NLP 任务的系统被认为是好的。当你使用谷歌翻译来学习如何说“你在哪里?”时,你依赖于这些 NLP 活动的一部分。
  • 让我们来看看 NLP 的一些基础知识。
    • 标记化:标记化是任何 NLP 管道的初始阶段。它会显著影响您的管道的其余部分。标记化是将非结构化数据和自然语言文本划分成可被视为离散片段的数据单元的过程。可以直接利用文档的标记出现作为向量来表示该文档。这可以立即将文本文档或非结构化字符串转换为适合机器学习的数字数据格式。它们也可以被计算机直接用来启动有帮助的回答和行动。它们也可以用作机器学习管道中的特征,以启动更复杂的动作或判断。
    • 词义消歧:一种重要的自然语言处理技术,用于确定一个单词在上下文中的含义,称为词义消歧。NLP 系统很难正确识别单词,因此了解单词在给定的句子中是如何使用的可能是有用的。确定一个词在几个上下文中使用时的含义所产生的混乱基本上是通过词义消歧来解决的。
    • 排序:既然我们的单词是这样表示的,下一步就是用正确的数字序列来表示我们的句子。然后,这些数据将为神经网络处理做准备,以便解释或甚至生成新的文本。

举例:

让我们举一个例子,使用 tokenizer 函数

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer

new_words = ['The Clever fox',
             'Jumps over the lazy dog',
             ]

result = Tokenizer(num_words = 50)

result.fit_on_texts(new_words)

word_index = result.word_index

print(word_index)

在这个例子中,我们导入了所需的库,然后创建了一个想要标记的例句列表。接下来,我们将声明一个标记器,它可以有一个索引,单词数是可以保留的最大单词数。

之后,我们将为创建一个 tokenizer 对象的句子。输出将是一个字典。

下面是下面给出的代码的截图。

TensorFlow natural language Processing

TensorFlow natural language Processing

这就是我们如何通过使用自然语言处理来使用记号赋予器

例二:

现在我们将通过使用排序来举一个自然语言处理的例子

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer

new_words = ['The Clever fox',
             'Jumps over the lazy dog',
             'you love my dog!',
            ]

new_result = Tokenizer(num_words = 50)
new_result.fit_on_texts(new_words)
output = new_result.word_index

new_sequences = new_result.texts_to_sequences(new_words)

print(output)
print(new_sequences)

你可以参考下面的截图

TensorFlow natural language Processing sequential

TensorFlow natural language Processing sequential

正如您在屏幕截图中看到的,输出使用顺序方法显示了带单词的索引值。

阅读:tensor flow next _ batch+Examples

自然语言处理有什么好处

  • 在这一节中,我们将讨论自然语言处理的好处。
    • 执行大规模分析:自然语言处理技术使对各种文档、内部系统、电子邮件、社交媒体数据、在线评论等的可扩展文本分析成为可能。此外,NLP 工具可以根据您的需求即时放大或缩小,从而提供您所需的计算能力。
    • 在搜索中排名靠前:在一家公司,搜索引擎优化至关重要。每个企业都渴望拥有高排名。自然,自然语言处理是有用的。解决方案评估搜索查询,找到并推荐相似的关键字,然后优化我们的内容,同时节省研究时间。
    • 制造:制造商可以通过使用 NLP 来分析数据,从而提高自动化程度并简化流程。他们可以进行改进以提高效率,并立即决定需要改进的领域。
    • 医疗保健:为了更好地诊断和治疗患者,并提供更好的结果,NLP 可以通过电子邮件、聊天应用程序和患者帮助热线来评估患者沟通。

阅读: TensorFlow 全球平均池

自然语言处理的优势有哪些

  • 这里我们将讨论自然语言处理的一些优点
  • 自然语言处理帮助用户提出任何主题的问题,并在一秒钟内得到结果。
  • 自然语言处理帮助计算机用任何语言与人类交流。
  • 这是一个更快的客户服务响应时间,也非常省时。
  • 它将允许你比较更多的基于语言的数据和一个人,而不会感到疲劳,并且以一种公平和一致的方式。
  • 自然语言处理与雇佣人类相比成本更低,因为人类可以比机器多花三到四倍的时间来完成这项任务。

阅读:二元交叉熵张量流

自然语言处理的缺点有哪些

  • 在这一节中,我们将讨论自然语言处理的缺点。
  • 自然语言处理具有文档的准确性,并且它不能抓住新的领域,并且它具有有限的功能,这就是为什么自然语言处理是为特定任务而构建的。
  • 如果查询是简写的,算法可能无法给出正确的响应。

你可能也喜欢阅读下面的 Python TensorFlow。

在本教程中,我们重点介绍了如何部署一个 TensorFlow 自然语言处理 模型,并且我们还看了一些如何在 TensorFlow 中学习自然语言处理的示例。我们已经讨论了这些主题。

  • 张量流自然语言处理
  • 自然语言处理的好处是什么
  • 自然语言处理的优势是什么
  • 自然语言处理的缺点是什么

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

TensorFlow next_batch +示例

原文:https://pythonguides.com/tensorflow-next_batch/

Python & Machine Learning training courses

在这个 Python 教程中,我们将学习如何为 Python TensorFlow 中的数据执行 Tensorflow next_batch。此外,我们将涵盖以下主题。

  • TensorFlow next_batch
  • 张量流数据集 next_batch
  • TensorFlow 数据集获取 next_batch
  • tensor flow Mn ist . train . next _ batch

另外,查看 TensorFlow 上的相关教程: TensorFlow feed_dict

目录

TensorFlow next_batch

  • 在本节中,我们将讨论如何为 Python TensorFlow 中的数据实现 TensorFlow next_batch。
  • 为了执行这个特定的任务,我们将从给定的训练集中生成 100 个随机数据点,然后使用全局函数以数组的形式传递样本数。

举例:

让我们举个例子,看看如何在 Python TensorFlow 中为数据实现 TensorFlow next_batch。

源代码:

 import numpy as np

def next_batch(new_num, new_dat, labels):

    new_indx = np.arange(0 , len(new_dat))
    np.random.shuffle(new_indx)
    idx = new_indx[:new_num]
    new_result = [new_dat[ i] for i in new_indx]
    new_output = [labels[ i] for i in new_indx]

    return np.asarray(new_result), np.asarray(new_output)

new_value, new_val = np.arange(0, 10), np.arange(0, 100).reshape(10, 10)
print(new_value)
print(new_val)

new_value, new_val = next_batch(5, new_value, new_val)
print('random samples')
print(new_value)
print(new_val) 

在下面给出的代码中,我们导入了 NumPy 库,然后定义了函数 next_batch() ,在该函数中,我们将 new_num 和 new_data 作为参数传递,它将返回随机样本的总数。

之后,我们通过使用 np.arange() 函数和 reshape 方法设置了随机的 100 个值。一旦执行了这段代码,输出将显示 NumPy 数组,其中存储了 100 个值。

下面是下面给出的代码的截图。

TensorFlow next batch

TensorFlow next_batch

阅读: Tensorflow 嵌入 _ 查找

TensorFlow 数据集 next_batch

  • 在本节中,我们将讨论如何使用数据集在 Python TensorFlow 中实现 TensorFlow next_batch。
  • 为了执行这个特定的任务,我们将使用TF . data . dataset . from _ tensor _ slices()函数,这个函数声明了一个潜在的大型值集。

语法:

我们先来看看语法,了解一下 tf.data.dataset() 函数在 Python TensorFlow 中的工作原理。

tf.data.Dataset
               (
                variant_tensor
               )
  • 它由几个参数组成。
    • variant_tensor: 该参数定义了张量的数据集。

举例:

import tensorflow as tf

input_tensor = tf.range(7)

new_datset = tf.data.Dataset.from_tensor_slices(input_tensor)
print(new_datset)
for m in new_datset:    
    print(m)
new_datset2 = new_datset.batch(batch_size=2)
print("Batch method:")
for m in new_datset2:
    print(m) 

在下面给出的代码中,我们导入了 Tensorflow 库,然后使用 tf.range() 函数创建了张量。之后,我们使用TF . data . dataset . from _ tensor _ slices()函数创建数据集,并在此函数内将输入张量指定为参数。

一旦执行了这段代码,输出将显示我们在张量中设置的范围值。之后,我们对 next_batch 值使用了 new_dataset.batch() 方法。

下面是下面给出的代码的截图。

TensorFlow dataset next batch

TensorFlow dataset next_batch

阅读:张量流 clip_by_value

TensorFlow 数据集获取 next_batch

  • 在本节中,我们将讨论如何在 Python TensorFlow 中获取 next_batch 数据集。
  • 为了完成这个任务,我们将使用TF . data . dataset . from _ tensor slices()函数,在这个函数中,我们将设置 batch 和 epochs() 值。
  • 接下来,我们将声明大小和纪元值的变量,然后使用 tf.variable scope() 函数。该函数声明新的变量,并在禁用急切执行时按预期工作。

语法:

让我们看一下语法,了解一下 Python TensorFlow 中TF . compat . v1 . variable _ scope()函数的工作原理。

tf.compat.v1.variable_scope(
    name_or_scope,
    default_name=None,
    values=None,
    initializer=None,
    regularizer=None,
    caching_device=None,
    partitioner=None,
    custom_getter=None,
    reuse=None,
    dtype=None,
    use_resource=None,
    constraint=None,
    auxiliary_name_scope=True
)

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中获取 next_batch 数据集。

源代码:

import tensorflow as tf
from __future__ import absolute_import
from __future__ import division

def ds_train(new_val_size, new_epochs):  
    new_val = (tf.data.Dataset.from_tensor_slices(([16.2,76.2,38.4,11.6,19.3], [-12,-15,-28,-45,-89]))
            .batch(new_val_size)
            .repeat(new_epochs)        
            )
    return new_val

new_val_size= 1
input_size = 1
new_epochs = 2

with tf.variable_scope("dataset"):       
    result= ds_train(new_val_size, new_epochs)

with tf.variable_scope("iterator"):
    val_iterate = result.make_initializable_iterator()
    new_iterate_handle = tf.placeholder(tf.string, shape=[])
    iterator = tf.data.Iterator.from_string_handle(new_iterate_handle, 
                                                val_iterate.output_types,
                                                val_iterate.output_shapes)

    def next_item():
        new_element = iterator.get_next(name="new_element")
        m, n = tf.cast(new_element[0], tf.float32), new_element[1]
        return m, n        

inputs = tf.Variable(tf.zeros(shape=[new_val_size,input_size]), dtype=tf.float32, name="inputs", trainable=False, use_resource=True)
target = tf.Variable(tf.zeros(shape=[new_val_size], dtype=tf.int32), dtype=tf.int32, name="target", trainable=False,use_resource=True)
is_new = tf.placeholder_with_default(tf.constant(False), shape=[], name="new_item_flag")

def new_data(new_val_size, input_size):

    next_inputs, next_target = next_item()
    next_inputs = tf.reshape(next_inputs, shape=[new_val_size, input_size])
    with tf.control_dependencies([tf.assign(inputs, next_inputs), tf.assign(target, next_target)]):
        return tf.identity(inputs), tf.identity(target)

def old_data():

    return inputs, target

next_inputs, next_target = next_item()

inputs, target =  tf.cond(is_new, lambda:new_data(new_val_size, input_size), old_data)

with tf.Session() as sess:
    sess.run([tf.global_variables_initializer(),tf.local_variables_initializer()])
    handle_t = sess.run(val_iterate.string_handle())
    sess.run(val_iterate.initializer)
    while True:
        try:
            print(sess.run([inputs, target], feed_dict={new_iterate_handle:handle_t, is_new: False}))
            print(sess.run([inputs, target], feed_dict={new_iterate_handle:handle_t, is_new: False}))
            print(sess.run([inputs, target], feed_dict={new_iterate_handle:handle_t, is_new: True}))
        except tf.errors.OutOfRangeError:
            print("End of training dataset.")
            break 

在下面给出的代码中,我们使用了TF . data . iterator . from _ string _ handle()函数,该函数指示了遍历数据集,然后使用 tf.variables() 函数声明张量的状态。

下面是以下给定代码的实现。

TensorFlow dataset get next batch

TensorFlow dataset get next_batch

阅读:二元交叉熵张量流

tensor flow mnist . train . next _ batch

  • 在本节中,我们将讨论如何通过使用 Python TensorFlow 在 next_batch 中使用 mnist 训练数据集。
  • 在 Python 中,mnist 是指定手写数字分类的图像的数据集,并且在 mnist 数据集中,有几乎 70,000 个图像,并且每个图像包括 784 个特征。

注:来自tensor flow . examples . tutorials . mnist import input _ data()库仅在 TensorFlow 1.x 版本中可用。如果您使用的是 TensorFlow 的最新版本,那么您必须卸载并安装 TensorFlow 的 1.x 版本才能执行此程序。

举例:

让我们举个例子,通过使用 Python TensorFlow 来检查如何在 next_batch 中使用 mnist 训练数据集。

源代码:

import matplotlib.pyplot as plt
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("data")

new_index_val = 8
new_index_val -=2 
mnist.train.next_batch(-mnist.train._index_in_epoch)

mnist.train.next_batch(new_index_val) 
new_batc_x, new_batc_y = mnist.train.next_batch(1)

print("mnist train next batch")
plt.imshow(new_batc_x.reshape([28, 28]), cmap='Blues')
plt.show()
print(new_batc_y, np.argmax(new_batc_y), mnist.train._index_in_epoch)

new_img_x = mnist.train.images[new_index_val] 
new_img_y = mnist.train.labels[new_index_val] 

print("mnist image batch")
plt.imshow(new_img_x.reshape([28, 28]), cmap='Dark2')
plt.show()
print(new_img_y, np.argmax(new_img_y), mnist.train._index_in_epoch)

在下面给出的代码中,我们从 tensor flow . examples . tutorials . mnist 导入了 input_data 库,然后使用了索引值。

之后,我们将批处理分为两部分 new_batc_x 和 new_batc_y 变量,并为 mnist.train.next_batch()赋值。在 plot imshow() 函数中,我们提到了图像的像素(28,28)和图像颜色作为参数。

下面是下面给出的代码的截图。

TensorFlow mnist.train.next_batch in Python

TensorFlow mnist.train.next_batch in Python

还有,多看看一些 Python TensorFlow 教程。

在这个 Python 教程中, 我们学习了如何在 Python TensorFlow 中对数据执行 Tensorflow next_batch。此外,我们还讨论了以下主题。

  • TensorFlow next_batch
  • 张量流数据集 next_batch
  • TensorFlow 数据集获取 next_batch
  • tensor flow Mn ist . train . next _ batch

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

Python TensorFlow one_hot

原文:https://pythonguides.com/tensorflow-one_hot/

Python & Machine Learning training courses

在本 Python 教程中,我们将学习如何在 Python 中使用 TensorFlow one_hot 函数。此外,我们将讨论以下主题。

  • TensorFlow one_hot 示例
  • 张量流 one_hot to index
  • TensorFlow one_hot 编码示例
  • TensorFlow one_hot axis
  • 张量流一热分类
  • TensorFlow one hot 编码字符串
  • 张量流一从热到密
  • TensorFlow text one 热编码
  • 反向一热编码张量流
  • 张量流稀疏一热
  • TensorFlow 多标签 one hot

目录

Python TensorFlow one_hot

  • 在本节中,我们将讨论如何在 TensorFlow Python 中使用 one_hot()函数。
  • 在 python 中,one-hot 编码是一种用于将分类数据转换为数字的技术,以便您可以将其用于机器学习算法。
  • 假设我们有随机变量来表示指数数字,现在我们想把这些数字转换成数字整数 (0,1)
  • 为了执行这个特定的任务,我们将使用 tf.one_hot() 函数。这个函数将帮助用户返回一个单键张量。

语法:

让我们看一下语法,了解一下 TensorFlow Python 中的 tf.one_hot() 函数的工作原理。

tf.one_hot
          (
           indices,
           depth,
           on_value=None,
           off_value=None,
           axis=None,
           dtype=None,
           name=None
          )
  • 它由几个参数组成
    • 索引:该参数表示我们要操作的索引号,是索引的张量。
    • 深度:定义一个热张量的行数和列数的维度。
    • on_value: 如果没有提供,默认取 1 值。
    • off_value: 如果没有提供,默认取 0 值。
    • 轴:该参数定义了要填充的轴,默认为 -1
    • dtype: 输出张量的数据类型。

注意:如果没有提供数据类型,那么默认情况下 on_value 和 off_value 的数据类型将是 tf.float32 ,并且在两个参数中必须是相同的数据类型。如果不匹配,那么将会出现类型错误。

举例:

我们举个例子,检查一下如何在 Python TensorFlow 中使用 one_hot() 函数。

源代码:

import tensorflow as tf

new_indi = [2, 3, 5]
new_val = 4
result=tf.one_hot(new_indi, new_val)
print(result)

在上面的代码中,我们导入了 TensorFlow 库,然后初始化了一个列表,在其中我们分配了索引号。之后,我们使用了 tf.one_hot() 函数,在这个函数中,我们将索引和深度作为参数传递。

下面是以下给定代码的实现。

Python TensorFlow one hot

Python TensorFlow one_hot

另外,请阅读: TensorFlow Tensor to NumPy

TensorFlow one_hot 示例

  • 在本节中,我们将讨论 Python TensorFlow 中 one_hot 函数的示例。
  • 为了完成这个任务,我们将使用 tf.one_hot() 函数,它将把随机数转换成二进制整数。
  • 在本例中,我们通过导入TF . compat . v1 . disable _ eager _ execution()函数创建了会话。
  • 接下来,我们将在列表中声明索引号,然后我们将使用 tf.one_hot() 函数,并将索引,深度轴指定为参数。

举例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_ind = [0,2,3,4,1]
tens = tf.constant(4)

result = tf.one_hot(new_ind, tens,on_value=1.0,off_value=0.0, axis =-1)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

下面是以下给定代码的执行。

Python TensorFlow one_hot example

Python TensorFlow one_hot example

正如你在截图中看到的,输出显示张量 one_hot。

阅读:张量流得到形状

TensorFlow one_hot to index

  • 在本期节目中,我们将讨论如何在 Python TensorFlow 中将 one_hot 转换为 index。
  • 为了完成这个任务,首先,我们将显示一热的张量,然后将其转换为一个指数。通过使用 tf.argmax() 函数,我们可以很容易地将单热张量转换成指数。
  • 在 Python 中, tf.argmax() 函数用于返回给定输入张量的索引。

语法:

让我们看一下语法,理解一下 tf.argmax() 函数的工作原理。

tf.argmax
         (
          x,
          axis
         )

举例:

让我们举一个例子,看看如何在 Python TensorFlow 中将一热张量转换为 index。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_ind = [0,2,3,4,1]
tens = tf.constant(4)

result = tf.one_hot(new_ind, tens,on_value=1.0,off_value=0.0, axis =-1)
new_result = tf.argmax(result, axis=1)
with tf.compat.v1.Session() as val:
    new_output=val.run(new_result)
    print(new_output)

下面是以下给定代码的实现。

Python TensorFlow one_hot to index

Python TensorFlow one_hot to index

正如您在屏幕截图中看到的,输出显示了指数数字。

阅读:导入错误没有名为 TensorFlow 的模块

TensorFlow one_hot 编码示例

  • 在本节中,我们将讨论 TensorFlow Python 中的示例 one_hot 编码。
  • 通过使用 tf.one_hot() 函数,我们可以轻松地执行这个特定的任务,并使用函数中的所有参数。

举例:

让我们看一下这个例子,了解一下 tf.one_hot() 函数的工作原理。

源代码:

import tensorflow as tf

tens=[1,3,4,5]
result= tf.one_hot(tens, depth=4, on_value="True", off_value="False")
tf.print(result) 

在下面的代码中,我们导入了 TensorFlow 库,然后初始化了一个指示索引号的列表。之后,我们使用了 tf.one_hot() 函数,在该函数中,我们将深度、on_value 和 off_value 指定为参数。

在本例中,我们设置了 on_value="True "和 off_value="False" 。一旦执行了这段代码,输出将按照布尔值的顺序显示一键张量。

下面是下面给出的代码的截图。

Python TensorFlow one_hot encoding example

Python TensorFlow one_hot encoding example

阅读: Python 复制 NumPy 数组

张量流 one _ 热轴

  • 在本节中,我们将讨论我们将在 TensorFlow Python 中的 one_hot()函数中使用轴参数。
  • 为了完成这个任务,我们将使用 tf.one_hot() 函数,在这个函数中,我们设置了 axis=-1 ,它表示最里面的轴。

语法:

让我们看看语法,理解 Python 中 TensorFlow one_hot() 函数的工作原理。

tf.one_hot
          (
           indices,
           depth,
           on_value=None,
           off_value=None,
           axis=None,
           dtype=None,
           name=None
          )

举例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

result = tf.one_hot([1,3,5,2], 6,axis =-1)
with tf.compat.v1.Session() as val:
    new_output=val.run(result)
    print(new_output)

在下面给出的代码中,我们通过导入TF . compat . v1 . disable _ eager _ execution()函数创建了一个会话,然后在 tf.onehot() 函数中指定了 axis=-1

下面是下面给出的代码的截图。

Python TensorFlow one_hot axis

Python TensorFlow one_hot axis

阅读:Python tensor flow expand _ dims

张量流一热分类

  • 这里我们将讨论如何在 Python TensorFlow 中使用 one _ hot categorical()函数。
  • 在本例中,我们将使用 TFP . distribution . onehot categorial()函数,该函数由对数概率参数化,然后我们将创建一个类分布。

语法:

下面是TFP . distributions . onehot categorial()函数的语法。

tfp.distributions.Categorical
                             (
                              logits=None,
                              probs=None,
                              dtype=tf.int32,
                              validate_args=False,
                              allow_nan_stats=True,
                              name='Categorical'
                             )

举例:

让我们举个例子,了解一下TFP . distributions . onehot categorial()函数的工作原理。

import tensorflow as tf
import tensorflow_probability as tfp

tens=tfp.distributions.OneHotCategorical(probs=[0.7,0.4,0.5])
print(tens)
result=tens.sample()
print(result)

下面是以下给定代码的实现。

Python TensorFlow one hot categorical

Python TensorFlow one hot categorical

正如您在屏幕截图中看到的,输出将事件形状显示为 3,这意味着随机变量现在是一个向量。

阅读: Python NumPy Savetxt +示例

TensorFlow one hot 编码字符串

  • 在本节中,我们将讨论如何通过在 Python 中创建张量来获得输出中的字符串值。
  • 在本例中,我们已经在 tf.one_hot() 函数中设置了参数 on_value='x '和 off_value='y' 。一旦执行了这段代码,输出就会以一个热张量的形式显示字符串值。

举例:

import tensorflow as tf

tens=[1,3,6,5,4,7]
result= tf.one_hot(tens, depth=6, on_value='x', off_value='y')
tf.print(result)

下面是下面给出的代码的截图。

Python TensorFlow one hot encoding string

Python TensorFlow one hot encoding string

阅读: Python TensorFlow 截断法线

张量流一热一密

  • 在本节中,我们将讨论如何在 Python TensorFlow 中将一个热张量转换为稠密张量。
  • 通过使用切片和 tf.where() 函数,我们可以很容易地将 one_hot 张量转换为 dense。
  • 为了完成这项任务,我们将首先导入TF . compat . v1 . disable _ eager _ execution()模块来创建会话,然后我们将使用 tf.constant() 函数来创建张量索引。

语法:

下面是 tf.where() 函数的语法

tf.where
        (
         condition,
         x=None,
         y=None,
         name=None
        )

举例:

我们举个例子,检查一下如何在 Python 中将 one_hot 张量转换成 dense。

源代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
tens = tf.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
dense = tf.where(tf.equal(tens, 1))
indices = dense[:,1]
with tf.compat.v1.Session() as val:
    new_output=val.run(indices)
    print(new_output)

下面是以下代码的截图

Python TensorFlow one hot to dense

Python TensorFlow one hot to dense

阅读:将列表转换为张量张量流

TensorFlow text one 热编码

  • 在这一节中,我们将讨论如何用 Python 将文本编码成单词列表。
  • 为了执行这个特定的任务,我们将使用TF . keras . preprocessing . text . one _ hot()函数,这个函数用于将文本转换成单词列表。在这个例子中,我们将一个字符串作为输入,它将返回一个编码的整数列表。

语法:

让我们看看语法,了解一下 tf 的工作原理。keras . preprocessing . text . one _ hot()函数。

tf.keras.preprocessing.text.one_hot
                                   (
                                    input_text,
                                    n,
                                    filters='!"#$%&,
                                    lower=True,
                                    split=' ',
                                   )
  • 它由几个参数组成
    • input_text: 该参数表示将是字符串的输入文本。
    • n :定义输入文本的大小
    • 拆分:该参数用于分词。

举例:

让我们举一个例子,看看如何用 Python 将一个文本编码成一个单词列表。

源代码:

import tensorflow as tf

tens_text = "Python Programming"
new_output = tf.keras.preprocessing.text.one_hot(tens_text,n=3)
print(new_output)

下面是以下给定代码的实现

Python TensorFlow text one hot encoding

Python TensorFlow text one-hot encoding

阅读:张量流自定义损失函数

反转一个热编码张量流

  • 在本节中,我们将讨论如何在 Python TensorFlow 中反转独热编码张量。
  • 为了执行这个特定的任务,我们将通过使用 tf.one_hot() 函数来创建 one_hot 张量,然后我们将通过在 Python 中应用 tf.reverse() 函数来反转 one-hot 张量元素。
  • 此函数用于基于轴反转张量,它在 TensorFlow 包中可用。

语法:

我们来看一下语法,了解一下 tf.reverse() 函数的工作原理。

tf.reverse
          (
           tensor,
           axis,
           name=None
          ) 
  • 它由几个参数组成
    • 张量:该参数表示张量,必须是整数数据类型。
    • 轴:要反转的维度的索引。
    • name: 缺省情况下取 none 值,表示操作的名称。

举例:

让我们举个例子,看看如何在 Python 中反转一键编码张量。

源代码:

import tensorflow as tf

new_indi = [3, 1, 2]
new_val = 4
result=tf.one_hot(new_indi, new_val)
print(result)
b_reversed = tf.reverse(result, axis=[0, 1])
print(b_reversed)

你可以参考下面的截图。

reverse one hot encoding tensorflow in Python

reverse one hot encoding TensorFlow in Python

阅读: TensorFlow next_batch

张量流稀疏一热

  • 在本期节目中,我们将讨论如何在 Python TensorFlow 中使用 tf.sparse.to_dense() 函数。
  • 通过使用 tf.sparse.to_dense() 函数用于将稀疏张量转换为密集张量。

语法:

下面是 tf.sparse.to_dense()函数的语法。

tf.sparse.to_dense
                  (
                   sp_input,
                   default_value=None,
                   validate_indices=True,
                   name=None
                  )
  • 它由几个参数组成
    • sp_input: 该参数表示我们要操作的输入备用张量。
    • default_value :默认情况下不取值,用于设置索引。
    • validate _ indexes:该参数指定没有重新分区,它将检查条件,如果值为真,则它们按字典顺序排序。

举例:

让我们看一下例子,了解一下 tf.sparse.to_dense() 函数的工作原理。

源代码:

import tensorflow as tf

tens_input = tf.SparseTensor(
  dense_shape=[3, 6],
 values=[3, 4,5],
  indices =[[0, 1],
            [0, 3],
            [2, 0]])
result=tf.sparse.to_dense(tens_input).numpy()
print(result)

在下面给定的代码中我们已经导入了 TensorFlow 库,然后使用了 tf。SparseTensor() 函数,在该函数中,我们指定了密集的形状、值、索引作为参数。

下面是以下给定代码的实现。

Python TensorFlow sparse one hot

Python TensorFlow sparse one hot

正如你在截图中看到的,输出显示了稠密张量。

阅读: TensorFlow 稀疏张量

TensorFlow 多标签 one hot

  • 这里我们要讨论的是如何在 Python TensorFlow 中的 one_hot()函数中使用多标签。
  • 为了完成这个任务,我们将使用 TF . ragged . constant()函数,当我们在张量中有一个嵌套列表时,就会用到这个函数。
  • 接下来,我们将声明一个变量并指定 tf.one_hot()函数,在这个函数中,我们将指定深度作为一个参数。

语法:

下面是TF . ragged . constant()函数的语法。

tf.ragged.constant
                  (
                   pylist,
                   dtype=None,
                   ragged_rank=None,
                   inner_shape=None,
                   name=None,
                   row_splits_dtype=tf.dypes.int64
                  )

举例:

import tensorflow as tf
new_indices = tf.ragged.constant([[2, 3], [2], [1, 2]])

one_hot_tensor = tf.one_hot(new_indices, 5)
multi_labels = tf.reduce_max(one_hot_tensor, axis=1)
print(multi_labels)

下面是下面给出的代码的截图。

Python TensorFlow multilabel one hot

Python TensorFlow multilabel one hot

您可能也喜欢阅读以下 Python TensorFlow 教程。

在本 Python 教程中,我们学习了如何在 Python 中使用 TensorFlow one_hot 函数。此外,我们还讨论了以下主题。

  • TensorFlow one_hot 示例
  • 张量流 one_hot to index
  • TensorFlow one_hot 编码示例
  • TensorFlow one_hot axis
  • 张量流一热分类
  • TensorFlow one hot 编码字符串
  • 张量流一从热到密
  • 张量流数据集一次性编码
  • TensorFlow text one 热编码
  • 反向一热编码张量流
  • 张量流稀疏一热
  • TensorFlow 多标签 one hot

Bijay Kumar MVPBijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

posted @ 2024-11-02 15:54  绝不原创的飞龙  阅读(81)  评论(0)    收藏  举报