29、数据可视化与手写数字识别:D3库与机器学习的应用

数据可视化与手写数字识别:D3库与机器学习的应用

1. 嵌入JavaScript D3库到IPython Notebook

在IPython Notebook中,我们可以借助JavaScript的D3库来进一步扩展数据展示能力。例如,通过以下代码可以展示一个代表人口数据的图表:

display(Javascript(myTemplate.render(
    data=states.sort_values(['POPESTIMATE2022'], ascending=False)
    [:5].itertuples()
)))

再次运行 render() 函数,就能得到一个类似图11 - 6的聚类条形图,该图展示了2020 - 2022年人口最多的五个州的人口情况。

1.1 等值区域地图(Choropleth Maps)

等值区域地图是一种非常复杂的地理数据表示方式,它将地理区域划分为不同颜色的部分,颜色和区域边界本身就是数据的一种表示。这种表示方式对于展示人口统计或经济信息的数据分析结果非常有用,尤其适用于与地理分布相关的数据。

等值区域地图的表示基于一种名为TopoJSON的文件,这种文件包含了表示等值区域地图的所有内部信息,例如美国地图。可以在U.S. Atlas TopoJSON(https://github.com/mbostock/us - atlas)找到相关材料,网上也有很多关于它的文献。

下面是在IPython Notebook中创建等值区域地图的详细步骤:
1. 导入必要的JavaScript库 :除了D3库,还需要导入queue和TopoJSON库。

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/queue - async/1.0.7/queue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.19/topojson.min.js"></script>

使用 require.config() 配置库的路径:

%%javascript
require.config({
    paths: {
        d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min',
        queue: '//cdnjs.cloudflare.com/ajax/libs/queue - async/1.0.7/queue.min',
        topojson: '//cdnjs.cloudflare.com/ajax/libs/topojson/1.6.19/topojson.min'
    }
});
  1. 设置CSS样式和HTML元素
from IPython.display import display, Javascript, HTML
display(HTML("""
<style>
.counties {
    fill: none;
}
.states {
    fill: none;
    stroke: #fff;
    stroke - linejoin: round;
}
.q0 - 9 { fill:rgb(247,251,255); }
.q1 - 9 { fill:rgb(222,235,247); }
.q2 - 9 { fill:rgb(198,219,239); }
.q3 - 9 { fill:rgb(158,202,225); }
.q4 - 9 { fill:rgb(107,174,214); }
.q5 - 9 { fill:rgb(66,146,198); }
.q6 - 9 { fill:rgb(33,113,181); }
.q7 - 9 { fill:rgb(8,81,156); }
.q8 - 9 { fill:rgb(8,48,107); }
</style>
<div id="choropleth" />
"""))
  1. 定义模板
import jinja2
choropleth = jinja2.Template("""
require(["d3","queue","topojson"], function(d3,queue,topojson){
    d3.select("#choropleth svg").remove()
    var width = 960,
        height = 600;
    var rateById = d3.map();
    var quantize = d3.scale.quantize()
      .domain([0, .15])
      .range(d3.range(9).map(function(i) { return "q" + i + "-9"; }));
    var projection = d3.geo.albersUsa()
      .scale(1280)
      .translate([width / 2, height / 2]);
    var path = d3.geo.path()
      .projection(projection);
    var svg = d3.select("#choropleth").append("svg")
      .attr("width", width)
      .attr("height", height);
    queue()
      .defer(d3.json, "us.json")
      .defer(d3.tsv, "unemployment.tsv", function(d) { rateById.set(d.id, +d.rate); })
      .await(ready);
    function ready(error, us) {
        if (error) throw error;
        svg.append("g")
          .attr("class", "counties")
          .selectAll("path")
          .data(topojson.feature(us, us.objects.counties).features)
          .enter().append("path")
          .attr("class", function(d) { return quantize(rateById.get(d.id)); })
          .attr("d", path);
        svg.append("path")
          .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a!== b; }))
          .attr("class", "states")
          .attr("d", path);
    }
});
""");
  1. 渲染图表
display(Javascript(choropleth.render()))

1.2 2022年美国人口等值区域地图

现在我们可以结合从美国人口普查局提取的人口数据和等值区域地图的创建方法,来展示美国各县的人口情况。人口越多的县颜色越深,人口非常少的县颜色则趋近于白色。

具体步骤如下:
1. 提取各县人口数据

pop2022_by_county = pop2022[pop2022.SUMLEV == 50]
  1. 获取县的ID和名称对应关系
USJSONnames = pd.read_table('us - county - names.tsv')
  1. 重构数据
counties = pop2022_by_county[['STATE','COUNTY','POPESTIMATE2022']]
counties.is_copy = False
counties['id'] = counties['STATE'].str.lstrip('0') + "" + counties['COUNTY']
del counties['STATE']
del counties['COUNTY']
counties.columns = ['pop','id']
counties = counties[['id','pop']]
counties.to_csv('population.csv')
  1. 重写HTML内容
from IPython.display import display, Javascript, HTML
display(HTML("""
<style>
.counties {
    fill: none;
}
.states {
    fill: none;
    stroke: #fff;
    stroke - linejoin: round;
}
.q0 - 9 { fill:rgb(247,251,255); }
.q1 - 9 { fill:rgb(222,235,247); }
.q2 - 9 { fill:rgb(198,219,239); }
.q3 - 9 { fill:rgb(158,202,225); }
.q4 - 9 { fill:rgb(107,174,214); }
.q5 - 9 { fill:rgb(66,146,198); }
.q6 - 9 { fill:rgb(33,113,181); }
.q7 - 9 { fill:rgb(8,81,156); }
.q8 - 9 { fill:rgb(8,48,107); }
</style>
<div id="choropleth2" />
"""))
  1. 定义新模板
choropleth2 = jinja2.Template("""
require(["d3","queue","topojson"], function(d3,queue,topojson){
    var data = []
    d3.select("#choropleth2 svg").remove()
    var width = 960,
        height = 600;
    var rateById = d3.map();
    var quantize = d3.scale.quantize()
      .domain([0, 1000000])
      .range(d3.range(9).map(function(i) { return "q" + i + "-9"; }));
    var projection = d3.geo.albersUsa()
      .scale(1280)
      .translate([width / 2, height / 2]);
    var path = d3.geo.path()
      .projection(projection);
    var svg = d3.select("#choropleth2").append("svg")
      .attr("width", width)
      .attr("height", height);
    queue()
      .defer(d3.json, "us.json")
      .defer(d3.csv,"population.csv", function(d) { rateById.set(d.id, +d.pop); })
      .await(ready);
    function ready(error, us) {
        if (error) throw error;
        svg.append("g")
          .attr("class", "counties")
          .selectAll("path")
          .data(topojson.feature(us, us.objects.counties).features)
          .enter().append("path")
          .attr("class", function(d) { return quantize(rateById.get(d.id)); })
          .attr("d", path);
        svg.append("path")
          .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a!== b; }))
          .attr("class", "states")
          .attr("d", path);
    }
});
""");
  1. 渲染图表
display(Javascript(choropleth2.render()))

2. 手写数字识别

数据的分析和分类不仅仅局限于数字和字符串,图像和声音也可以进行分析和分类。在这部分,我们将学习手写数字识别。

2.1 手写数字识别的背景

手写文本识别问题可以追溯到早期需要识别手写文档中单个字符的自动机器,例如邮局信件上的邮政编码识别。光学字符识别(OCR)软件也是手写识别的一个重要应用场景。早在20世纪20年代,Emanuel Goldberg就开始研究这个问题,并提出统计方法是一个最佳选择。

2.2 使用scikit - learn识别手写数字

scikit - learn库提供了一种不同的数据分析方式,它可以处理与数值、字符串、图像和声音相关的数据。在手写数字识别问题中,我们使用支持向量分类(SVC)技术。

2.2.1 准备工作
  1. 导入必要的库和创建估计器
from sklearn import svm
svc = svm.SVC(gamma = 0.001, C = 100.)
  1. 加载数据集
from sklearn import datasets
digits = datasets.load_digits()
  1. 查看数据集信息
print(digits.DESCR)
  1. 查看图像数据
digits.images[0]

可以使用matplotlib库可视化图像:

import matplotlib.pyplot as plt
plt.imshow(digits.images[0], cmap = plt.cm.gray_r, interpolation = 'nearest')
  1. 查看目标值
digits.target
2.2.2 学习和预测
  1. 划分训练集和验证集
    将数据集的前1791个元素作为训练集,后6个元素作为验证集。
import matplotlib.pyplot as plt
plt.subplot(321)
plt.imshow(digits.images[1791], cmap = plt.cm.gray_r, interpolation = 'nearest')
plt.subplot(322)
plt.imshow(digits.images[1792], cmap = plt.cm.gray_r, interpolation = 'nearest')
plt.subplot(323)
plt.imshow(digits.images[1793], cmap = plt.cm.gray_r, interpolation = 'nearest')
plt.subplot(324)
plt.imshow(digits.images[1794], cmap = plt.cm.gray_r, interpolation = 'nearest')
plt.subplot(325)
plt.imshow(digits.images[1795], cmap = plt.cm.gray_r, interpolation = 'nearest')
plt.subplot(326)
plt.imshow(digits.images[1796], cmap = plt.cm.gray_r, interpolation = 'nearest')
  1. 训练模型
svc.fit(digits.data[1:1790], digits.target[1:1790])
  1. 测试模型
svc.predict(digits.data[1791:1976])

将预测结果与实际值进行比较:

digits.target[1791:1976]

可以发现 svc 估计器能够正确识别验证集中的所有六个手写数字。

2.3 使用TensorFlow识别手写数字

TensorFlow库也可以用于手写数字识别,并且它包含了MNIST数据集的副本,方便我们进行神经网络的研究和测试。

2.3.1 安装必要的库

可以使用Anaconda Navigator或命令行安装 tensorflow - dataset 包:

conda install tensorflow - dataset

如果没有Anaconda平台,可以通过PyPI系统安装:

pip install tensorflow - dataset
2.3.2 导入数据集
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
(x_train, y_train),(x_test, y_test) = tf.keras.datasets.mnist.load_data()
2.3.3 划分数据集
x_validation = x_train[55000:]
x_train = x_train[:55000]
y_validation = y_train[55000:]
y_train = y_train[:55000]
2.3.4 查看数据集信息
len(x_train)
len(x_test)
len(x_validation)
2.3.5 可视化数据集
x_train[0].shape
plt.imshow(x_train[0], cmap = plt.cm.gray_r, interpolation = 'nearest')

还可以可视化100个数字:

fig, ax = plt.subplots(10, 10)
k = 0
for i in range(10):
    for j in range(10):
        ax[i][j].imshow(x_train[k].reshape(28, 28),
                        cmap = plt.cm.gray_r,
                        interpolation = 'nearest',
                        aspect = 'auto')
        ax[i][j].set_xticks([])
        ax[i][j].set_yticks([])
        k += 1

综上所述,我们学习了如何使用D3库创建复杂的等值区域地图,以及如何使用scikit - learn和TensorFlow进行手写数字识别。这些技术为我们处理不同类型的数据提供了强大的工具。

3. 总结与展望

3.1 技术总结

技术领域 关键技术 操作步骤
数据可视化 D3库创建等值区域地图 1. 导入必要的JavaScript库;2. 设置CSS样式和HTML元素;3. 定义模板;4. 渲染图表
手写数字识别 scikit - learn的SVC 1. 导入必要的库和创建估计器;2. 加载数据集;3. 查看数据集信息;4. 划分训练集和验证集;5. 训练模型;6. 测试模型
手写数字识别 TensorFlow 1. 安装必要的库;2. 导入数据集;3. 划分数据集;4. 查看数据集信息;5. 可视化数据集

3.2 技术应用场景

  • 数据可视化 :等值区域地图可用于展示人口分布、经济数据、疾病传播等与地理区域相关的数据,帮助决策者直观地了解不同地区的情况。
  • 手写数字识别 :在邮政、银行、教育等领域有广泛应用,如邮政编码识别、支票金额识别、学生答卷自动评分等。

3.3 未来发展趋势

  • 数据可视化 :随着数据量的不断增加和数据类型的多样化,数据可视化将朝着更加交互性、实时性和个性化的方向发展。例如,结合虚拟现实(VR)和增强现实(AR)技术,提供更加沉浸式的可视化体验。
  • 手写数字识别 :深度学习技术的不断发展将进一步提高手写数字识别的准确率和效率。同时,结合自然语言处理技术,实现对手写文本的更深入理解和分析。

3.4 学习建议

  • 数据可视化 :深入学习D3库的各种功能和API,同时了解其他数据可视化工具,如Plotly、Matplotlib等,根据不同的需求选择合适的工具。
  • 手写数字识别 :掌握机器学习和深度学习的基本原理,多实践不同的算法和模型,不断优化识别效果。

3.5 流程图:手写数字识别流程

graph LR
    A[准备数据] --> B[选择模型]
    B --> C[训练模型]
    C --> D[测试模型]
    D --> E{是否满足要求}
    E -- 是 --> F[应用模型]
    E -- 否 --> B

3.6 注意事项

  • 数据可视化 :在使用D3库时,要注意JavaScript库的版本兼容性,避免出现代码错误。
  • 手写数字识别 :在训练模型时,要注意数据集的质量和数量,避免过拟合和欠拟合的问题。

通过本文的学习,我们了解了如何使用D3库进行数据可视化,以及如何使用scikit - learn和TensorFlow进行手写数字识别。这些技术不仅可以帮助我们更好地理解和分析数据,还可以应用到实际的工作和生活中。希望大家能够不断学习和实践,掌握这些技术,为自己的职业发展和生活带来更多的便利和价值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值