这里给出一个简单的AI模型从训练到部署的源码示例,以图像分类为例:
1. 数据收集和预处理
```python
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# 导入Fashion MNIST数据集
(x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()
# 数据预处理
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
# 将标签转化为One-hot编码
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
```
2. 模型训练
```python
# 构建模型
model = keras.Sequential(
[
keras.Input(shape=(28, 28)),
layers.Reshape(target_shape=(28, 28, 1)),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(10, activation="softmax"),
]
)
# 编译模型
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
# 训练模型
model.fit(x_train, y_train, batch_size=64, epochs=5, validation_split=0.2)
```
3. 模型评估和保存
```python
# 模型评估
test_loss, test_acc = model.evaluate(x_test, y_test)
print("Test accuracy:", test_acc)
# 保存模型
model.save("my_model.h5")
```
4. 部署模型
```python
# 加载模型
model = keras.models.load_model("my_model.h5")
# 预测
prediction = model.predict(x_test)
# 展示结果
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(x_test[i], cmap=plt.cm.binary)
predicted_label = np.argmax(prediction[i])
true_label = np.argmax(y_test[i])
if predicted_label == true_label:
color = "green"
else:
color = "red"
plt.xlabel("{} ({})".format(class_names[predicted_label], class_names[true_label]), color=color)
plt.show()
```
以上是一个简单的示例,实际上在生产环境中,需要更严谨的模型优化、评估和部署,在部署过程中还需要考虑安全性和性能问题,并进行实时监测和维护。