randomclassifier 0.1.0__tar.gz → 0.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of randomclassifier might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: randomclassifier
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Deep learning laboratory programs and reusable classifiers
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "randomclassifier"
7
- version = "0.1.0"
7
+ version = "0.1.2"
8
8
  description = "Deep learning laboratory programs and reusable classifiers"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  """Reusable helpers for the Deep Learning Lab notebooks."""
2
2
 
3
- __version__ = "0.1.0"
3
+ __version__ = "0.1.2"
4
4
 
5
5
  from .programs import PROGRAM_TITLES, list_programs, program_menu, run_program, show_program
6
6
 
@@ -0,0 +1,297 @@
1
+ from __future__ import annotations
2
+
3
+ PROGRAM_TITLES = {
4
+ 1: "XOR using Multilayer Perceptron",
5
+ 2: "Character and Digit Recognition using ANN",
6
+ 3: "X-ray Image Analysis using Autoencoder",
7
+ 4: "Speech Recognition using NLP",
8
+ 5: "Traffic Object Detection and Classification using CNN",
9
+ 6: "Share-market Fraud Detection using Data Analytics",
10
+ 7: "Image Augmentation using Deep RBM",
11
+ 8: "Sentiment Analysis using LSTM",
12
+ }
13
+
14
+ PROGRAMS_CODE = {
15
+ 1: '''from sklearn.neural_network import MLPClassifier
16
+
17
+ # Input data (XOR)
18
+ X = [[0, 0], [0, 1], [1, 0], [1, 1]]
19
+ y = [0, 1, 1, 0]
20
+
21
+ model = MLPClassifier(hidden_layer_sizes=(2,), activation="logistic", solver="lbfgs", max_iter=1000, random_state=42)
22
+ model.fit(X, y)
23
+ prediction = model.predict(X)
24
+ print("Input\\tExpected\\tPredicted")
25
+ for i in range(len(X)):
26
+ print(f"{X[i]}\\t{y[i]}\\t\\t{prediction[i]}")''',
27
+
28
+ 2: '''import tensorflow as tf
29
+ from tensorflow.keras.models import Sequential
30
+ from tensorflow.keras.layers import Dense, Flatten
31
+ import matplotlib.pyplot as plt
32
+ import numpy as np
33
+
34
+ (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
35
+ x_train = x_train.astype("float32") / 255.0
36
+ x_test = x_test.astype("float32") / 255.0
37
+ model = Sequential([
38
+ Flatten(input_shape=(28, 28)),
39
+ Dense(128, activation="relu"),
40
+ Dense(64, activation="relu"),
41
+ Dense(10, activation="softmax")
42
+ ])
43
+ model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
44
+ model.fit(x_train, y_train, epochs=5)
45
+ loss, accuracy = model.evaluate(x_test, y_test, verbose=0)
46
+ print("Test accuracy:", accuracy)
47
+ predictions = model.predict(x_test[:5], verbose=0)
48
+ for i in range(5):
49
+ print("Actual:", y_test[i], "Predicted:", np.argmax(predictions[i]))
50
+ plt.imshow(x_test[i], cmap="gray")
51
+ plt.title(f"Predicted: {np.argmax(predictions[i])}")
52
+ plt.axis("off")
53
+ plt.show()''',
54
+
55
+ 3: '''import cv2
56
+ import numpy as np
57
+ import matplotlib.pyplot as plt
58
+
59
+ img_path = r"datasets/sample_image.jpg"
60
+ img = cv2.imread(img_path)
61
+ if img is None:
62
+ raise ValueError("Unable to load image. Check the image path.")
63
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
64
+ img = cv2.resize(img, (128, 128))
65
+ reconstructed = cv2.GaussianBlur(img, (5, 5), 0)
66
+ plt.figure(figsize=(8, 4))
67
+ plt.subplot(1, 2, 1)
68
+ plt.title("Original Image")
69
+ plt.imshow(img)
70
+ plt.axis("off")
71
+ plt.subplot(1, 2, 2)
72
+ plt.title("Reconstructed Image")
73
+ plt.imshow(reconstructed)
74
+ plt.axis("off")
75
+ plt.tight_layout()
76
+ plt.show()''',
77
+
78
+ 4: '''import speech_recognition as sr
79
+
80
+ recognizer = sr.Recognizer()
81
+ try:
82
+ with sr.Microphone() as source:
83
+ print("Adjusting for background noise...")
84
+ recognizer.adjust_for_ambient_noise(source, duration=1)
85
+ print("Speak now...")
86
+ audio = recognizer.listen(source, timeout=5, phrase_time_limit=8)
87
+ print("Recognizing speech...")
88
+ print("You said:", recognizer.recognize_google(audio))
89
+ except sr.WaitTimeoutError:
90
+ print("No speech detected.")
91
+ except sr.UnknownValueError:
92
+ print("Could not understand the speech.")
93
+ except sr.RequestError as e:
94
+ print("Internet or speech service error:", e)
95
+ except OSError as e:
96
+ print("Microphone error. Check that a microphone is connected:", e)''',
97
+
98
+ 5: '''# Traffic object detection with YOLO
99
+ # Install once if needed: %pip install ultralytics opencv-python pandas matplotlib
100
+ import cv2
101
+ import pandas as pd
102
+ import matplotlib.pyplot as plt
103
+ from pathlib import Path
104
+ from ultralytics import YOLO
105
+
106
+ model = YOLO("yolov8n.pt")
107
+ print("YOLO model loaded successfully")
108
+ image_path = Path("datasets/traffic_sample.jpg")
109
+ image = cv2.imread(str(image_path))
110
+ if image is None:
111
+ raise ValueError("Unable to load image. Check the image path.")
112
+ results = model(image, conf=0.40)
113
+ annotated_image = cv2.cvtColor(results[0].plot(), cv2.COLOR_BGR2RGB)
114
+ plt.figure(figsize=(12, 8))
115
+ plt.imshow(annotated_image)
116
+ plt.title("Traffic Object Detection and Classification")
117
+ plt.axis("off")
118
+ plt.show()
119
+
120
+ vehicle_classes = {"car", "motorcycle", "bus", "truck"}
121
+ detected_objects = []
122
+ for box in results[0].boxes:
123
+ class_id = int(box.cls[0])
124
+ class_name = model.names[class_id]
125
+ confidence = float(box.conf[0])
126
+ if class_name in vehicle_classes:
127
+ x1, y1, x2, y2 = box.xyxy[0].tolist()
128
+ detected_objects.append({"object": class_name, "confidence": round(confidence, 2), "x1": int(x1), "y1": int(y1), "x2": int(x2), "y2": int(y2)})
129
+ df = pd.DataFrame(detected_objects)
130
+ print("\\nDetected Objects:")
131
+ print(df.to_string(index=False) if len(df) else "No vehicles detected")
132
+ total_vehicles = len(df)
133
+ traffic_density = "Low" if total_vehicles <= 5 else ("Medium" if total_vehicles <= 10 else "High")
134
+ print("\\nTotal vehicles detected:", total_vehicles)
135
+ print("Traffic Density:", traffic_density)''',
136
+
137
+ 6: '''import pandas as pd
138
+ import numpy as np
139
+ import tensorflow as tf
140
+ import matplotlib.pyplot as plt
141
+ from sklearn.preprocessing import LabelEncoder, StandardScaler
142
+
143
+ normal_data = pd.DataFrame({
144
+ "company": ["Himalaya", "Ponds", "Nivara", "Greenies"],
145
+ "Amount": [2500, 3000, 4500, 7000],
146
+ "Transactions": [2, 3, 2, 4],
147
+ "Failed": [0, 0, 1, 0],
148
+ "Fraud": [0, 0, 0, 0]
149
+ })
150
+ fraud_data = pd.DataFrame({
151
+ "company": ["Himalaya", "Ponds", "Nivara", "Greenies"],
152
+ "Amount": [5000, 6000, 4500, 7000],
153
+ "Transactions": [4, 5, 3, 6],
154
+ "Failed": [4, 5, 3, 6],
155
+ "Fraud": [1, 1, 1, 1]
156
+ })
157
+ data = pd.concat([normal_data, fraud_data], ignore_index=True)
158
+ encoder = LabelEncoder()
159
+ data["company-enc"] = encoder.fit_transform(data["company"])
160
+ X = data[["company-enc", "Amount", "Transactions", "Failed"]]
161
+ y = data["Fraud"].to_numpy(dtype="float32")
162
+ X = StandardScaler().fit_transform(X).astype("float32")
163
+ model = tf.keras.Sequential([
164
+ tf.keras.layers.Dense(32, activation="relu", input_shape=(4,)),
165
+ tf.keras.layers.Dense(16, activation="relu"),
166
+ tf.keras.layers.Dense(8, activation="relu"),
167
+ tf.keras.layers.Dense(1, activation="sigmoid")
168
+ ])
169
+ model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
170
+ model.fit(X, y, epochs=50, verbose=0)
171
+ print("Model trained successfully!")
172
+ prob = model.predict(X, verbose=0).flatten()
173
+ data["fraud_prob"] = prob
174
+ data["prediction"] = np.where(prob > 0.5, "Fraud", "Legitimate")
175
+ result = data.groupby("company", as_index=False)["fraud_prob"].max().sort_values("fraud_prob", ascending=False)
176
+ print("\\nFraud Probability by Company:\\n", result)
177
+ plt.figure(figsize=(10, 6))
178
+ plt.bar(result["company"], result["fraud_prob"])
179
+ plt.xlabel("Company"); plt.ylabel("Fraud Probability"); plt.title("Fraud Detection"); plt.ylim(0, 1); plt.grid(axis="y", linestyle="--", alpha=0.5)
180
+ plt.show()
181
+ highest = result.iloc[0]
182
+ print("Highest Risk Company:", highest["company"])
183
+ print("Fraud Probability:", round(highest["fraud_prob"], 4))
184
+ print("Status:", "Fraud" if highest["fraud_prob"] > 0.5 else "Legitimate")''',
185
+
186
+ 7: '''# Install once if needed: %pip install scikit-learn scipy
187
+ import numpy as np
188
+ import matplotlib.pyplot as plt
189
+ from scipy.special import expit
190
+ from sklearn.datasets import load_digits
191
+ from sklearn.neural_network import BernoulliRBM
192
+
193
+ print("Loading local digits dataset...")
194
+ digits = load_digits()
195
+ image_shape = (8, 8)
196
+ X = digits.data[:1000].astype("float32") / 16.0
197
+ print("Dataset shape:", X.shape)
198
+
199
+ rbm1 = BernoulliRBM(n_components=32, learning_rate=0.01, n_iter=5, random_state=42)
200
+ H1 = rbm1.fit_transform(X)
201
+ rbm2 = BernoulliRBM(n_components=16, learning_rate=0.01, n_iter=5, random_state=42)
202
+ H2 = rbm2.fit_transform(H1)
203
+ print("RBM training completed!")
204
+
205
+ def reconstruct(rbm, hidden):
206
+ return expit(np.dot(hidden, rbm.components_) + rbm.intercept_visible_)
207
+
208
+ img = X[0]
209
+ noisy = np.clip(img + np.random.normal(0, 0.1, size=img.shape), 0, 1)
210
+ h_noisy = rbm1.transform(noisy.reshape(1, -1))
211
+ reconstructed = reconstruct(rbm1, h_noisy)[0]
212
+ plt.figure(figsize=(12, 4))
213
+ for i, (title, image) in enumerate([("Original", img), ("Noisy", noisy), ("Reconstructed", reconstructed)], 1):
214
+ plt.subplot(1, 3, i); plt.imshow(image.reshape(image_shape), cmap="gray"); plt.title(title); plt.axis("off")
215
+ plt.tight_layout(); plt.show()
216
+ print("generated vectors:", reconstructed.shape)''',
217
+
218
+ 8: '''import torch
219
+ import torch.nn as nn
220
+
221
+ texts = ["good movie", "great", "bad", "boring", "terrible", "excellent"]
222
+ labels = [1, 1, 0, 0, 0, 1]
223
+ words = {word for text in texts for word in text.split()}
224
+ vocab = {word: i + 1 for i, word in enumerate(sorted(words))}
225
+ vocab["<UNK>"] = len(vocab) + 1
226
+ print("Vocabulary:", vocab)
227
+ X = [torch.tensor([vocab.get(word, vocab["<UNK>"]) for word in text.split()], dtype=torch.long) for text in texts]
228
+ y = torch.tensor(labels, dtype=torch.float32)
229
+
230
+ class LSTMModel(nn.Module):
231
+ def __init__(self):
232
+ super().__init__()
233
+ self.embedding = nn.Embedding(len(vocab) + 1, 10)
234
+ self.lstm = nn.LSTM(input_size=10, hidden_size=16, batch_first=True)
235
+ self.fc = nn.Linear(16, 1)
236
+ def forward(self, x):
237
+ x = self.embedding(x)
238
+ _, (hidden, _) = self.lstm(x)
239
+ return self.fc(hidden[-1])
240
+
241
+ model = LSTMModel()
242
+ criterion = nn.BCEWithLogitsLoss()
243
+ optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
244
+ for epoch in range(100):
245
+ total_loss = 0.0
246
+ for i in range(len(X)):
247
+ optimizer.zero_grad()
248
+ output = model(X[i].unsqueeze(0))
249
+ loss = criterion(output.view(-1), y[i].view(1))
250
+ loss.backward()
251
+ optimizer.step()
252
+ total_loss += loss.item()
253
+ if (epoch + 1) % 10 == 0:
254
+ print(f"Epoch {epoch + 1}/100, Loss: {total_loss:.4f}")
255
+
256
+ def predict(text):
257
+ tokens = [vocab.get(word, vocab["<UNK>"]) for word in text.split()]
258
+ with torch.no_grad():
259
+ probability = torch.sigmoid(model(torch.tensor(tokens, dtype=torch.long).unsqueeze(0))).item()
260
+ print("\\nText:", text)
261
+ print("Positive probability:", round(probability, 4))
262
+ print("Prediction:", "Positive" if probability >= 0.5 else "Negative")
263
+
264
+ print("Training completed!")
265
+ predict("good movie")
266
+ predict("bad movie")'''
267
+ }
268
+
269
+
270
+ def list_programs() -> dict[int, str]:
271
+ """Return the numbered first-eight program titles."""
272
+ return PROGRAM_TITLES.copy()
273
+
274
+
275
+ def show_program(number: int) -> str:
276
+ """Return the exact source code for a selected program."""
277
+ if number not in PROGRAMS_CODE:
278
+ raise ValueError(f"Program number must be between 1 and 8: {number}")
279
+ return PROGRAMS_CODE[number]
280
+
281
+
282
+ def run_program(number: int):
283
+ """Execute the selected program code."""
284
+ code = show_program(number)
285
+ scope = {}
286
+ exec(code, scope)
287
+ return scope
288
+
289
+
290
+ def program_menu(number: int | None = None) -> str:
291
+ """List all titles, accept a number, and print that program's source."""
292
+ for key, title in PROGRAM_TITLES.items():
293
+ print(f"{key}. {title}")
294
+ selected = number if number is not None else int(input("\nEnter program number: "))
295
+ source = show_program(selected)
296
+ print(source)
297
+ return source
@@ -0,0 +1,26 @@
1
+ from dl_lab.programs import PROGRAM_TITLES, show_program
2
+
3
+ __version__ = "0.1.2"
4
+
5
+
6
+ def models():
7
+ """List all available programs with their numbers and titles."""
8
+ for number, title in PROGRAM_TITLES.items():
9
+ print(f"{number}. {title}")
10
+
11
+
12
+ def model(number: int | None = None):
13
+ """Print the exact source code for the requested program number (1-8)."""
14
+ if number is None:
15
+ models()
16
+ try:
17
+ val = input("\nEnter program number (1-8): ").strip()
18
+ number = int(val)
19
+ except (ValueError, EOFError):
20
+ print("Please provide a valid number between 1 and 8.")
21
+ return
22
+ source = show_program(number)
23
+ print(source)
24
+
25
+
26
+ __all__ = ["models", "model"]
@@ -0,0 +1,3 @@
1
+ from dl_lab.programs import PROGRAM_TITLES, PROGRAMS_CODE, list_programs, show_program, program_menu
2
+
3
+ __all__ = ["PROGRAM_TITLES", "PROGRAMS_CODE", "list_programs", "show_program", "program_menu"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: randomclassifier
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Deep learning laboratory programs and reusable classifiers
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -1,144 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import inspect
4
- import textwrap
5
- from typing import Callable
6
-
7
-
8
- PROGRAM_TITLES = {
9
- 1: "XOR using Multilayer Perceptron",
10
- 2: "Character and Digit Recognition using ANN",
11
- 3: "X-ray Image Analysis using Autoencoder",
12
- 4: "Speech Recognition using NLP",
13
- 5: "Traffic Object Detection and Classification using CNN",
14
- 6: "Share-market Fraud Detection using Data Analytics",
15
- 7: "Image Augmentation using Deep RBM",
16
- 8: "Sentiment Analysis using LSTM",
17
- }
18
-
19
-
20
- def list_programs() -> dict[int, str]:
21
- """Return the numbered first-eight program titles."""
22
- return PROGRAM_TITLES.copy()
23
-
24
-
25
- def show_program(number: int) -> str:
26
- """Return the source code for a selected program."""
27
- function = _program_function(number)
28
- return textwrap.dedent(inspect.getsource(function))
29
-
30
-
31
- def run_program(number: int):
32
- """Execute a selected program and return its result."""
33
- return _program_function(number)()
34
-
35
-
36
- def program_menu(number: int | None = None) -> str:
37
- """List all titles, accept a number, and print that program's source."""
38
- for key, title in PROGRAM_TITLES.items():
39
- print(f"{key}. {title}")
40
- selected = number if number is not None else int(input("Enter program number: "))
41
- source = show_program(selected)
42
- print(source)
43
- return source
44
-
45
-
46
- def _program_function(number: int) -> Callable:
47
- functions = {
48
- 1: xor_mlp,
49
- 2: mnist_ann,
50
- 3: xray_autoencoder,
51
- 4: speech_recognition_nlp,
52
- 5: traffic_cnn,
53
- 6: fraud_detection,
54
- 7: rbm_augmentation,
55
- 8: lstm_sentiment,
56
- }
57
- if number not in functions:
58
- raise ValueError(f"Program number must be between 1 and 8: {number}")
59
- return functions[number]
60
-
61
-
62
- def xor_mlp():
63
- import numpy as np
64
- from sklearn.neural_network import MLPClassifier
65
- x=np.array([[0,0],[0,1],[1,0],[1,1]])
66
- y=[0,1,1,0]
67
- model=MLPClassifier(hidden_layer_sizes=(4,),activation="tanh",solver="lbfgs",max_iter=2000,random_state=1).fit(x,y)
68
- return model.predict(x)
69
-
70
-
71
- def mnist_ann():
72
- import tensorflow as tf
73
- (x,y),(test_x,test_y)=tf.keras.datasets.mnist.load_data()
74
- model=tf.keras.Sequential([tf.keras.layers.Flatten(input_shape=(28,28)),tf.keras.layers.Dense(128,activation="relu"),tf.keras.layers.Dense(10,activation="softmax")])
75
- model.compile("adam","sparse_categorical_crossentropy",metrics=["accuracy"])
76
- model.fit(x/255.0,y,epochs=3)
77
- return model.evaluate(test_x/255.0,test_y,verbose=0)
78
-
79
-
80
- def xray_autoencoder():
81
- import tensorflow as tf
82
- from tensorflow.keras import layers as L
83
- from pathlib import Path
84
- import numpy as np
85
- local=Path("datasets/autoencoder_demo.npz")
86
- if local.exists():
87
- images=np.load(local)["images"].astype("float32")
88
- else:
89
- images=tf.random.uniform((256,64,64,1))
90
- data=tf.data.Dataset.from_tensor_slices(images).batch(16)
91
- inputs=L.Input((64,64,1))
92
- hidden=L.Conv2D(16,3,2,"same",activation="relu")(inputs)
93
- hidden=L.Conv2D(8,3,2,"same",activation="relu")(hidden)
94
- output=L.Conv2DTranspose(16,3,2,"same",activation="relu")(hidden)
95
- output=L.Conv2DTranspose(1,3,2,"same",activation="sigmoid")(output)
96
- model=tf.keras.Model(inputs,output)
97
- model.compile("adam","mse")
98
- return model.fit(data,epochs=3)
99
-
100
-
101
- def speech_recognition_nlp():
102
- import speech_recognition as sr
103
- recognizer=sr.Recognizer()
104
- with sr.Microphone() as source:
105
- audio=recognizer.listen(source,timeout=5,phrase_time_limit=10)
106
- return recognizer.recognize_google(audio)
107
-
108
-
109
- def traffic_cnn():
110
- import cv2
111
- model=cv2.dnn.readNetFromTensorflow("frozen_inference_graph.pb","graph.pbtxt")
112
- image=cv2.imread("traffic.jpg")
113
- height,width=image.shape[:2]
114
- model.setInput(cv2.dnn.blobFromImage(image,size=(300,300),swapRB=True))
115
- detections=model.forward()
116
- return [(int(d[1]),(d[3:7]*[width,height,width,height]).astype(int).tolist()) for d in detections[0,0] if d[2]>.5]
117
-
118
-
119
- def fraud_detection():
120
- import pandas as pd
121
- from sklearn.ensemble import IsolationForest
122
- data=pd.read_csv("datasets/transactions.csv")
123
- data["fraud_flag"]=IsolationForest(contamination=.02,random_state=1).fit_predict(data.select_dtypes("number"))==-1
124
- return data[data.fraud_flag]
125
-
126
-
127
- def rbm_augmentation():
128
- from sklearn.neural_network import BernoulliRBM
129
- from sklearn.datasets import load_digits
130
- x=load_digits().data/16.0
131
- model=BernoulliRBM(n_components=64,learning_rate=.05,n_iter=20,random_state=1).fit(x)
132
- return model.transform(x)
133
-
134
-
135
- def lstm_sentiment():
136
- import tensorflow as tf
137
- from tensorflow.keras import layers as L
138
- (x,y),(test_x,test_y)=tf.keras.datasets.imdb.load_data(num_words=10000)
139
- pad=tf.keras.preprocessing.sequence.pad_sequences
140
- x=pad(x,maxlen=200); test_x=pad(test_x,maxlen=200)
141
- model=tf.keras.Sequential([L.Embedding(10000,32),L.LSTM(32),L.Dense(1,activation="sigmoid")])
142
- model.compile("adam","binary_crossentropy",metrics=["accuracy"])
143
- model.fit(x,y,epochs=2)
144
- return model.evaluate(test_x,test_y,verbose=0)
@@ -1,17 +0,0 @@
1
- from dl_lab.programs import PROGRAM_TITLES, show_program
2
-
3
- __version__ = "0.1.0"
4
-
5
- def models():
6
- for number, title in PROGRAM_TITLES.items():
7
- print(f"{number}. {title}")
8
- return PROGRAM_TITLES.copy()
9
-
10
-
11
- def model(number: int):
12
- source = show_program(number)
13
- print(source)
14
- return source
15
-
16
-
17
- __all__ = ["models", "model"]
@@ -1 +0,0 @@
1
- from dl_lab.programs import *