Source code examples of AI models from training to deployment

Here is an example of the source code of a simple AI model from training to deployment, taking image classification as an example:

1. Data collection and preprocessing

```python
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Import Fashion MNIST dataset
(x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()

# Data preprocessing
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0

# Convert labels to One-hot encoding
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)

```

2. Model training

```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"])

# Training model
model.fit(x_train, y_train, batch_size=64, epochs=5, validation_split=0.2)
```

3. Model evaluation and preservation

```python
# Model evaluation
test_loss, test_acc = model.evaluate(x_test, y_test)
print("Test accuracy:", test_acc)

# Save the model
model.save("my_model.h5")
```

4. Deploy the model

```python
# load model
model = keras.models.load_model("my_model.h5")

# Predict
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()
```

The above is a simple example. In fact, in a production environment, more rigorous model optimization, evaluation, and deployment are required. During the deployment process, security and performance issues also need to be considered, and real-time monitoring and maintenance are required.

Guess you like

Origin blog.csdn.net/weixin_43955838/article/details/131656030