TensorFlow 零基础入门:手把手教你跑通第一个AI模型

今天用最直白的语言,带完全零基础的同学走进 TensorFlow 的世界。不用担心数学公式,先学会"开车",再学"造车"!

1. 准备工作:安装TensorFlow

就像玩游戏需要先安装游戏客户端一样,我们需要先安装 TensorFlow。打开你的电脑(Windows/Mac都行),按下 Win + R,输入 cmd 打开命令提示符,然后输入:

pip install tensorflow

看到"Successfully installed"就搞定啦!如果安装慢,可以试试这个国内镜像:

pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple

2. 第一个程序:预测商品销量

想象你开了一家奶茶店,记录了每天的气温和卖出的奶茶杯数:

气温(℃) 奶茶销量
20 45
25 75
30 105

我们想让电脑学会:当气温是28℃时,大概能卖多少杯?

完整代码(直接复制就能用!)

# 导入TensorFlow库(就像我们要用计算器得先打开它)
import tensorflow as tf
import numpy as np

# 1. 准备数据
temperature = np.array([20, 25, 30], dtype=float)  # 输入特征:气温
sales = np.array([45, 75, 105], dtype=float)       # 真实销量

# 2. 创建最简单的AI模型(只有一个神经元)
model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1])  # 全连接层
])

# 3. 配置模型(告诉电脑怎么学习)
model.compile(
    optimizer=tf.keras.optimizers.Adam(0.1),  # 学习率设为0.1
    loss='mean_squared_error'  # 用均方误差衡量预测好坏
)

# 4. 开始训练!(让电脑从数据中学习)
print("开始训练...")
history = model.fit(temperature, sales, epochs=500, verbose=False)
print("训练完成!")

# 5. 使用训练好的模型预测
print("当气温是28℃时,预测销量:", model.predict([28])[0][0], "杯")

运行结果

你会看到类似这样的输出:

当气温是28℃时,预测销量: 93.2 杯

逐行解释(给完全不懂的同学)

  1. import tensorflow as tf:就像打开计算器APP

  2. temperature 和 sales:我们给电脑看的"例题"

  3. Dense(units=1):最简单的AI大脑(只有1个"脑细胞")

  4. optimizer:电脑的学习方式(Adam是比较聪明的学习方法)

  5. fit():让电脑反复做题(500遍)

  6. predict():让电脑做新题(28℃时卖多少?)

3. 升级任务:识别手写数字

现在我们来做个更酷的——让电脑认识你写的数字!就像手机解锁时的数字识别。

完整代码(直接运行)

import tensorflow as tf

# 1. 加载数字图片数据集(TensorFlow自带)
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# 2. 预处理(把图片像素值从0-255缩放到0-1)
train_images = train_images / 255.0
test_images = test_images / 255.0

# 3. 构建AI模型(这次用3层神经网络)
model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),  # 把图片展平
    tf.keras.layers.Dense(128, activation='relu'),  # 隐藏层(128个脑细胞)
    tf.keras.layers.Dense(10)                       # 输出层(0-9十个数字)
])

# 4. 配置模型
model.compile(
    optimizer='adam',
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=['accuracy']  # 我们要看准确率
)

# 5. 训练(这次训练5轮就够了)
model.fit(train_images, train_labels, epochs=5)

# 6. 测试准确率
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f"\n测试准确率:{test_acc*100:.1f}%")  # 正常能达到97%左右

你会看到

Epoch 1/5
1875/1875 [=====] - 3s 1ms/step - loss: 0.2586 - accuracy: 0.9265
...
测试准确率:97.4%

重点解释

  1. mnist.load_data():下载包含6万张手写数字图片的数据集

  2. /255.0:把图片从黑白(0-255)变成灰度(0-1)

  3. Flatten:把28×28的图片"压平"成784个数字

  4. Dense(128):第二层有128个"脑细胞"

  5. epochs=5:整个数据集学习5遍

4. 常见问题解答

❓ 问:为什么我的结果和例子不一样?
答:正常!AI训练有随机性,只要准确率在95%以上都算成功。

❓ 问:电脑需要很高配置吗?
答:不用!这些例子普通笔记本都能跑,TensorFlow会自动用CPU计算。

❓ 问:想识别自己的手写数字怎么办?
答:可以用这个进阶代码(需要安装Pillow库):

from PIL import Image
import numpy as np

# 加载自己写的数字图片(黑白28x28像素)
img = Image.open('my_digit.png').convert('L')
img = np.array(img) / 255.0
img = img.reshape(1, 28, 28)

# 预测
prediction = model.predict(img)
print("AI认为这是数字:", np.argmax(prediction))

5. 下一步学习建议

  1. 修改参数玩一玩:比如把epochs=5改成epochs=10,看看准确率变化

  2. 可视化训练过程:在model.fit()前加:

    import matplotlib.pyplot as plt
    plt.plot(history.history['accuracy'], label='accuracy')
  3. 尝试其他数据集:比如tf.keras.datasets.cifar10(彩色图片分类)

记住:学AI就像学骑自行车,先学会骑,再研究原理。现在你已经成功跑通了两个AI模型,给自己点个赞吧!

如果有任何问题,欢迎在评论区留言,我会一一解答~

你可能感兴趣的:(人工智能,人工智能,tensorflow,python,机器学习,深度学习,分类)