當前位置:首頁 » 編程語言 » clusterpython

clusterpython

發布時間: 2022-05-29 04:01:39

python scipy怎麼做層次聚類

Python機器學習包裡面的cluster提供了很多聚類演算法,其中ward_tree實現了凝聚層次聚類演算法。
但是沒有看明白ward_tree的返回值代表了什麼含義,遂決定尋找別的實現方式。
經過查找,發現scipy.cluster.hierarchy.fclusterdata能夠實現層次聚類。

❷ 如何使用python 連接kafka 並獲取數據

連接 kafka 的庫有兩種類型,一種是直接連接 kafka 的,存儲 offset 的事情要自己在客戶端完成。還有一種是先連接 zookeeper 然後再通過 zookeeper 獲取 kafka 的 brokers 信息, offset 存放在 zookeeper 上面,由 zookeeper 來協調。
我現在使用 samsa 這個 highlevel 庫
Procer示例
from kazoo.client import KazooClientfrom samsa.cluster import Clusterzookeeper = KazooClient()zookeeper.start()cluster = Cluster(zookeeper)topic = cluster.topics['topicname']topic.publish('msg')

** Consumer示例 **
from kazoo.client import KazooClientfrom samsa.cluster import Clusterzookeeper = KazooClient()zookeeper.start()cluster = Cluster(zookeeper)topic = cluster.topics['topicname']consumer = topic.subscribe('groupname')for msg in consumer:
print msg

Tip
consumer 必需在 procer 向 kafka 的 topic 裡面提交數據後才能連接,否則會出錯。
在 Kafka 中一個 consumer 需要指定 groupname , groue 中保存著 offset 等信息,新開啟一個 group 會從 offset 0 的位置重新開始獲取日誌。
kafka 的配置參數中有個 partition ,默認是 1 ,這個會對數據進行分區,如果多個 consumer 想連接同個 group 就必需要增加 partition , partition 只能大於 consumer 的數量,否則多出來的 consumer 將無法獲取到數據。

❸ 求幫忙寫一個python自動腳本完成以下步驟:

這個就用shell比較方便吧?
寫一個shell腳本,比如shell.sh
startcluster start xyz
tarcluster put xyz /path/to/file/or/dir /path/on/remote/server
starcluster sshmaster xyz
mpicc abc
mpirun abc
然後在python里直接調用shell.sh
import subprocess
p = subprocess.Popen('/home/username/shell.sh',stdout=subprocess.PIPE)
print p.stdout.readlines()
或者如果你願意的話,也可以直接用subprocess模塊來調用所有的命令。
比如:
p = subprocess.Popen('startcluster start xyz',stdout=subprocess.PIPE)
然後逐個看看每個步驟的返回信息。

❹ Python數據挖掘從哪些

一. 基於Python的數據挖掘 基本架構

1. matplotlib, 圖形化

2. pandas,數據挖掘的關鍵, 提供各種挖掘分析的演算法

3. numpy, 提供基本的統計
scipy, 提供各種數學公式

4. python common lib,python基本框架

二. 環境搭建
1. 安裝python

2. 安裝pip
pandas依賴的pip版本,最低是8.0.0。如果pip是8以下的版本,如7.2.1,需要升級pip.
命令是「python -m pip install -U pip」,這是windows版本。
Linux是」pip install -U pip「

通過命令「pip --version」, 可以查看pip版本號

3. 安裝pandas
命令「pip install pandas", 這是windows版本。

Linux平台可用
sudo apt-get install python-pandas

4. 安裝matplotlib
pip install matplotlib

三. 數據類型
pypython common type
string list tuple dict set
6鍾學列
list, tuple, string, unicode string, buffer object, xrange

pandas type
ndarray, series dateFrame

ndarray, 數組類型,新增原因:
list, tuple是基於指針+對象設計的。即list,tuple存儲的是void*指針,指針指向具體對象的數據。
因為是void*指針,所以二者可以存儲各種數據類型,即數據類型可以不統一。
雖然存儲豐富,但如果數據量過大時,即處理大數據時,有弊端。
1. 存儲空間大,浪費內存。因為存兩部分,指針+數據
2. 讀取慢,通過index,找到指針;基於指針,找到數據
所以在大數據處理時,新增ndarray,數字類型,類似C++ 數組。存儲相同,讀取、修改快捷。
別名:array, 有利於節省內存、提高CPU的計算時間,有豐富的處理函數

