mrhammad12/hammad-logistic-regression
0
1from flask import Flask, render_template, request, jsonify
2import numpy as np
3import pickle
4import json
5import os
6
7app = Flask(__name__)
8
9# Import custom model
10try:
11 from model import LogisticRegressionFromScratch
12 print("✓ Successfully imported LogisticRegressionFromScratch")
13except ImportError as e:
14 print(f"Import error: {e}")
15 # Fallback implementation
16 class LogisticRegressionFromScratch:
17 def __init__(self, learning_rate=0.01, epochs=2000, lambda_param=0.01):
18 self.learning_rate = learning_rate
19 self.epochs = epochs
20 self.lambda_param = lambda_param
21 self.weights = None
22 self.bias = None
23
24 def sigmoid(self, z):
25 z = np.clip(z, -500, 500)
26 return 1 / (1 + np.exp(-z))
27
28 def load_model(self, filepath):
29 with open(filepath, 'r') as f:
30 model_data = json.load(f)
31 self.weights = np.array(model_data['weights'])
32 self.bias = model_data['bias']
33
34 def predict(self, X):
35 z = np.dot(X, self.weights) + self.bias
36 y_pred = self.sigmoid(z)
37 return (y_pred >= 0.5).astype(int)
38
39 def predict_proba(self, X):
40 z = np.dot(X, self.weights) + self.bias
41 return self.sigmoid(z)
42
43# Load trained model and scaler
44try:
45 model = LogisticRegressionFromScratch()
46 model.load_model('trained_model.json')
47 print("✓ Model loaded successfully")
48
49 with open('scaler.pkl', 'rb') as f:
50 scaler = pickle.load(f)
51 print("✓ Scaler loaded successfully")
52
53except Exception as e:
54 print(f"Error loading model/scaler: {e}")
55 model = None
56 scaler = None
57
58# Feature names from Breast Cancer dataset
59FEATURE_NAMES = [
60 'mean radius', 'mean texture', 'mean perimeter', 'mean area',
61 'mean smoothness', 'mean compactness', 'mean concavity',
62 'mean concave points', 'mean symmetry', 'mean fractal dimension',
63 'radius error', 'texture error', 'perimeter error', 'area error',
64 'smoothness error', 'compactness error', 'concavity error',
65 'concave points error', 'symmetry error', 'fractal dimension error',
66 'worst radius', 'worst texture', 'worst perimeter', 'worst area',
67 'worst smoothness', 'worst compactness', 'worst concavity',
68 'worst concave points', 'worst symmetry', 'worst fractal dimension'
69]
70
71# Sample data for demonstration
72SAMPLE_DATA = {
73 'mean radius': 13.54, 'mean texture': 14.36, 'mean perimeter': 87.46,
74 'mean area': 566.3, 'mean smoothness': 0.09779, 'mean compactness': 0.08129,
75 'mean concavity': 0.06664, 'mean concave points': 0.04781, 'mean symmetry': 0.1885,
76 'mean fractal dimension': 0.05766, 'radius error': 0.2699, 'texture error': 0.7886,
77 'perimeter error': 2.058, 'area error': 23.56, 'smoothness error': 0.008462,
78 'compactness error': 0.0146, 'concavity error': 0.02387, 'concave points error': 0.01315,
79 'symmetry error': 0.0198, 'fractal dimension error': 0.0023, 'worst radius': 15.11,
80 'worst texture': 19.26, 'worst perimeter': 99.7, 'worst area': 711.2,
81 'worst smoothness': 0.144, 'worst compactness': 0.1773, 'worst concavity': 0.239,
82 'worst concave points': 0.1288, 'worst symmetry': 0.2977, 'worst fractal dimension': 0.07259
83}
84
85@app.route('/')
86def home():
87 return render_template('index.html', features=FEATURE_NAMES, sample_data=SAMPLE_DATA)
88
89@app.route('/predict', methods=['POST'])
90def predict():
91 try:
92 if model is None or scaler is None:
93 return jsonify({'error': 'Model not loaded properly'}), 400
94
95 data = request.get_json()
96 features = np.array([float(data.get(f, 0)) for f in FEATURE_NAMES]).reshape(1, -1)
97
98 # Scale features
99 features_scaled = scaler.transform(features)
100
101 # Make prediction
102 prediction = model.predict(features_scaled)[0]
103 probability = model.predict_proba(features_scaled)[0]
104
105 result = {
106 'prediction': int(prediction),
107 'probability': float(probability),
108 'diagnosis': 'Malignant' if prediction == 1 else 'Benign',
109 'confidence': f"{max(probability, 1-probability)*100:.2f}%"
110 }
111
112 return jsonify(result)
113
114 except Exception as e:
115 return jsonify({'error': str(e)}), 400
116
117@app.route('/load_sample', methods=['GET'])
118def load_sample():
119 """Return sample data for demonstration"""
120 return jsonify(SAMPLE_DATA)
121
122@app.route('/model_info')
123def model_info():
124 """Return model information"""
125 info = {
126 'accuracy': '98%',
127 'training_samples': 455,
128 'test_samples': 114,
129 'features': len(FEATURE_NAMES),
130 'algorithm': 'Logistic Regression with L2 Regularization',
131 'learning_rate': 0.01,
132 'epochs': 2000,
133 'model_loaded': model is not None,
134 'author': 'Hammad'
135 }
136 return jsonify(info)
137
138if __name__ == '__main__':
139 port = int(os.environ.get('PORT', 5000))
140 app.run(debug=False, host='0.0.0.0', port=port)