stevenlriv commited on
Commit
a2bb9cc
·
unverified ·
1 Parent(s): d915a29

model commit

Browse files
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .DS_Store
README.md CHANGED
@@ -1,3 +1,47 @@
1
  ---
2
  license: mit
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
  ---
4
+
5
+ # Practical Alien Detector
6
+
7
+ Finetuned resnet50 for detecting if the image you show it is an alien or not.
8
+
9
+ You can try it out as an API by following the `How to run an API and test your model` instructions.
10
+
11
+ This model was created for fun!
12
+
13
+ ## Installation
14
+
15
+ ```shell
16
+ pip3 install fastbook
17
+
18
+ pip3 install fastai
19
+
20
+ pip3 install flask
21
+ ```
22
+
23
+ ## How to build your model
24
+
25
+ ```shell
26
+ python3 aliens_model_builder.py
27
+ ```
28
+
29
+ ## How to test your model
30
+
31
+ ![Python Terminal](./img/python-terminal.png)
32
+
33
+ After running it wil ask the image path.
34
+
35
+ ```shell
36
+ python3 aliens_model_test.py
37
+ ```
38
+
39
+ ## How to run an API and test your model
40
+
41
+ ![Python API](./img/python-api.png)
42
+
43
+ After running it, visit `http://localhost:5000/`
44
+
45
+ ```shell
46
+ python3 aliens_api.py
47
+ ```
aliens_api.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, send_file
2
+ from fastai.vision.all import *
3
+
4
+ app = Flask(__name__)
5
+
6
+ # Load the trained model
7
+ model_path = './model.pkl'
8
+ learn = load_learner(model_path)
9
+
10
+ @app.route('/')
11
+ def index():
12
+ return send_file('index.html')
13
+
14
+ @app.route('/predict', methods=['POST'])
15
+ def predict():
16
+ # Check if an image file is present in the request
17
+ if 'image' not in request.files:
18
+ return jsonify({'error': 'No image file found'}), 400
19
+
20
+ image_file = request.files['image']
21
+
22
+ # Save the uploaded image temporarily
23
+ image_path = 'uploaded_image.jpg'
24
+ image_file.save(image_path)
25
+
26
+ # Prepare the image for prediction
27
+ img = PILImage.create(image_path)
28
+
29
+ # Make predictions
30
+ pred_class, pred_idx, probs = learn.predict(img)
31
+
32
+ # Prepare the response
33
+ response = {
34
+ 'predicted_class': pred_class,
35
+ 'predicted_probabilities': probs.tolist()
36
+ }
37
+
38
+ # Remove the temporary image file
39
+ os.remove(image_path)
40
+
41
+ return jsonify(response)
42
+
43
+ if __name__ == '__main__':
44
+ app.run()
aliens_model_builder.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastbook import *
2
+ from fastai.vision.all import *
3
+ from fastai.vision.widgets import *
4
+
5
+ # Step 1: Gather the data
6
+ # You can use APIs or manually download the data
7
+
8
+ # The name of the path where the two folders
9
+ # with the data are located at
10
+ # ie. ./alien_or_not/alien for alien images
11
+ # ie. ./alien_or_not/not_alien for human images
12
+ path = Path('alien_or_not')
13
+
14
+ # Step 2: Establish your Data Loader object
15
+
16
+ aliens = DataBlock(
17
+ blocks=(ImageBlock, CategoryBlock),
18
+ get_items=get_image_files,
19
+ splitter=RandomSplitter(valid_pct=0.2, seed=42),
20
+ get_y=parent_label,
21
+ item_tfms=Resize(128))
22
+
23
+ dls = aliens.dataloaders(path)
24
+ dls.valid.show_batch(max_n=4, nrows=1)
25
+
26
+ # Step 3: Fine tune your model
27
+ # models you can use:
28
+ # resnet18
29
+ # resnet50
30
+
31
+ learn = vision_learner(dls, resnet50, metrics=error_rate)
32
+ learn.fine_tune(500)
33
+
34
+ # Step 4: Mistakes and Cleaning them
35
+
36
+ # Step 5: Use the model
37
+ is_alien, _, probs = learn.predict(PILImage.create('test_images/4.jpg'))
38
+
39
+ print(f"This is a: {is_alien}.")
40
+ print(f"Probability it's an alien: {probs[0]:.4f}")
41
+
42
+ # Step 6: Export the model
43
+
44
+ learn.export('model.pkl')
aliens_model_test.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastai.vision.all import *
2
+
3
+ # Load the trained model
4
+ model_path = './model.pkl'
5
+ learn = load_learner(model_path)
6
+
7
+ # Prompt the user to enter the image path
8
+ test_image_path = input("Enter the path to the test image: ")
9
+
10
+ # Prepare your test data
11
+ img = PILImage.create(test_image_path)
12
+
13
+ # Make predictions
14
+ is_alien, _, probs = learn.predict(img)
15
+
16
+ # Print the predicted class and probabilities
17
+ if is_alien == "aliens":
18
+ print(f"This is an alien.")
19
+ else:
20
+ print(f"This is not an alien.")
21
+
22
+ print(f"Probability it's an alien: {probs[0]:.4f}")
img/python-api.png ADDED
img/python-terminal.png ADDED
index.html ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Practical Alien Detector</title>
5
+ <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
6
+ <script>
7
+ function uploadImage() {
8
+ var formData = new FormData();
9
+ formData.append('image', $('#imageUpload')[0].files[0]);
10
+
11
+ $.ajax({
12
+ url: '/predict',
13
+ type: 'POST',
14
+ data: formData,
15
+ processData: false,
16
+ contentType: false,
17
+ success: function(response) {
18
+ if (response.predicted_class == "aliens") {
19
+ $('#result').text('This is an alien.');
20
+ } else {
21
+ $('#result').text('This is NOT an alien.');
22
+ }
23
+ $('#prob').text('Probability its an alien: '+response.predicted_probabilities);
24
+ },
25
+ error: function(xhr, status, error) {
26
+ console.log(error);
27
+ }
28
+ });
29
+ }
30
+ </script>
31
+ </head>
32
+ <body>
33
+ <h1>Practical Alien Detector</h1>
34
+ <input type="file" id="imageUpload">
35
+ <button onclick="uploadImage()">Predict</button>
36
+ <div id="result"></div>
37
+ <div id="prob"></div>
38
+ </body>
39
+ </html>
model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5caf29df5c2e2c5bafffeb078f41ea86a80ad2ae7ad15db01d9a95fb6b16fbb8
3
+ size 102906478