series,變長字典,
類似一維數組的對象;有數據和索引組成
新增原因:
dict是無序的,它的key和value存在映射關系。但key和value之間是不獨立的,存儲在一起。
如果需要對一項進行操作,會影響到另外一項。所以有了series, series的key和value是獨立的,獨立存儲。
series的key是定長有序的。通過series.key獲取整個索引, 通過series.values獲取所有values.
series的key,可以通過series.index.name,設置唯一的名稱。
series整體也可以設置唯一名稱,通過series.name

DataFrame:
1. 一個表格型的數據結構
2. 含有一組有序的列(類似於index)
3. 可以認為是,共享一個index的Series集合

data1={'name':['java', 'c', 'python'], 'year': [2,2,3]}
frame = pd.DataFrame(data1)

------------------------------------------------
四. 基本的數據分析流程:
1. 數據的獲取

2. 數據准備--規格化,建立各種索引index

3. 數據的顯示、描述,用於調試
如df.index, df.values, df.head(n), df.tail(n) df.describe

4. 數據的選擇
index獲取, 切片獲取, 行、列獲取, 矩形區域獲取

index獲取,df.row1 或者 df['row1']
行列,df.loc[行list, 列list], 如df.loc[0:1,['co1','col2'] ]
通過二位索引,取二維左上角,df.iloc[0,0],也可以列表 df.iloc[0:2,0:2],取前2行。

5. 簡單的統計與處理
統計平均值、最大值等

6. Grouping 分組
df.groupby(df.row1)

7. Merge合並
append追加,
contact連接, 包含append功能,也可以兩個不同的二維數據結構合並
join連接, sql連接,基於相同欄位連接,如 sql的where, a.row1 = b.row1

------------------------------------------------
五. 高級的數據處理與可視化:
1. 聚類分析
聚類是數據挖掘描述性任務和預測性任務的一個重要組成部分,它以相似性為基礎,
把相似的對象通過靜態分類,分成不同的組別和子集。
在python中,有很多第三方庫提供了聚類演算法。

聚類演算法有很多, 其中K-均值演算法,因為其簡單、快捷的特點,被廣泛使用。
基本原理是,
1. 查找某數據集的中心,
2. 使用均方差,計算距離。使得每一個數據點都收斂在一個組內;各個組是完全隔離的

案例:
>>> from pylab import *
>>> from scipy.cluster.vq import *
>>>
>>> list1=[88,64,96,85]
>>> list2=[92,99,95,94]
>>> list3=[91,87,99,95]
>>> list4 = [78,99,97,81]
>>> list5=[88,78,98,84]
>>> list6=[100,95,100,92]
>>> tempdate = (list1, list2, list3, list4, list5, list6)
>>>
>>> tempdate
([88, 64, 96, 85], [92, 99, 95, 94], [91, 87, 99, 95], [78, 99, 97, 81], [88, 78
, 98, 84], [100, 95, 100, 92])
>>> date = vstack(tempdate)
>>>
>>> date
array([[ 88, 64, 96, 85],
[ 92, 99, 95, 94],
[ 91, 87, 99, 95],
[ 78, 99, 97, 81],
[ 88, 78, 98, 84],
[100, 95, 100, 92]])

>>> centroids,abc=kmeans(date,2) #查找聚類中心,第二個參數是設置分N類,如5類,則為5

>>> centroids # 基於每列查找的中心點,可能是平均值
array([[88, 71, 97, 84],
[90, 95, 97, 90]])
>>>
>>> result,cde=vq(date,centroids) #對數據集,基於聚類中心進行分類
>>> result
array([0, 1, 1, 1, 0, 1])

2. 繪圖基礎
python描繪庫,包含兩部分,
繪圖api, matplotlib提供各種描繪介面。
集成庫,pylab(包含numpy和matplotlib中的常用方法),描繪更快捷、方便。

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0,10)

plt.plot(t, t+2)
plt.plot(t,t, 'o', t,t+2, t,t**2, 'o') #(x,y)一組,默認是折線;『o'是散點,
plt.bar(t,t**2) # 柱狀圖
plt.show()

--------------------
import pylab as pl
t = np.arange(0,10)
plt.plot(t, t+2)
plt.show()

3. matplotlib圖像屬性控制
色彩、樣式
名稱: 圖、橫、縱軸,
plt.title('philip\'s python plot')
plt.xlabel('date')
plt.ylabel('value')
其他: pl.figure(figsize=(8,6),dpi=100)
pl.plot(x,y, color='red', linewidth=3, lable='line1')
pl.legend(loc='upper left')

