其他分享
首页 > 其他分享> > 2021-06-17

2021-06-17

作者:互联网

demo

import numpy as np
from sklearn.cluster import KMeans

读取文件,处理数据

def kmeansDemo():
file=open(“city.txt”,encoding=“utf-8”)
cityName=[]
cityData=[]
for line in file: # line 即为每行数据
items=line.split(",")
cityName.append(items[0])
cityData.append([float (items[i]) for i in range(1,len(items)) ])

实例化kmeans对象,调用方法对数据分组 ,标注序号

km=KMeans(n_clusters=5)
label=km.fit_predict(cityData)
# print(label)

expense=np.sum(km.cluster_centers_,axis=1)

dataCluster=[[],[],[],[],[]]


for i in range(len(cityName)):  # i 0-30
    #dataCluster用于保存各个小组的城市
    print("各消费水平:",expense[i])
    print("各城市名称:",cityName[i])
    dataCluster[label[i]].append(cityName[i])

return expense,dataCluster

输出统计结果

if name == ‘main’:
level,clusterName=kmeansDemo()
for i in range(len(clusterName)):
print(“消费水平:%.2f元:”%level[i])
print(clusterName[i])

app

from flask import Flask,render_template
from demo1 import keansdemo
app=Flask(name)

@app.route("/")
def index():
level,clusterName=keansdemo()
x=list(map(lambda a:"%.2f元"%a,level))
y=[ len(items) for items in clusterName ]
return render_template(“index.html”,x=x,y=y)

if name==“main”:
app.run(debug=True,port=8888)

index

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="static/js/echarts.min.js"></script>
</head>
<body>
    <div id="box" style="width: 700px;height: 550px;margin: 0 auto"></div>
    <script type="text/javascript">
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('box'),"dark");

        // 指定图表的配置项和数据
        var option = {
            title: {
                text:"31省消费水平统计",
                left:30
            },
            legend:{
                right:50,
                top:5
            },
            tooltip:{
                show:true,
                trigger:"axis"
            },
            xAxis: {
                type: 'category',
                data: {{ x | safe }}
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name:"各省数量",
                data: {{ y | safe }},
                barWidth:"60%",
                itemStyle:{
                    color:"orange",
                    barBorderRedius:[8,8,0,0]
                },
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.2)'
                },
            }]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    </script>
</body>
</html>

标签:06,dataCluster,17,clusterName,items,cityName,2021,print,name
来源: https://blog.csdn.net/qq_51474032/article/details/117980062