《前端开发者的人工智能第一课》第一节:从浏览器到神经网络

92 阅读2分钟

《前端开发者的人工智能第一课》第一节:从浏览器到神经网络

🌟 课程亮点

  • 零数学公式入门AI
  • 全程JavaScript实现
  • 浏览器内完成所有实验
  • 融合前端工程化思维

第一节:用CSS滤镜理解卷积神经网络

1.1 课前准备

# 推荐环境(任选其一)
1. CodeSandbox + TensorFlow.js模板
2. Vite项目 + @tensorflow/tfjs
3. Observable Notebook在线环境

1.2 认知革命:图像处理的进化论

// 传统前端图像处理
document.querySelector('img').style.filter = 'grayscale(100%)';

// 现代AI图像处理
const model = await tf.loadGraphModel('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2');

1.3 手写数字识别实战

<!-- 前端工程师的第一个AI界面 -->
<div class="canvas-box">
  <canvas id="drawpad" width="280" height="280"></canvas>
  <button onclick="predict()">识别数字</button>
  <div id="result"></div>
</div>

<script>
// 加载预训练模型
const model = await tf.loadLayersModel('https://storage.googleapis.com/tfjs-models/tfjs/mnist_model/model.json');

// 将Canvas绘图转换为张量
function preprocess(canvas) {
  return tf.tidy(() => {
    return tf.browser.fromPixels(canvas)
      .resizeNearestNeighbor([28, 28])
      .mean(2)
      .expandDims(2)
      .toFloat()
      .div(255.0);
  });
}

// 像处理事件监听一样处理预测
async function predict() {
  const tensor = preprocess(document.getElementById('drawpad'));
  const prediction = model.predict(tensor);
  const result = prediction.argMax(1).dataSync()[0];
  document.getElementById('result').innerText = `识别结果:${result}`;
}
</script>

1.4 原理拆解:神经网络即滤镜管道

// 用滤镜链模拟神经网络
const neuralNetwork = [
  { type: 'conv', filterSize: 5, stride: 1 },  // 卷积层
  { type: 'relu' },                            // 激活函数
  { type: 'pool', operation: 'max' },          // 池化层
  { type: 'flatten' },                         // 展平层
  { type: 'dense', units: 128 },               // 全连接层
  { type: 'softmax' }                          // 输出层
];

1.5 拓展实验:可视化特征提取

// 使用tfjs-vis进行中间层可视化
const surface = tfvis.visor().surface({ name: '卷积特征图' });
const layer = model.getLayer('conv2d_1');
const activationModel = tf.model({
  inputs: model.inputs,
  outputs: layer.output
});

const activations = activationModel.predict(tensor);
tfvis.show.heatmap(surface, {
  values: activations.squeeze(),
  width: 28,
  height: 28
});

📚 课后实践

  1. 修改Canvas尺寸观察识别准确率变化
  2. 尝试在输入图像添加噪声(模拟数据增强)
  3. 用CSS animation实现识别结果过渡效果

💡 下节预告

《用React状态管理训练线性回归》

  • 用useReducer实现梯度下降
  • Redux管理训练状态
  • Hooks封装模型训练逻辑