子圖
pl.subplot(211) # 整體圖片,可以分為二維部分;
#第一個是圖的行,第二個是列;第三個是index, 從左上開始0遍歷 當前行,再下一行。
#如果是2位數,如11,需要『,』
axes(left, bottom, width, height) # 參數取值范圍是(0,1), left,是到左邊的距離,bottom是到下面的距離

4. pandas作圖
Series、DataFrame支持直接描繪,封裝了調用matplotlib的介面,如
series.close.plot()
df.close.plot() #具體參數類似matplotlib普通介面

屬性控制
類似matplotlib普通介面,修改各種圖片的類型,柱形圖、折線等

--------common-----------------
list, tuple, dict

--------numpy-----------------
ndarray, Series, DataFrame

❺ 減法聚類如何用Python實現

下面是一個k-means聚類演算法在python2.7.5上面的具體實現,你需要先安裝Numpy和Matplotlib:
from numpy import *
import time
import matplotlib.pyplot as plt

# calculate Euclidean distance
def euclDistance(vector1, vector2):
return sqrt(sum(power(vector2 - vector1, 2)))
# init centroids with random samples
def initCentroids(dataSet, k):
numSamples, dim = dataSet.shape
centroids = zeros((k, dim))
for i in range(k):
index = int(random.uniform(0, numSamples))
centroids[i, :] = dataSet[index, :]
return centroids
# k-means cluster
def kmeans(dataSet, k):
numSamples = dataSet.shape[0]
# first column stores which cluster this sample belongs to,
# second column stores the error between this sample and its centroid
clusterAssment = mat(zeros((numSamples, 2)))
clusterChanged = True
## step 1: init centroids
centroids = initCentroids(dataSet, k)
while clusterChanged:
clusterChanged = False
## for each sample
for i in xrange(numSamples):
minDist = 100000.0
minIndex = 0
## for each centroid
## step 2: find the centroid who is closest
for j in range(k):
distance = euclDistance(centroids[j, :], dataSet[i, :])
if distance < minDist:
minDist = distance
minIndex = j

## step 3: update its cluster
if clusterAssment[i, 0] != minIndex:
clusterChanged = True
clusterAssment[i, :] = minIndex, minDist**2
## step 4: update centroids
for j in range(k):
pointsInCluster = dataSet[nonzero(clusterAssment[:, 0].A == j)[0]]
centroids[j, :] = mean(pointsInCluster, axis = 0)
print 'Congratulations, cluster complete!'
return centroids, clusterAssment
# show your cluster only available with 2-D data
def showCluster(dataSet, k, centroids, clusterAssment):
numSamples, dim = dataSet.shape
if dim != 2:
print "Sorry! I can not draw because the dimension of your data is not 2!"
return 1
mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '<r', 'pr']
if k > len(mark):
print "Sorry! Your k is too large! please contact Zouxy"
return 1
# draw all samples
for i in xrange(numSamples):
markIndex = int(clusterAssment[i, 0])
plt.plot(dataSet[i, 0], dataSet[i, 1], mark[markIndex])
mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '<b', 'pb']
# draw the centroids
for i in range(k):
plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize = 12)
plt.show()

❻ nlp和python有什麼關系

nlp的很多工具都有python版本
nlp是研究領域,python是語言工具。

❼ python2.7安裝rediscluster模塊報錯,求助

1如果是在windows上請下載PYTHON2.6的安裝程序,然後直接運行即可安裝完成。2安裝完成後需要到系統的環境變數處設置PYTHON的環境變數具體設置方法如圖3在命令行鍵入python遍可以進入PYTHON的交互編程界面。如果需要在LINUX上安裝以CENTOS為例:1,用ROOT方式登陸到系統輸入yuminstallpython即可完成安裝。2運行SHELL輸入PYTHON即可運行。3執行在shell中輸入pythonany.py即可

❽ 用python K值聚類識別圖片主要顏色的程序,演算法python代碼已經有了

難得被人求助一次, 這個必須回答一下. 不過你的需求確實沒有寫得太清楚. 根據k值演算法出來的是主要顏色有三個, 所以我把三個顏色都打在記事本里了. 如果和你的需求有誤, 請自行解決吧.


另外這里需要用到numpy的庫, 希望你裝了, 如果沒裝, 這個直接安裝也比較麻煩, 可以看一下portablepython的綠色版。


代碼如下:


