自定义数据集 使用tensorflow框架实现逻辑回归并保存模型,然后保存模型后再加载模型进行预测

在 TensorFlow 中实现逻辑回归、保存模型并加载模型进行预测的过程可以分为以下几个步骤:

  1. 准备数据:创建或加载你的自定义数据集。
  2. 构建逻辑回归模型
  3. 训练模型
  4. 保存模型
  5. 加载模型
  6. 使用加载的模型进行预测
  7. import tensorflow as tf
    import numpy as np
    
    # 1. 准备数据
    # 示例:生成一些随机数据
    np.random.seed(0)
    X_train = np.random.rand(100, 3)  # 100个样本,每个样本3个特征
    y_train = (np.sum(X_train, axis=1) > 1.5).astype(int)  # 简单的标签生成逻辑
    
    X_test = np.random.rand(20, 3)  # 20个样本用于测试
    
    # 2. 构建逻辑回归模型
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(1, activation='sigmoid', input_shape=(3,))
    ])
    
    # 编译模型
    model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
    
    # 3. 训练模型
    model.fit(X_train, y_train, epochs=10, verbose=1)
    
    # 4. 保存模型
    model_save_path = 'logistic_regression_model.h5'
    model.save(model_save_path)
    print(f"Model saved to {model_save_path}")
    
    # 5. 加载模型
    loaded_model = tf.keras.models.load_model(model_save_path)
    
    # 6. 使用加载的模型进行预测
    predictions = loaded_model.predict(X_test)
    predicted_classes = (predictions > 0.5).astype(int)
    
    print("Predictions:")
    print(predicted_classes)

你可能感兴趣的:(machine,learning,人工智能)