【人工智能】Tensorflow深度学习模板(极简版)

模型定义

import tensorflow as tf
from tensorflow.keras import layers, models, optimizers, losses, metrics, callbacks
import numpy as np

# 生成示例数据(此处应替换为真实数据)
def load_data():
    # 假设输入为1000个样本,每个样本20个特征(结构化数据)
    x_train = np.random.rand(1000, 20).astype('float32')  # 1000行20列
    y_train = np.random.randint(0, 2, size=(1000,))       # 二分类标签
    return x_train, y_train

x_train, y_train = load_data()

# 数据预处理(标准化/编码)
x_train = (x_train - np.mean(x_train, axis=0)) / np.std(x_train, axis=0)  # 标准化
y_train = tf.keras.utils.to_categorical(y_train, num_classes=2)          # one-hot编码

# 构建全连接神经网络
model = models.Sequential([
    layers.Input(shape=(input_shape,)),          # 输入层
    layers.Dense(64, activation='relu'),         # 隐藏层1
    layers.Dense(32, activation='relu'),         # 隐藏层2
    layers.Dense(num_classes, activation='softmax')  # 输出层(分类用softmax)
])

# 编译模型
model.compile(
    optimizer=optimizers.Adam(learning_rate=0.001),
    loss=losses.CategoricalCrossentropy(),
    metrics=[metrics.CategoricalAccuracy()]
)

# 训练模型
history = model.fit(x_train, y_train,epochs=100)

# 评估模型
loss, accuracy = model.evaluate(x_train, y_train, verbose=0)
print(f"训练集准确率: {accuracy:.4f}")

# 保存模型
model.save('dense_model.h5')

训练结果可视化

import matplotlib.pyplot as plt

print(history.history.keys())

plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train','validation'])
plt.show()

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train','validation'])
plt.show()

你可能感兴趣的:(人工智能,tensorflow,python)