Skip to content

Commit 23ea3d2

Browse files
Merge pull request #14 from Programmer-RD-AI/25/06/2023
25/06/2023
2 parents 7e9538f + a49ef9a commit 23ea3d2

File tree

12 files changed

+1483
-32
lines changed

12 files changed

+1483
-32
lines changed

.ipynb_checkpoints/01-checkpoint.ipynb

Lines changed: 202 additions & 15 deletions
Large diffs are not rendered by default.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"id": "09e4eaf8-3998-4393-abea-1afcc82a954d",
7+
"metadata": {},
8+
"outputs": [],
9+
"source": []
10+
}
11+
],
12+
"metadata": {
13+
"kernelspec": {
14+
"display_name": "Python 3 (ipykernel)",
15+
"language": "python",
16+
"name": "python3"
17+
},
18+
"language_info": {
19+
"codemirror_mode": {
20+
"name": "ipython",
21+
"version": 3
22+
},
23+
"file_extension": ".py",
24+
"mimetype": "text/x-python",
25+
"name": "python",
26+
"nbconvert_exporter": "python",
27+
"pygments_lexer": "ipython3",
28+
"version": "3.8.8"
29+
}
30+
},
31+
"nbformat": 4,
32+
"nbformat_minor": 5
33+
}

.ipynb_checkpoints/Redo_01-checkpoint.ipynb

Lines changed: 427 additions & 0 deletions
Large diffs are not rendered by default.

.virtual_documents/01.ipynb.py

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
# Create data
3030

3131
start = 0.0
32-
end = 5.0
32+
end = 1.0
3333
step = 0.02
3434
X = torch.arange(start, end ,step).unsqueeze(dim=1).to('cuda')
3535
y = (weight * X + bias).to('cuda')
@@ -119,6 +119,9 @@ def forward(self,X):
119119
from tqdm import tqdm
120120
# the model gets to see the data once
121121
epochs = 100
122+
epoch_count = []
123+
loss_values = []
124+
test_loss_values = []
122125

123126

124127
for epoch in tqdm(range(epochs)):
@@ -140,7 +143,20 @@ def forward(self,X):
140143
# Gradient Descent
141144
optimizer.step()
142145

143-
model_0.eval() # turns off gradient tracking
146+
model_0.eval() # turns off stf like dropout and batchnormalisation
147+
148+
with torch.inference_mode(): # turns off gradient tracking
149+
# 1. Do the forward pass
150+
test_pred = model_0(X_test)
151+
152+
# Calculate the loss
153+
test_loss = loss_fn(test_pred,y_test)
154+
155+
if epoch % 10 == 0:
156+
epoch_count.append(epoch)
157+
loss_values.append(loss.cpu().detach())
158+
test_loss_values.append(test_loss.cpu().detach())
159+
print(f"Epoch: {epoch} | Test : {test_loss} | Loss : {loss}")
144160

145161

146162
y_preds[:5],y_train[:5]
@@ -152,4 +168,32 @@ def forward(self,X):
152168
plot_predictions(predictions=y_preds.cpu())
153169

154170

171+
model_0.state_dict()
172+
173+
174+
weight,bias
175+
176+
177+
# Plot the loss curves
178+
plt.plot(epoch_count,loss_values,label='Train Loss')
179+
plt.plot(epoch_count,test_loss_values,label='Test Loss')
180+
plt.title("Loss Curves")
181+
plt.ylabel("Loss")
182+
plt.xlabel("Epochs")
183+
plt.legend()
184+
185+
186+
# Saving out PyTorch model
187+
torch.save(model.state_dict(),'./models/01/00.pth')
188+
189+
190+
state_dict_00 = torch.load("./models/01/00.pth")
191+
192+
193+
model_01 = LinearRegressionModel()
194+
195+
196+
model_01.load_state_dict(state_dict_00)
197+
198+
155199

.virtual_documents/02.ipynb.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

