当前位置:首页 » 编程语言 » python向量加减

python向量加减

发布时间: 2022-08-07 17:52:19

python的例题解法

不看numpy一维数组的话,就是len相同的一个列表相同索引值相加吧。

x1=[1,2,3]

x2=[4,5,6]

x3=[]

defadd():

foriinrange(0,len(x1)):

x3.append(x1[i]+x2[i])

returnx3

print(add())

㈡ python3.6如何进行变量之间的加减

input() 返回的是键盘输入的一个字符串,需要转换成数值类型然后再相加,可以用 int() 将字符串转换成整型数值 。

例如:

A=int(input())
B=int(input())
C=A+B
print(C)

#或者

A=input()
B=input()
C=int(A)+int(B)
print(C)

㈢ python多个向量怎么聚合成一个向量

将向量相加,然后除以总数,得出中心点,过来另一个向量,计算距离就可以了。

如果你想说的是KMeans这种聚类方法的话,简单给你介绍一下:

类别

聚类算法 非监督学习算法

参数

k值 : 分成的类的数量
距离公式 : 计算距离
阀值 : 距离大于阀值要重新计算

算法详细

step 1 : 随机选取k个点作为簇团中心点
step 2 : 将元数据中各数据划分到距离最近的一个中心点所对应的簇团中
step 3 : 重新计算出各簇团的中心点,再将元数据中各数据划分到距离最近的一
个中心点所对应的簇团中
step 4 : 重新计算中心点,计算中心点与前回中心点的距离,如果距离大于阀值,
跳到step3,否则结束

㈣ 使用Python编写一个三维向量,实现向量的加法减法,点乘叉乘

#--coding:gb2312--

classvector3:

def__init__(self,x_=0,y_=0,z_=0):#构造函数

self.x=x_

self.y=y_

self.z=z_

def__add__(self,obj):#重载+作为加号

returnvector3(self.x+obj.x,self.y+obj.y,self.z+obj.z)

def__sub__(self,obj):#重载-作为减号

returnvector3(self.x-obj.x,self.y-obj.y,self.z-obj.z)

def__mul__(self,obj):#重载*作为点乘

returnvector3(self.x*obj.x,self.y*obj.y,self.z*obj.z)

def__pow__(self,obj):#重载**作为叉乘。不好,偏离了常理上的意义,可以考虑重载其他符号,或者直接写函数。

returnvector3(self.y*obj.z-obj.y*self.z,self.z*obj.x-self.x*obj.z,self.x*obj.y-obj.x*self.y)

def__str__(self):#供print打印的字符串

returnstr(self.x)+','+str(self.y)+','+str(self.z)

v1=vector3(1,2,3)

v2=vector3(0,1,2)

printv1+v2

printv1-v2

printv1*v2

printv1**v2

结果:

㈤ python numpy 向量

importnumpyasnp

a=[1,2,3]
b=[4,5,6]
r=np.vstack((a,b)).T
print(r)
>>>[[1,4]
[2,5]
[3,6]]

㈥ Python 里面向量该怎样运算

首先要写上这一句:
from numpy import *
(写上这句的前提也得你已经安了numpy)
(1) 定义一个零向量(4维):
>>>a=zeros(4)
>>>a
array([0.,0.,0.,0.])
定义一个List:
b=[1,2,3,4]
(2)向量可直接与List相加:
>>>c=a+b
>>>c
array([1.,2.,3.,4.])

(3)要给向量里每个元素都乘以同一个数:
>>>d=b*[3]
或者:
>>>c=3
>>>d=b*[c]
>>>d
array([3.,6.,9.,12.])

而不能是d=b*3,即要乘的这个数字得是个List形式
(4)两个向量相除(对应元素相除):
>>>e=[3,2,3,4]
>>>f=d/e
>>>f
array([1.,3.,3.,3.])

㈦ python类中两个列表实例如何相加或相减

import numpy

a = [1, 2, 3, 4]

b = [5, 6, 7, 8]

a_array = numpy.array(a)

b_array = numpy.array(b)

c_array = a_array + b_array

d_array = a_array - b_array

print c_array

print d_array

(7)python向量加减扩展阅读:

