|
import torch |
|
import numpy as np |
|
import gradio as gr |
|
|
|
|
|
def predict_score(x1, x2): |
|
Theta0 = torch.tensor(-0.5738734424645411) |
|
Theta1 = torch.tensor(2.1659122905141825) |
|
Theta2 = torch.tensor(0.0) |
|
pred_score = Theta0 + Theta1 * x1 + Theta2 * x2 |
|
return pred_score.item() |
|
|
|
input1 = gr.inputs.Number(label="Number of new students") |
|
input2 = gr.inputs.Number(label="Number of temperature") |
|
|
|
output = gr.outputs.Textbox(label='Predicted Score') |
|
|
|
|
|
gr.Interface(fn=predict_score, inputs=[input1, input2], outputs=output).launch() |
|
|
|
|
|
x1 = torch.tensor([50, 60, 70, 80, 90]) |
|
x2 = torch.tensor([20, 21, 22, 23, 24]) |
|
y_actual = torch.tensor([30, 35, 40, 45, 50]) |
|
|
|
|
|
alpha = 0.01 |
|
max_iters = 1000 |
|
|
|
|
|
Theta0 = torch.tensor(0.0, requires_grad=True) |
|
Theta1 = torch.tensor(0.0, requires_grad=True) |
|
Theta2 = torch.tensor(0.0, requires_grad=True) |
|
|
|
|
|
iter_count = 0 |
|
|
|
|
|
while iter_count < max_iters: |
|
|
|
y_pred = Theta0 + Theta1 * x1 + Theta2 * x2 |
|
|
|
|
|
errors = y_pred - y_actual |
|
|
|
|
|
cost = torch.sum(errors ** 2) / (2 * len(x1)) |
|
|
|
|
|
if iter_count % 100 == 0: |
|
print("Iteration {}: Cost = {}, Theta0 = {}, Theta1 = {}, Theta2 = {}".format(iter_count, cost, Theta0.item(), Theta1.item(), |
|
Theta2.item())) |
|
|
|
|
|
if iter_count > 0 and torch.abs(cost - prev_cost) < 0.0001: |
|
print("Converged after {} iterations".format(iter_count)) |
|
break |
|
|
|
|
|
cost.backward() |
|
|
|
|
|
with torch.no_grad(): |
|
Theta0 -= alpha * Theta0.grad |
|
Theta1 -= alpha * Theta1.grad |
|
Theta2 -= alpha * Theta2.grad |
|
|
|
|
|
Theta0.grad.zero_() |
|
Theta1.grad.zero_() |
|
Theta2.grad.zero_() |
|
|
|
|
|
iter_count += 1 |
|
prev_cost = cost |
|
|
|
|
|
print("Final values: Theta0 = {}, Theta1 = {}, Theta2 = {}".format(Theta0.item(), Theta1.item(), Theta2.item())) |
|
print("Final Cost: Cost = {}".format(cost.item())) |
|
print("Final values: y_pred = {}, y_actual = {}".format(y_pred, y_actual)) |
|
|