#### pytorch import torch import torch.nn as nn import torch.optim as optim # Define the model using nn.Sequential model = nn.Sequential( nn.Linear(2, 5), # First layer: 2 input features (age, blood pressure), 5 neurons nn.ReLU(), # ReLU activation after first layer nn.Linear(5, 1), # Second layer: 5 neurons to 1 output nn.Sigmoid() # Sigmoid activation for binary classification ) # Initialize the model, loss function, and optimizer (Adam instead of SGD) criterion = nn.BCELoss() # Binary cross-entropy for binary classification optimizer = optim.Adam(model.parameters(), lr=0.01) # Using Adam optimizer # Expanded simulated dataset: [age, blood pressure] -> label (disease or not) data = torch.tensor([ [25, 120], # Age 25, Blood pressure 120 [45, 140], # Age 45, Blood pressure 140 [35, 130], # Age 35, Blood pressure 130 [50, 160], # Age 50, Blood pressure 160 [60, 170], # Age 60, Blood pressure 170 [30, 115], # Age 30, Blood pressure 115 [55, 155], # Age 55, Blood pressure 155 [40, 135], # Age 40, Blood pressure 135 [65, 180], # Age 65, Blood pressure 180 [70, 190], # Age 70, Blood pressure 190 [32, 125], # Age 32, Blood pressure 125 [48, 150], # Age 48, Blood pressure 150 [58, 165], # Age 58, Blood pressure 165 [42, 145], # Age 42, Blood pressure 145 [38, 132] # Age 38, Blood pressure 132 ], dtype=torch.float32) # Labels: 0 (no disease), 1 (disease) labels = torch.tensor([ [0], [1], [0], [1], [1], [0], [1], [0], [1], [1], [0], [1], [1], [1], [0] ], dtype=torch.float32) # Training loop epochs = 1000 for epoch in range(epochs): # Forward pass outputs = model(data) loss = criterion(outputs, labels) # Backward pass and optimization optimizer.zero_grad() # Clear gradients from previous step loss.backward() # Compute gradients optimizer.step() # Update model parameters # Print loss every 100 epochs if (epoch+1) % 100 == 0: print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}') # Testing the model test_data = torch.tensor([ [40, 145], # New test data: Age 40, Blood pressure 145 [30, 110], # Age 30, Blood pressure 110 [50, 170], # Age 50, Blood pressure 170 [60, 160], # Age 60, Blood pressure 160 ], dtype=torch.float32) with torch.no_grad(): predictions = model(test_data) print("\nPredictions (probabilities):") print(predictions) # Convert probabilities to binary predictions (threshold at 0.5) binary_predictions = (predictions >= 0.5).float() print("\nBinary Predictions (0: No disease, 1: Disease):") print(binary_predictions) #### tensorflow import tensorflow as tf import numpy as np # Define the model using tf.keras.Sequential model = tf.keras.Sequential([ tf.keras.Input(shape=(2,)), # Explicit Input layer with input shape (2,) tf.keras.layers.Dense(5, activation='relu'), # First hidden layer with 5 neurons tf.keras.layers.Dense(1, activation='sigmoid') # Output layer with 1 neuron, sigmoid activation ]) # Compile the model with binary cross-entropy loss and Adam optimizer model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.01), loss='binary_crossentropy') # Expanded simulated dataset: [age, blood pressure] -> label (disease or not) data = np.array([ [25, 120], # Age 25, Blood pressure 120 [45, 140], # Age 45, Blood pressure 140 [35, 130], # Age 35, Blood pressure 130 [50, 160], # Age 50, Blood pressure 160 [60, 170], # Age 60, Blood pressure 170 [30, 115], # Age 30, Blood pressure 115 [55, 155], # Age 55, Blood pressure 155 [40, 135], # Age 40, Blood pressure 135 [65, 180], # Age 65, Blood pressure 180 [70, 190], # Age 70, Blood pressure 190 [32, 125], # Age 32, Blood pressure 125 [48, 150], # Age 48, Blood pressure 150 [58, 165], # Age 58, Blood pressure 165 [42, 145], # Age 42, Blood pressure 145 [38, 132] # Age 38, Blood pressure 132 ], dtype=np.float32) # Labels: 0 (no disease), 1 (disease) labels = np.array([ [0], [1], [0], [1], [1], [0], [1], [0], [1], [1], [0], [1], [1], [1], [0] ], dtype=np.float32) # Training the model epochs = 1000 model.fit(data, labels, epochs=epochs, verbose=0) # verbose=0 suppresses output during training # Display loss every 100 epochs for epoch in range(100, epochs+1, 100): loss = model.evaluate(data, labels, verbose=0) print(f'Epoch [{epoch}/{epochs}], Loss: {loss:.4f}') # Testing the model test_data = np.array([ [40, 145], # New test data: Age 40, Blood pressure 145 [30, 110], # Age 30, Blood pressure 110 [50, 170], # Age 50, Blood pressure 170 [60, 160], # Age 60, Blood pressure 160 ], dtype=np.float32) # Make predictions predictions = model.predict(test_data) print("\nPredictions (probabilities):") print(predictions) # Convert probabilities to binary predictions (threshold at 0.5) binary_predictions = (predictions >= 0.5).astype(np.float32) print("\nBinary Predictions (0: No disease, 1: Disease):") print(binary_predictions) import torch import time # Choose device: "cuda" for NVIDIA , "mps" for Apple , or default to "cpu" device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" print(f"Using device: {device}") # GPU matrix multiplication start_time = time.time() a = torch.randn(10000, 10000, device=device) b = torch.randn(10000, 10000, device=device) torch.matmul(a, b) torch.cuda.synchronize() if device == "cuda" else torch.mps.synchronize() elapsed_time = time.time() - start_time print(f"GPU ({device.upper()}) Time: {elapsed_time}") # CPU matrix multiplication for comparison start_time = time.time() a = torch.randn(10000, 10000) b = torch.randn(10000, 10000) torch.matmul(a, b) elapsed_time = time.time() - start_time print(f"CPU Time: {elapsed_time}")