harshiv commited on
Commit
8a64eea
1 Parent(s): a79d21e

Update api.py

Browse files
Files changed (1) hide show
  1. api.py +73 -59
api.py CHANGED
@@ -1,70 +1,84 @@
1
  import numpy as np
2
  import pandas as pd
3
- import torch
4
- import torch.nn as nn
5
- import torch.optim as optim
6
- from sklearn.model_selection import train_test_split
7
- from sklearn.metrics import accuracy_score
8
 
9
- class PlacementModel(nn.Module):
10
- def __init__(self, input_size, hidden_size, output_size):
11
- super(PlacementModel, self).__init__()
12
- self.fc1 = nn.Linear(input_size, hidden_size)
13
- self.fc2 = nn.Linear(hidden_size, output_size)
 
 
14
 
15
- def forward(self, x):
16
- x = torch.relu(self.fc1(x))
17
- x = self.fc2(x)
18
- return x
19
 
20
- # Load and preprocess data
21
- df = pd.read_csv("Placement (2).csv")
22
- df = df.drop(columns=["sl_no","stream","ssc_p","ssc_b","hsc_p","hsc_b","etest_p"])
23
- df['internship'] = df['internship'].map({'Yes':1,'No':0})
24
- df['status'] = df['status'].map({'Placed':1,'Not Placed':0})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- X_fullstk = df.drop(['status','management','leadership','communication','sales'], axis=1)
27
- y = df['status']
 
 
 
 
 
 
 
 
 
28
 
29
- X_train_fullstk, X_test_fullstk, y_train, y_test = train_test_split(X_fullstk, y, test_size=0.20, random_state=42)
 
30
 
31
- # Define model hyperparameters
32
- input_size = X_fullstk.shape[1]
33
- hidden_size = 128
34
- output_size = 2
35
- learning_rate = 0.01
36
- epochs = 100
37
 
38
- # Initialize model
39
- model = PlacementModel(input_size, hidden_size, output_size)
40
- criterion = nn.CrossEntropyLoss()
41
- optimizer = optim.Adam(model.parameters(), lr=learning_rate)
42
 
43
- # Train model
44
- for epoch in range(epochs):
45
- inputs = torch.tensor(X_train_fullstk.values, dtype=torch.float32)
46
- labels = torch.tensor(y_train.values, dtype=torch.long)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- optimizer.zero_grad()
49
-
50
- outputs = model(inputs)
51
- loss = criterion(outputs, labels)
52
- loss.backward()
53
- optimizer.step()
54
-
55
- if epoch % 10 == 0:
56
- print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}')
57
-
58
- # Evaluate model
59
- with torch.no_grad():
60
- inputs = torch.tensor(X_test_fullstk.values, dtype=torch.float32)
61
- labels = torch.tensor(y_test.values, dtype=torch.long)
62
-
63
- outputs = model(inputs)
64
- _, predicted = torch.max(outputs.data, 1)
65
- accuracy = accuracy_score(labels, predicted)
66
-
67
- print(f'Test Accuracy: {accuracy:.4f}')
68
-
69
- # Save model
70
- torch.save(model.state_dict(), 'placement_model.pth')
 
1
  import numpy as np
2
  import pandas as pd
3
+ import gradio as gr
4
+ import pickle
 
 
 
5
 
6
+ # Load trained models
7
+ with open('rf_hacathon_fullstk.pkl', 'rb') as f1:
8
+ rf_fullstk = pickle.load(f1)
9
+ with open('rf_hacathon_prodengg.pkl', 'rb') as f2:
10
+ rf_prodengg = pickle.load(f2)
11
+ with open('rf_hacathon_mkt.pkl', 'rb') as f3:
12
+ rf_mkt = pickle.load(f3)
13
 
 
 
 
 
14
 
15
+ # Define input and output functions for Gradio
16
+ def predict_placement(option, degree_p, internship, DSA, java, management,
17
+ leadership, communication, sales):
18
+ if option == "Fullstack":
19
+ new_data = pd.DataFrame(
20
+ {
21
+ 'degree_p': degree_p,
22
+ 'internship': internship,
23
+ 'DSA': DSA,
24
+ 'java': java,
25
+ },
26
+ index=[0])
27
+ prediction = rf_fullstk.predict(new_data)
28
+ probability = rf_fullstk.predict_proba(new_data)[0][1]
29
+ elif option == "Marketing":
30
+ new_data = pd.DataFrame(
31
+ {
32
+ 'degree_p': degree_p,
33
+ 'internship': internship,
34
+ 'management': management,
35
+ 'leadership': leadership,
36
+ },
37
+ index=[0])
38
+ prediction = rf_mkt.predict(new_data)
39
+ probability = rf_mkt.predict_proba(new_data)[0][1]
40
 
41
+ elif option == "Production Engineer":
42
+ new_data = pd.DataFrame(
43
+ {
44
+ 'degree_p': degree_p,
45
+ 'internship': internship,
46
+ 'communication': communication,
47
+ 'sales': sales,
48
+ },
49
+ index=[0])
50
+ prediction = rf_prodengg.predict(new_data)
51
+ probability = rf_prodengg.predict_proba(new_data)[0][1]
52
 
53
+ else:
54
+ return "Invalid option"
55
 
56
+ if prediction == 1:
57
+ return f"{probability:.2f}"
58
+ else:
59
+ return f"{probability:.2f}"
 
 
60
 
 
 
 
 
61
 
62
+ # Create Gradio interface
63
+ iface = gr.Interface(
64
+ fn=predict_placement,
65
+ inputs=[
66
+ gr.inputs.Dropdown(["Fullstack", "Marketing", "Production Engineer"],
67
+ label="Select Option"),
68
+ gr.inputs.Number(label="Degree Percentage"),
69
+ gr.inputs.Number(label="Internship"),
70
+ gr.inputs.Checkbox(label="DSA"),
71
+ gr.inputs.Checkbox(label="Java"),
72
+ gr.inputs.Checkbox(label="Management"),
73
+ gr.inputs.Checkbox(label="Leadership"),
74
+ gr.inputs.Checkbox(label="Communication"),
75
+ gr.inputs.Checkbox(label="Sales"),
76
+ ],
77
+ outputs=gr.outputs.Textbox(label="Placement Prediction"),
78
+ title="Placement Prediction",
79
+ description=
80
+ "Predict the chances of placement for different job roles using machine learning models.",
81
+ )
82
 
83
+ # Launch Gradio app
84
+ iface.launch(share=True)