當前位置:首頁 » 編程語言 » 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中怎樣計算兩個向量的內積

這是從物理實踐中來,在物理計算中,經常會用到一個向量投影到另一個向量的方向,然後再乘以另一個向量的模.而且這樣的演算法表示固定的物理意義.由於經常會遇到這種問題,於是有人就這樣定義了內積,是為了便於書寫和直觀辨認.一個式子太長或太復雜就會給計算帶來很多的不便,定義了簡便的式子有助有從數學上理解物理.至於為什麼兩個向量的內積是常數,這就是定義,定義成常數罷了.內積的公式還是很簡單的,外積的就復雜得多.

熱點內容
資料庫的表怎麼看 發布:2024-04-19 10:43:52 瀏覽:562
空調壓縮機不響 發布:2024-04-19 10:42:22 瀏覽:50
linux下的ftp工具 發布:2024-04-19 10:42:15 瀏覽:929
橡膠圈壓縮 發布:2024-04-19 10:29:50 瀏覽:169
風雲tv密碼哪裡有 發布:2024-04-19 10:20:03 瀏覽:997
小翼管家如何查看密碼 發布:2024-04-19 09:57:31 瀏覽:156
怎麼緩存小品 發布:2024-04-19 09:49:02 瀏覽:410
在系統編程 發布:2024-04-19 08:54:55 瀏覽:235
visualstudio反編譯 發布:2024-04-19 08:44:46 瀏覽:320
ise怎麼配置晶元 發布:2024-04-19 08:27:31 瀏覽:997