Python3 code for How to formulate random 3D rotation matrix
- User
Python3 code for How to formulate random 3D rotation matrix
- Assistant
import numpy as np from scipy.spatial.transform import Rotation
Function to generate random 3D rotation matrix
def random_rotation_matrix(): # Generate random axis of rotation axis = np.random.rand(3) - 0.5 axis /= np.linalg.norm(axis)
# Generate random angle of rotation angle = np.random.rand() * 2 * np.pi # Create rotation object using axis and angle r = Rotation.from_rotvec(angle * axis) # Get the rotation matrix rotation_matrix = r.as_matrix() return rotation_matrixExample usage
rotation_matrix = random_rotation_matrix() print(rotation_matrix)
- User
python3 code for backpropogation algorithm
- Assistant
- User
python3 code for logistic regressions
- Assistant
import numpy as np
class LogisticRegression: def init(self, learning_rate=0.01, num_iterations=1000): self.learning_rate = learning_rate self.num_iterations = num_iterations
def sigmoid(self, z): # Sigmoid activation function return 1 / (1 + np.exp(-z)) def initialize_parameters(self, n_features): # Initialize the parameters (weights and bias) self.theta = np.zeros((n_features, 1)) self.bias = 0 def compute_cost(self, X, y): # Compute the cost (error) with current parameters m = X.shape[0] # number of training examples h = self.sigmoid(np.dot(X, self.theta) + self.bias) # predicted outputs cost = (-1/m) * np.sum(y * np.log(h) + (1-y) * np.log(1-h)) # binary cross-entropy loss return cost def gradient_descent(self, X, y): # Gradient descent to update parameters and minimize the cost m = X.shape[0] # number of training examples for i in range(self.num_iterations): h = self.sigmoid(np.dot(X, self.theta) + self.bias) # predicted outputs # Update the parameters using the gradient descent update rule self.theta -= (self.learning_rate/m) * np.dot(X.T, (h-y)) self.bias -= (self.learning_rate/m) * np.sum(h-y) def fit(self, X, y): # Fit the model to the training data self.initialize_parameters(X.shape[1]) self.gradient_descent(X, y) def predict(self, X): # Predict the output for new inputs h = self.sigmoid(np.dot(X, self.theta) + self.bias) predictions = (h >= 0.5).astype(int) return predictions