clusterpython
❶ 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)才是不可变的