算术运算结果的数字类型与运算数的类型有关。进行除法(/)运算时,不管商为整数还是浮点数,运算结果始终为浮点数。要得到整型的商,需要用双斜杠(//)做整除,且除数必须是整型的。对于其他的运算,只要任一运算数为浮点数,运算结果就是浮点数。Python算术运算的基础使用方法如下所示。

num_int = 4

num_float = 4.0

print('整数与浮点数的和为:', num_int + num_float)

#Out[1]: 整数与浮点数的和为:8.0

print('整数与浮点数的差为:', num_int - num_float)

#Out[2]: 整数与浮点数的差为: 0.0

print('整数与浮点数的积为:', num_int * num_float)

#Out[3]: 整数与浮点数的积为:16.0

print('浮点数与整数的商为:', num_float / num_int)

#Out[4]: 浮点数与整数的商为:1.0

print('浮点数对整数取模结果为:', num_float % num_int)

#Out[5]: 浮点数对整数取模结果为: 0.0

print('浮点数的整数次幂为:', num_float ** num_int)

#Out[6]: 浮点数的整数次幂为:256.0

㈧ python 如何对intvar做加减乘除

python做加减乘除功能上比较容易实现。
就是做计算器的界面,这个选择比较多。
tk,wxpython,Qt都可以
tk内置,不需要另外安装库,简洁。就是看起来,比较windows。
wxpython库比较成熟了,各种样式很多。
qt,有界面编辑很方便。我没用过。
我觉得wxpython比较好,demo中的样式就很多了。
具体实现的话:用wxpython做一个计算器的界面,有一个输入框。然后将输入的数字和加减乘除,str=“32*32-543/543+25” 直接eval(str)成表达式,就知道结果了。

㈨ python gensim怎么用word2vect

词向量(word2vec)原始的代码是C写的,python也有对应的版本,被集成在一个非常牛逼的框架gensim中。

我在自己的开源语义网络项目graph-mind(其实是我自己写的小玩具)中使用了这些功能,大家可以直接用我在上面做的进一步的封装傻瓜式地完成一些操作,下面分享调用方法和一些code上的心得。

1.一些类成员变量:

[python]view plain

  • def__init__(self,modelPath,_size=100,_window=5,_minCount=1,_workers=multiprocessing.cpu_count()):

  • self.modelPath=modelPath

  • self._size=_size

  • self._window=_window

  • self._minCount=_minCount

  • self._workers=_workers

  • modelPath是word2vec训练模型的磁盘存储文件(model在内存中总是不踏实),_size是词向量的维度,_window是词向量训练时的上下文扫描窗口大小,后面那个不知道,按默认来,_workers是训练的进程数(需要更精准的解释,请指正),默认是当前运行机器的处理器核数。这些参数先记住就可以了。

    2.初始化并首次训练word2vec模型

    完成这个功能的核心函数是initTrainWord2VecModel,传入两个参数:corpusFilePath和safe_model,分别代表训练语料的路径和是否选择“安全模式”进行初次训练。关于这个“安全模式”后面会讲,先看代码:

    [python]view plain

  • definitTrainWord2VecModel(self,corpusFilePath,safe_model=False):

  • '''''

  • initandtrainaneww2vmodel

  • (,

  • aboutsoft_model:

  • ifsafe_modelistrue,,

  • andthiscankeeptheusageofos'smemorysafebutslowly.

  • andifsafe_modelisfalse,

  • .)

  • '''

  • extraSegOpt().reLoadEncoding()

  • fileType=localFileOptUnit.checkFileState(corpusFilePath)

  • iffileType==u'error':

  • warnings.warn('loadfileerror!')

  • returnNone

  • else:

  • model=None

  • iffileType==u'opened':

  • print('trainingmodelfromsingleFile!')

  • model=Word2Vec(LineSentence(corpusFilePath),size=self._size,window=self._window,min_count=self._minCount,workers=self._workers)

  • eliffileType==u'file':

  • corpusFile=open(corpusFilePath,u'r')

  • print('trainingmodelfromsingleFile!')

  • model=Word2Vec(LineSentence(corpusFile),size=self._size,window=self._window,min_count=self._minCount,workers=self._workers)

  • eliffileType==u'directory':

  • corpusFiles=localFileOptUnit.listAllFileInDirectory(corpusFilePath)

  • print('!')

  • ifsafe_model==True:

  • model=Word2Vec(LineSentence(corpusFiles[0]),size=self._size,window=self._window,min_count=self._minCount,workers=self._workers)

  • forfileincorpusFiles[1:len(corpusFiles)]:

  • model=self.updateW2VModelUnit(model,file)

  • else:

  • sentences=self.loadSetencesFromFiles(corpusFiles)

  • model=Word2Vec(sentences,size=self._size,window=self._window,min_count=self._minCount,workers=self._workers)

  • eliffileType==u'other':

  • #TODOaddsentenceslistdirectly

  • pass

  • model.save(self.modelPath)

  • model.init_sims()

  • print('procingword2vecmodel...ok!')

  • returnmodel

  • 首先是一些杂七杂八的,判断一下输入文件路径下访问结果的类型,根据不同的类型做出不同的文件处理反应,这个大家应该能看懂,以corpusFilePath为一个已经打开的file对象为例,创建word2vec model的代码为:

    [python]view plain

  • model=Word2Vec(LineSentence(corpusFilePath),size=self._size,window=self._window,min_count=self._minCount,workers=self._workers)

  • 其实就是这么简单,但是为了代码健壮一些,就变成了上面那么长。问题是在面对一个路径下的许多训练文档且数目巨大的时候,一次性载入内存可能不太靠谱了(没有细研究gensim在Word2Vec构造方法中有没有考虑这个问题,只是一种习惯性的警惕),于是我设定了一个参数safe_model用于判断初始训练是否开启“安全模式”,所谓安全模式,就是最初只载入一篇语料的内容,后面的初始训练文档通过增量式学习的方式,更新到原先的model中。

    上面的代码里,corpusFilePath可以传入一个已经打开的file对象,或是一个单个文件的地址,或一个文件夹的路径,通过函数checkFileState已经做了类型的判断。另外一个函数是updateW2VModelUnit,用于增量式训练更新w2v的model,下面会具体介绍。loadSetencesFromFiles函数用于载入一个文件夹中全部语料的所有句子,这个在源代码里有,很简单,哥就不多说了。

    3.增量式训练更新word2vec模型

    增量式训练w2v模型,上面提到了一个这么做的原因:避免把全部的训练语料一次性载入到内存中。另一个原因是为了应对语料随时增加的情况。gensim当然给出了这样的solution,调用如下:

    [python]view plain

  • defupdateW2VModelUnit(self,model,corpusSingleFilePath):

  • '''''

  • (onlycanbeasingleFile)

  • '''

  • fileType=localFileOptUnit.checkFileState(corpusSingleFilePath)

  • iffileType==u'directory':

  • warnings.warn('cannotdealadirectory!')

  • returnmodel

  • iffileType==u'opened':

  • trainedWordCount=model.train(LineSentence(corpusSingleFilePath))

  • print('updatemodel,updatewordsnumis:'+trainedWordCount)

  • eliffileType==u'file':

  • corpusSingleFile=open(corpusSingleFilePath,u'r')

  • trainedWordCount=model.train(LineSentence(corpusSingleFile))

  • print('updatemodel,updatewordsnumis:'+trainedWordCount)

  • else:

  • #TODOaddsentenceslistdirectly(sameaslastfunction)

  • pass

  • returnmodel

  • 简单检查文件type之后,调用model对象的train方法就可以实现对model的更新,这个方法传入的是新语料的sentences,会返回模型中新增词汇的数量。函数全部执行完后,return更新后的model,源代码中在这个函数下面有能够处理多类文件参数(同2)的增强方法,这里就不多介绍了。

    4.各种基础查询

    当你确定model已经训练完成,不会再更新的时候,可以对model进行锁定,并且据说是预载了相似度矩阵能够提高后面的查询速度,但是你的model从此以后就read only了。

    [python]view plain

  • deffinishTrainModel(self,modelFilePath=None):

  • '''''

  • warning:afterthis,themodelisread-only(can'tbeupdate)

  • '''

  • ifmodelFilePath==None:

  • modelFilePath=self.modelPath

  • model=self.loadModelfromFile(modelFilePath)

  • model.init_sims(replace=True)

  • 可以看到,所谓的锁定模型方法,就是init_sims,并且把里面的replace参数设定为True。

    然后是一些word2vec模型的查询方法:

    [python]view plain

  • defgetWordVec(self,model,wordStr):

  • '''''

  • gettheword'

  • '''

  • returnmodel[wordStr]

  • [python]view plain

  • defqueryMostSimilarWordVec(self,model,wordStr,topN=20):

  • '''''

  • return2-dimList[0]isword[1]isdouble-prob

  • '''

  • similarPairList=model.most_similar(wordStr.decode('utf-8'),topn=topN)

  • returnsimilarPairList

  • [python]view plain

  • defculSimBtwWordVecs(self,model,wordStr1,wordStr2):

  • '''''

  • returndouble-prob

  • '''

  • similarValue=model.similarity(wordStr1.decode('utf-8'),wordStr2.decode('utf-8'))

  • returnsimilarValue

  • 上述方法都很简单,基本上一行解决,在源代码中,各个函数下面依然是配套了相应的model文件处理版的函数。其中,getWordVec是得到查询词的word2vec词向量本身,打印出来是一个纯数字的array;queryMostSimilarWordVec是得到与查询词关联度最高的N个词以及对应的相似度,返回是一个二维list(注释里面写的蛮清楚);culSimBtwWordVecs是得到两个给定词的相似度值,直接返回double值。

    5.Word2Vec词向量的计算

    研究过w2v理论的童鞋肯定知道词向量是可以做加减计算的,基于这个性质,gensim给出了相应的方法,调用如下:

    [python]view plain

  • (self,model,posWordStrList,negWordStrList,topN=20):

  • '''''

  • pos-neg

  • return2-dimList[0]isword[1]isdouble-prob

  • '''

  • posWordList=[]

  • negWordList=[]

  • forwordStrinposWordStrList:

  • posWordList.append(wordStr.decode('utf-8'))

  • forwordStrinnegWordStrList:

  • negWordList.append(wordStr.decode('utf-8'))

  • pnSimilarPairList=model.most_similar(positive=posWordList,negative=negWordList,topn=topN)

  • returnpnSimilarPairList

  • 由于用的是py27,所以之前对传入的词列表数据进行编码过滤,这里面posWordList可以认为是对结果产生正能量的词集,negWordList则是对结果产生负能量的词集,同时送入most_similar方法,在设定return答案的topN,得到的返回结果形式同4中的queryMostSimilarWordVec函数,大家可以这样数学地理解这个操作:

    下面一个操作是我自创的,假设我想用上面词向量topN“词-关联度”的形式展现两个词或两组词之间的关联,我是这么做的:

    [python]view plain

  • (self,model,wordStrList1,wordStrList2,topN_rev=20,topN=20):

  • '''''

  • -wordListandtag-wordList

  • first,usethetag-wordListasneg-wordListtogettherev-wordList,

  • thenusethescr-wordListandtherev-wordListasthenewsrc-tag-wordList

  • topN_revistopNofrev-

  • '''

  • srcWordList=[]

  • tagWordList=[]

  • srcWordList.extend(wordStr.decode('utf-8')forwordStrinwordStrList1)

  • tagWordList.extend(wordStr.decode('utf-8')forwordStrinwordStrList2)

  • revSimilarPairList=self.queryMSimilarVecswithPosNeg(model,[],tagWordList,topN_rev)

  • revWordList=[]

  • revWordList.extend(pair[0].decode('utf-8')forpairinrevSimilarPairList)

  • stSimilarPairList=self.queryMSimilarVecswithPosNeg(model,srcWordList,revWordList,topN)

  • returnstSimilarPairList

  • 这个操作的思路就是,首先用两组词中的一组作为negWordList,传入上面的queryMSimilarVecswithPosNeg函数,得到topN一组的中转词,在使用这些中转词与原先的另一组词进行queryMSimilarVecswithPosNeg操作,很容易理解,第一步得到的是一组词作为negWordList的反向结果,再通过这个反向结果与另一组词得到“负负得正”的效果。这样就可以通过一组topN的“词-关联度”配对List表示两组词之间的关系。

㈩ Python中怎样计算两个向量的内积

这是从物理实践中来,在物理计算中,经常会用到一个向量投影到另一个向量的方向,然后再乘以另一个向量的模.而且这样的算法表示固定的物理意义.由于经常会遇到这种问题,于是有人就这样定义了内积,是为了便于书写和直观辨认.一个式子太长或太复杂就会给计算带来很多的不便,定义了简便的式子有助有从数学上理解物理.至于为什么两个向量的内积是常数,这就是定义,定义成常数罢了.内积的公式还是很简单的,外积的就复杂得多.

热点内容
zxingandroid简化 发布:2024-05-02 17:47:53 浏览:189
贵州银行卡查询密码是什么 发布:2024-05-02 17:47:17 浏览:119
飓风算法没用 发布:2024-05-02 17:41:41 浏览:350
android铃声设置 发布:2024-05-02 17:40:01 浏览:485
php日记本 发布:2024-05-02 17:28:22 浏览:850
msc拒绝访问 发布:2024-05-02 17:19:09 浏览:122
php函数漏洞 发布:2024-05-02 17:15:26 浏览:963
linux访问localhost 发布:2024-05-02 17:04:11 浏览:880
剑三自动任务脚本 发布:2024-05-02 16:59:42 浏览:526
哪里有java视频教程 发布:2024-05-02 16:59:31 浏览:346