#-*-coding:utf-8-*-
importImage
importrandom
importnumpy
classCluster(object):
def__init__(self):
self.pixels=[]
self.centroid=None
defaddPoint(self,pixel):
self.pixels.append(pixel)
defsetNewCentroid(self):
R=[colour[0]forcolourinself.pixels]
G=[colour[1]forcolourinself.pixels]
B=[colour[2]forcolourinself.pixels]
R=sum(R)/len(R)
G=sum(G)/len(G)
B=sum(B)/len(B)
self.centroid=(R,G,B)
self.pixels=[]
returnself.centroid
classKmeans(object):
def__init__(self,k=3,max_iterations=5,min_distance=5.0,size=200):
self.k=k
self.max_iterations=max_iterations
self.min_distance=min_distance
self.size=(size,size)
defrun(self,image):
self.image=image
self.image.thumbnail(self.size)
self.pixels=numpy.array(image.getdata(),dtype=numpy.uint8)
self.clusters=[Noneforiinrange(self.k)]
self.oldClusters=None
randomPixels=random.sample(self.pixels,self.k)
foridxinrange(self.k):
self.clusters[idx]=Cluster()
self.clusters[idx].centroid=randomPixels[idx]
iterations=0
whileself.shouldExit(iterations)isFalse:
self.oldClusters=[cluster.centroidforclusterinself.clusters]
printiterations
forpixelinself.pixels:
self.assignClusters(pixel)
forclusterinself.clusters:
cluster.setNewCentroid()
iterations+=1
return[cluster.centroidforclusterinself.clusters]
defassignClusters(self,pixel):
shortest=float('Inf')
forclusterinself.clusters:
distance=self.calcDistance(cluster.centroid,pixel)
ifdistance<shortest:
shortest=distance
nearest=cluster
nearest.addPoint(pixel)
defcalcDistance(self,a,b):
result=numpy.sqrt(sum((a-b)**2))
returnresult
defshouldExit(self,iterations):
ifself.oldClustersisNone:
returnFalse
foridxinrange(self.k):
dist=self.calcDistance(
numpy.array(self.clusters[idx].centroid),
numpy.array(self.oldClusters[idx])
)
ifdist<self.min_distance:
returnTrue
ifiterations<=self.max_iterations:
returnFalse
returnTrue
#############################################
#
defshowImage(self):
self.image.show()
defshowCentroidColours(self):
forclusterinself.clusters:
image=Image.new("RGB",(200,200),cluster.centroid)
image.show()
defshowClustering(self):
localPixels=[None]*len(self.image.getdata())
foridx,pixelinenumerate(self.pixels):
shortest=float('Inf')
forclusterinself.clusters:
distance=self.calcDistance(
cluster.centroid,
pixel
)
ifdistance<shortest:
shortest=distance
nearest=cluster
localPixels[idx]=nearest.centroid
w,h=self.image.size
localPixels=numpy.asarray(localPixels)
.astype('uint8')
.reshape((h,w,3))
colourMap=Image.fromarray(localPixels)
colourMap.show()

if__name__=="__main__":
fromPILimportImage
importos

k_image=Kmeans()
path=r'.\pics\'
fp=open('file_color.txt','w')
forfilenameinos.listdir(path):
printpath+filename
try:
color=k_image.run(Image.open(path+filename))
fp.write('Thecolorof'+filename+'is'+str(color)+' ')
except:
print"Thisfileformatisnotsupport"
fp.close()

❾ 關於python

獲取到的nonzero(clusterAssment[:,0]元素的一個屬性

❿ fcluster函數 生成結果怎麼查看 python

python. 如果只是研究演算法,集合(set)是可以變的,它是一個無序不重復元素集 元組(touple)才是不可變的

熱點內容
android改變字體 發布:2025-02-12 09:50:22 瀏覽:373
如何在本地布置ssh伺服器 發布:2025-02-12 09:48:50 瀏覽:333
本機搭建伺服器有用嗎 發布:2025-02-12 09:48:14 瀏覽:234
安卓手機如何打開7x文件 發布:2025-02-12 09:43:02 瀏覽:485
c語言等號 發布:2025-02-12 09:39:02 瀏覽:169
ug編程培訓要多少錢 發布:2025-02-12 09:38:27 瀏覽:620
小黃車的密碼怎麼打開 發布:2025-02-12 09:38:26 瀏覽:70
存儲時4k 發布:2025-02-12 09:33:31 瀏覽:87
stn資料庫 發布:2025-02-12 09:32:31 瀏覽:602
iossocket編程 發布:2025-02-12 09:32:20 瀏覽:899