File size: 2,112 Bytes
f75a1ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import joblib
import pandas as pd
from flask import Flask, request, jsonify

# Initialize Flask app
house_price_api = Flask("Boston House Price Predictor")

# Load the trained Boston housing model
model = joblib.load("boston_housing_model_v1_0.joblib")

# Define a route for the home page
@house_price_api.get('/')
def home():
    return "Welcome to the Boston House Price Prediction API!"

# Define an endpoint to predict price for a single house
@house_price_api.post('/v1/house')
def predict_house_price():
    # Get JSON data from the request
    house_data = request.get_json()

    # Extract relevant house features from the input data
    sample = {
        'CRIM': house_data['CRIM'],
        'ZN': house_data['ZN'],
        'INDUS': house_data['INDUS'],
        'CHAS': house_data['CHAS'],
        'NX': house_data['NX'],     # should be NOX in your dataset, check consistency
        'RM': house_data['RM'],
        'AGE': house_data['AGE'],
        'DIS': house_data['DIS'],
        'RAD': house_data['RAD'],
        'TAX': house_data['TAX'],
        'PTRATIO': house_data['PTRATIO'],
        'LSTAT': house_data['LSTAT']
    }

    # Convert the extracted data into a DataFrame
    input_data = pd.DataFrame([sample])

    # Make a prediction using the trained model
    prediction = model.predict(input_data).tolist()[0]

    # Return the prediction as a JSON response
    return jsonify({'Predicted_MEDV': prediction})

# Define an endpoint to predict price for a batch of houses
@house_price_api.post('/v1/housebatch')
def predict_house_batch():
    # Get the uploaded CSV file from the request
    file = request.files['file']

    # Read the file into a DataFrame
    input_data = pd.read_csv(file)

    # Make predictions for the batch data
    predictions = model.predict(input_data).tolist()

    # Add predictions to the DataFrame
    input_data['Predicted_MEDV'] = predictions

    # Convert results to dictionary
    result = input_data.to_dict(orient="records")

    return jsonify(result)

# Run the Flask app in debug mode
if __name__ == '__main__':
    house_price_api.run(debug=True)