CLC Assignment 03 AI START
CLC Assignment 03 AI START
chạy các version và nộp trước 12PM TỐI THỨ BA (THỨ BA 18/03)
CHÚ Ý: SINH VIÊN CÁC LỚP CLC NỘP BÀI ASSIGNMENT 2 TRƯỚC 23:50 TỐI THỨ HAI (17/03)
========================================
• kNN
• SVM linear kernel
• SVM RBF kernel
• Logistic Regression
• Deep Learning > 5 Layers
1. Compare accuracy of 5 models
2. Vizualize the accuracy in plots lines-chart
3. Deploy the models and use interface to allow users entering features, select model for showing
the results
4. Write 5 pages of deep learning
=====
VERSION 1
i only want to code and deploy web with deep learning for diagnose diabetes. code all again for me url =
"https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
columns = ["Pregnancies", "Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI",
"DiabetesPedigreeFunction", "Age", "Outcome"] df = pd.read_csv(url, names=columns)
ChatGPT said:
2. Builds a web app using Flask to allow users to enter input and get predictions.
3. Deploys the model so users can interact with it via a web interface.
Steps to Run
bash
CopyEdit
python app.py
This script trains a deep learning model on the Pima Indians Diabetes dataset and saves it.
python
CopyEdit
import pandas as pd
import numpy as np
import tensorflow as tf
import joblib
# Load dataset
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
df = pd.read_csv(url, names=columns)
X = df.drop("Outcome", axis=1)
y = df["Outcome"]
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Split data
def create_model():
model = Sequential([
Dropout(0.3),
Dense(64, activation="relu"),
Dropout(0.3),
Dense(32, activation="relu"),
Dense(16, activation="relu"),
Dense(1, activation="sigmoid")
])
return model
# Train model
model = create_model()
model.save("diabetes_model.h5")
joblib.dump(scaler, "scaler.pkl")
This script runs a Flask web app where users can enter health data and get diabetes predictions.
python
CopyEdit
import numpy as np
import tensorflow as tf
import joblib
model = tf.keras.models.load_model("diabetes_model.h5")
scaler = joblib.load("scaler.pkl")
app = Flask(__name__)
def index():
prediction = None
if request.method == "POST":
try:
"DiabetesPedigreeFunction", "Age"]]
# Scale input
input_data = scaler.transform([features])
# Predict
pred_prob = model.predict(input_data)[0][0]
except Exception as e:
if __name__ == "__main__":
app.run(debug=True)
This is the simple web form where users enter their details.
html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>Diabetes Prediction</title>
</head>
<body>
<form method="post">
</form>
</body>
</html>
bash
CopyEdit
python train_model.py
This saves the trained model as diabetes_model.h5 and the scaler as scaler.pkl.
bash
CopyEdit
python app.py
Features
Deep learning model with 5+ layers
User-friendly web interface
Deployable using Flask
Scalable and accurate
This should give you a working AI-powered diabetes diagnosis web app! Let me know if you need
help!
VERSION 2
We can enhance the web interface using CSS for styling and Node.js for better front-end interactivity
with a modern UI. Here's how we can improve it:
Plan
1. Frontend:
o Use HTML, CSS, and JavaScript (React.js or Vanilla JS) for a better user experience.
3. Deployment:
o Run Flask as a backend API and use Node.js for serving the frontend.
Steps
Same as before, but we just save the model and create an API endpoint.
python
CopyEdit
import pandas as pd
import numpy as np
import tensorflow as tf
import joblib
# Load dataset
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-
diabetes.data.csv"
df = pd.read_csv(url, names=columns)
# Split data
X = df.drop("Outcome", axis=1)
y = df["Outcome"]
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
def create_model():
model = Sequential([
Dropout(0.3),
Dense(64, activation="relu"),
Dropout(0.3),
Dense(32, activation="relu"),
Dense(16, activation="relu"),
Dense(1, activation="sigmoid")
])
return model
# Train model
model = create_model()
model.save("diabetes_model.h5")
joblib.dump(scaler, "scaler.pkl")
python
CopyEdit
import numpy as np
import tensorflow as tf
import joblib
model = tf.keras.models.load_model("diabetes_model.h5")
scaler = joblib.load("scaler.pkl")
app = Flask(__name__)
@app.route("/predict", methods=["POST"])
def predict():
try:
except Exception as e:
if __name__ == "__main__":
app.run(debug=True, port=5000)
We'll create a modern UI using Node.js and fetch predictions from Flask.
Install dependencies
mkdir diabetes-frontend
cd diabetes-frontend
npm init -y
javascript
CopyEdit
app.use(cors());
app.use(bodyParser.json());
});
Frontend UI (public/index.html)
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Diabetes Prediction</title>
</head>
<body>
<div class="container">
<h2>Diabetes Prediction</h2>
<form id="predictionForm">
<button type="submit">Predict</button>
</form>
<h3 id="result"></h3>
</div>
<script src="script.js"></script>
</body>
</html>
css
CopyEdit
body {
text-align: center;
background-color: #f4f4f4;
.container {
width: 50%;
margin: auto;
background: white;
padding: 20px;
border-radius: 10px;
input, button {
width: 90%;
padding: 10px;
margin: 5px;
JavaScript (public/script.js)
javascript
CopyEdit
event.preventDefault();
method: "POST",
});
});
bash
CopyEdit
python app.py
bash
CopyEdit
node server.js
Features
INSTALL NPM
TRY
npm -v
VERSION 3
ou can use REST API to connect your deep learning model with the frontend.
Since your deep learning model is in Python, we will use Flask to create an API that receives user
input, runs the model, and returns predictions.
cmd
CopyEdit
python
CopyEdit
import numpy as np
import tensorflow as tf
import pandas as pd
model = tf.keras.models.load_model("diabetes_model.h5")
app = Flask(__name__)
CORS(app)
@app.route("/predict", methods=["POST"])
def predict():
if __name__ == "__main__":
app.run(debug=True, port=5000)
cmd
CopyEdit
python server.py
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Diabetes Prediction</title>
</head>
<body>
<form id="predictForm">
<button type="submit">Predict</button>
</form>
<h3 id="result"></h3>
<script>
document.getElementById("predictForm").addEventListener("submit", function(event) {
event.preventDefault();
fetch("http://127.0.0.1:5000/predict", {
method: "POST",
})
document.getElementById("result").innerText =
});
});
</script>
</body>
</html>
Next Steps
2. Deploy API & Web: Use Flask with Gunicorn (backend) and React/Vue (frontend)
3. Use Docker: Package API into a Docker container for easy deployment
VERSION 4
ChatGPT said:
python
CopyEdit
import tensorflow as tf
import pandas as pd
import numpy as np
# Load dataset
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-
diabetes.data.csv"
df = pd.read_csv(url, names=columns)
# Split data
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
# Normalize data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
def create_model():
model = Sequential([
Dense(128, input_shape=(X_train.shape[1],)),
BatchNormalization(),
tf.keras.layers.LeakyReLU(alpha=0.1),
Dropout(0.4),
Dense(64),
BatchNormalization(),
tf.keras.layers.LeakyReLU(alpha=0.1),
Dropout(0.3),
Dense(32),
BatchNormalization(),
tf.keras.layers.LeakyReLU(alpha=0.1),
Dense(16, activation="relu"),
Dense(1, activation="sigmoid")
])
model.compile(optimizer=AdamW(learning_rate=0.001), loss="binary_crossentropy",
metrics=["accuracy"])
return model
model = create_model()
model.save("diabetes_model.h5")
python
CopyEdit
import numpy as np
import tensorflow as tf
app = Flask(__name__)
model = tf.keras.models.load_model("diabetes_model.h5")
@app.route("/predict", methods=["POST"])
def predict():
data = request.json
prediction = model.predict(features)[0][0]
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
Step 2: Create Dockerfile
dockerfile
CopyEdit
FROM python:3.9
WORKDIR /app
# Copy files
# Install dependencies
# Expose port
EXPOSE 5000
# Run server
sh
CopyEdit
Now, your Flask API runs inside Docker and is accessible at http://localhost:5000/predict
Next Steps
4o