.virtual_documents/Redo_01.ipynb.py

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import torch
2+
from torch import nn
3+
from torch import optim
4+
import matplotlib.pyplot as plt
5+
import pandas as pd
6+
import numpy as np
7+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
8+
9+
10+
torch.__version__
11+
12+
13+
# y = mx+c
14+
m = 0.69
15+
c = 0.96
16+
X = torch.arange(0,1,0.002).to(device)
17+
y = torch.tensor(m*X+c).to(device)
18+
19+
20+
from sklearn.model_selection import train_test_split
21+
22+
23+
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.25)
24+
25+
26+
class LinearRegressionModel(nn.Module):
27+
def __init__(self):
28+
super().__init__()
29+
self.m = nn.Parameter(torch.randn(1))
30+
self.c = nn.Parameter(torch.randn(1))
31+
32+
def forward(self,X):
33+
return X*self.m+self.c
34+
35+
36+
model_0 = LinearRegressionModel().to(device)
37+
criterion = nn.L1Loss()
38+
optimizer = optim.Adam(model_0.parameters(),lr=0.01)
39+
40+
41+
epochs = 100
42+
43+
44+
m_iter = []
45+
c_iter = []
46+
train_loss_iter = []
47+
test_loss_iter = []
48+
49+
50+
for epoch in range(epochs):
51+
# train
52+
model_0.train()
53+
y_preds = model_0(X_train)
54+
loss = criterion(y_preds,y_train)
55+
optimizer.zero_grad()
56+
loss.backward()
57+
optimizer.step()
58+
# test
59+
model_0.eval()
60+
with torch.inference_mode():
61+
y_test_preds = model_0(X_test)
62+
test_loss = criterion(y_test_preds,y_test)
63+
paramters = dict(model_0.state_dict())
64+
m_iter.append(paramters['m'].cpu())
65+
c_iter.append(paramters['c'].cpu())
66+
train_loss_iter.append(loss.cpu().detach().numpy())
67+
test_loss_iter.append(test_loss.cpu().detach().numpy())
68+
69+
70+
model_0.state_dict()
71+
72+
73+
plt.plot(range(epochs),m_iter)
74+
plt.xlabel('epochs')
75+
plt.ylabel('m_iter')
76+
plt.title("M_iter over time")
77+
plt.show()
78+
79+
80+
plt.plot(range(epochs),c_iter)
81+
plt.xlabel('epochs')
82+
plt.ylabel('c_iter')
83+
plt.title("c_iter over time")
84+
plt.show()
85+
86+
87+
plt.plot(range(epochs),test_loss_iter,'b')
88+
plt.plot(range(epochs),train_loss_iter,'r')
89+
plt.xlabel('epochs')
90+
plt.ylabel('loss')
91+
plt.title("Losss over time")
92+
plt.legend()
93+
plt.show()
94+
95+
96+
y_preds[5:7],y_train[5:7]
97+
98+
99+
state_dict = model_0.state_dict()
100+
101+
102+
torch.save(state_dict,'./models/01/redo_model_00.pth')
103+
104+
105+
model_01 = LinearRegressionModel()
106+
107+
108+
model_01.load_state_dict(torch.load('./models/01/redo_model_00.pth'))
109+
110+
111+

.virtual_documents/Untitled.ipynb.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

01.ipynb

Lines changed: 202 additions & 15 deletions
Large diffs are not rendered by default.

02.ipynb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"id": "09e4eaf8-3998-4393-abea-1afcc82a954d",
7+
"metadata": {},
8+
"outputs": [],
9+
"source": []
10+
}
11+
],
12+
"metadata": {
13+
"kernelspec": {
14+
"display_name": "Python 3 (ipykernel)",
15+
"language": "python",
16+
"name": "python3"
17+
},
18+
"language_info": {
19+
"codemirror_mode": {
20+
"name": "ipython",
21+
"version": 3
22+
},
23+
"file_extension": ".py",
24+
"mimetype": "text/x-python",
25+
"name": "python",
26+
"nbconvert_exporter": "python",
27+
"pygments_lexer": "ipython3",
28+
"version": "3.8.8"
29+
}
30+
},
31+
"nbformat": 4,
32+
"nbformat_minor": 5
33+
}

0 commit comments

Comments
 (0)