code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def test_infer_online_handles_content_type_text_plain(): """Test that the engine can handle text/plain responses and parse them as JSON.""" with aioresponses() as m: m.post( _TARGET_SERVER, status=200, body=json.dumps( { "choices": ...
Test that the engine can handle text/plain responses and parse them as JSON.
test_infer_online_handles_content_type_text_plain
python
oumi-ai/oumi
tests/unit/inference/test_remote_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py
Apache-2.0
def test_infer_online_handles_invalid_content(): """Test that the engine properly handles invalid content responses.""" with aioresponses() as m: m.post( _TARGET_SERVER, status=200, body=json.dumps({"error": {"message": "Invalid JSON content"}}), content_t...
Test that the engine properly handles invalid content responses.
test_infer_online_handles_invalid_content
python
oumi-ai/oumi
tests/unit/inference/test_remote_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py
Apache-2.0
def test_infer_online_exponential_backoff(): """Test that the engine implements exponential backoff correctly.""" sleep_calls = [] async def mock_sleep(delay): sleep_calls.append(delay) def callback(url, **kwargs): # Fail until the last attempt if len(sleep_calls) < 3: ...
Test that the engine implements exponential backoff correctly.
test_infer_online_exponential_backoff
python
oumi-ai/oumi
tests/unit/inference/test_remote_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py
Apache-2.0
def test_non_retriable_errors(mock_asyncio_sleep): """Test that certain HTTP status codes are not retried.""" non_retriable_codes = [400, 401, 403, 404, 422] error_messages = { 400: "Bad request error", 401: "Unauthorized error", 403: "Forbidden error", 404: "Not found error"...
Test that certain HTTP status codes are not retried.
test_non_retriable_errors
python
oumi-ai/oumi
tests/unit/inference/test_remote_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py
Apache-2.0
def test_response_processing_error(mock_asyncio_sleep): """Test handling of errors during response processing.""" with aioresponses() as m: m.post( _TARGET_SERVER, status=200, payload={"choices": [{"invalid": "response"}]}, # Missing required fields ) ...
Test handling of errors during response processing.
test_response_processing_error
python
oumi-ai/oumi
tests/unit/inference/test_remote_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py
Apache-2.0
def test_malformed_json_response(mock_asyncio_sleep): """Test handling of malformed JSON responses.""" with aioresponses() as m: m.post( _TARGET_SERVER, status=200, body="Invalid JSON {", content_type="application/json", ) m.post( ...
Test handling of malformed JSON responses.
test_malformed_json_response
python
oumi-ai/oumi
tests/unit/inference/test_remote_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py
Apache-2.0
def test_unexpected_error_handling(mock_asyncio_sleep): """Test handling of unexpected errors during API calls.""" def raise_unexpected(*args, **kwargs): raise ValueError("Unexpected internal error") with aioresponses() as m: m.post(_TARGET_SERVER, callback=raise_unexpected) engin...
Test handling of unexpected errors during API calls.
test_unexpected_error_handling
python
oumi-ai/oumi
tests/unit/inference/test_remote_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py
Apache-2.0
def test_list_response_error_handling(): """Test handling of list-type error responses.""" with aioresponses() as m: m.post( _TARGET_SERVER, status=500, payload=[{"error": {"message": "Internal server error"}}], ) engine = RemoteInferenceEngine( ...
Test handling of list-type error responses.
test_list_response_error_handling
python
oumi-ai/oumi
tests/unit/inference/test_remote_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py
Apache-2.0
def test_retry_with_different_errors(): """Test retry behavior with different types of errors on each attempt.""" attempt = 0 def get_response(*args, **kwargs): nonlocal attempt attempt += 1 if attempt == 1: raise aiohttp.ClientError("Network error") elif attemp...
Test retry behavior with different types of errors on each attempt.
test_retry_with_different_errors
python
oumi-ai/oumi
tests/unit/inference/test_remote_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py
Apache-2.0
def test_convert_conversation_to_api_input(sambanova_engine): """Test conversion of conversation to SambaNova API input format.""" conversation = Conversation( messages=[ Message(content="System message", role=Role.SYSTEM), Message(content="User message", role=Role.USER), ...
Test conversion of conversation to SambaNova API input format.
test_convert_conversation_to_api_input
python
oumi-ai/oumi
tests/unit/inference/test_sambanova_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_sambanova_inference_engine.py
Apache-2.0
def test_convert_api_output_to_conversation(sambanova_engine): """Test conversion of SambaNova API output to conversation.""" original_conversation = Conversation( messages=[ Message(content="User message", role=Role.USER), ], metadata={"key": "value"}, conversation_i...
Test conversion of SambaNova API output to conversation.
test_convert_api_output_to_conversation
python
oumi-ai/oumi
tests/unit/inference/test_sambanova_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_sambanova_inference_engine.py
Apache-2.0
def test_convert_api_output_to_conversation_error_handling(sambanova_engine): """Test error handling in API output conversion.""" original_conversation = Conversation( messages=[Message(content="User message", role=Role.USER)] ) # Test empty choices with pytest.raises(RuntimeError, match="N...
Test error handling in API output conversion.
test_convert_api_output_to_conversation_error_handling
python
oumi-ai/oumi
tests/unit/inference/test_sambanova_inference_engine.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_sambanova_inference_engine.py
Apache-2.0
async def test_get_failure_reason_from_response_with_json_response(): """Test handling of non-retryable errors with JSON response.""" mock_response = AsyncMock(spec=aiohttp.ClientResponse) mock_response.status = 400 mock_response.json.return_value = {"error": {"message": "Invalid request"}} result ...
Test handling of non-retryable errors with JSON response.
test_get_failure_reason_from_response_with_json_response
python
oumi-ai/oumi
tests/unit/utils/test_http.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/utils/test_http.py
Apache-2.0
async def test_get_failure_reason_from_response_with_list_response(): """Test handling of non-retryable errors with list response.""" mock_response = AsyncMock(spec=aiohttp.ClientResponse) mock_response.status = 400 mock_response.json.return_value = [{"error": {"message": "Invalid request"}}] resul...
Test handling of non-retryable errors with list response.
test_get_failure_reason_from_response_with_list_response
python
oumi-ai/oumi
tests/unit/utils/test_http.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/utils/test_http.py
Apache-2.0
async def test_get_failure_reason_from_response_with_empty_response(): """Test handling of non-retryable errors with empty response.""" mock_response = AsyncMock(spec=aiohttp.ClientResponse) mock_response.status = 400 mock_response.json.return_value = {} result = await get_failure_reason_from_respo...
Test handling of non-retryable errors with empty response.
test_get_failure_reason_from_response_with_empty_response
python
oumi-ai/oumi
tests/unit/utils/test_http.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/utils/test_http.py
Apache-2.0
async def test_get_failure_reason_from_response_with_json_error(): """Test handling of non-retryable errors when JSON parsing fails.""" mock_response = AsyncMock(spec=aiohttp.ClientResponse) mock_response.status = 400 mock_response.json.side_effect = Exception("JSON decode error") result = await ge...
Test handling of non-retryable errors when JSON parsing fails.
test_get_failure_reason_from_response_with_json_error
python
oumi-ai/oumi
tests/unit/utils/test_http.py
https://github.com/oumi-ai/oumi/blob/master/tests/unit/utils/test_http.py
Apache-2.0
def face_distance(face_encodings, face_to_compare): """ Given a list of face encodings, compare them to a known face encoding and get a euclidean distance for each comparison face. The distance tells you how similar the faces are. :param faces: List of face encodings to compare :param face_to_compar...
Given a list of face encodings, compare them to a known face encoding and get a euclidean distance for each comparison face. The distance tells you how similar the faces are. :param faces: List of face encodings to compare :param face_to_compare: A face encoding to compare against :return: A numpy ...
face_distance
python
davidsandberg/facenet
contributed/clustering.py
https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py
MIT
def _chinese_whispers(encoding_list, threshold=0.55, iterations=20): """ Chinese Whispers Algorithm Modified from Alex Loveless' implementation, http://alexloveless.co.uk/data/chinese-whispers-graph-clustering-in-python/ Inputs: encoding_list: a list of facial encodings from face_recognition ...
Chinese Whispers Algorithm Modified from Alex Loveless' implementation, http://alexloveless.co.uk/data/chinese-whispers-graph-clustering-in-python/ Inputs: encoding_list: a list of facial encodings from face_recognition threshold: facial match threshold,default 0.6 iterations: sin...
_chinese_whispers
python
davidsandberg/facenet
contributed/clustering.py
https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py
MIT
def cluster_facial_encodings(facial_encodings): """ Cluster facial encodings Intended to be an optional switch for different clustering algorithms, as of right now only chinese whispers is available. Input: facial_encodings: (image_path, facial_encoding) dictionary of facial en...
Cluster facial encodings Intended to be an optional switch for different clustering algorithms, as of right now only chinese whispers is available. Input: facial_encodings: (image_path, facial_encoding) dictionary of facial encodings Output: sorted_clusters: a...
cluster_facial_encodings
python
davidsandberg/facenet
contributed/clustering.py
https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py
MIT
def compute_facial_encodings(sess,images_placeholder,embeddings,phase_train_placeholder,image_size, embedding_size,nrof_images,nrof_batches,emb_array,batch_size,paths): """ Compute Facial Encodings Given a set of images, compute the facial encodings of each face detected in the images a...
Compute Facial Encodings Given a set of images, compute the facial encodings of each face detected in the images and return them. If no faces, or more than one face found, return nothing for that image. Inputs: image_paths: a list of image paths Outputs: facia...
compute_facial_encodings
python
davidsandberg/facenet
contributed/clustering.py
https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py
MIT
def main(args): """ Main Given a list of images, save out facial encoding data files and copy images into folders of face clusters. """ from os.path import join, basename, exists from os import makedirs import numpy as np import shutil import sys if not exists(args.output): ...
Main Given a list of images, save out facial encoding data files and copy images into folders of face clusters.
main
python
davidsandberg/facenet
contributed/clustering.py
https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py
MIT
def triplet_loss(anchor, positive, negative, alpha): """Calculate the triplet loss according to the FaceNet paper Args: anchor: the embeddings for the anchor images. positive: the embeddings for the positive images. negative: the embeddings for the negative images. Returns: t...
Calculate the triplet loss according to the FaceNet paper Args: anchor: the embeddings for the anchor images. positive: the embeddings for the positive images. negative: the embeddings for the negative images. Returns: the triplet loss according to the FaceNet paper as a float te...
triplet_loss
python
davidsandberg/facenet
src/facenet.py
https://github.com/davidsandberg/facenet/blob/master/src/facenet.py
MIT
def center_loss(features, label, alfa, nrof_classes): """Center loss based on the paper "A Discriminative Feature Learning Approach for Deep Face Recognition" (http://ydwen.github.io/papers/WenECCV16.pdf) """ nrof_features = features.get_shape()[1] centers = tf.get_variable('centers', [nrof_class...
Center loss based on the paper "A Discriminative Feature Learning Approach for Deep Face Recognition" (http://ydwen.github.io/papers/WenECCV16.pdf)
center_loss
python
davidsandberg/facenet
src/facenet.py
https://github.com/davidsandberg/facenet/blob/master/src/facenet.py
MIT
def _add_loss_summaries(total_loss): """Add summaries for losses. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages ...
Add summaries for losses. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages of losses.
_add_loss_summaries
python
davidsandberg/facenet
src/facenet.py
https://github.com/davidsandberg/facenet/blob/master/src/facenet.py
MIT
def detect_face(img, minsize, pnet, rnet, onet, threshold, factor): """Detects faces in an image, and returns bounding boxes and points for them. img: input image minsize: minimum faces' size pnet, rnet, onet: caffemodel threshold: threshold=[th1, th2, th3], th1-3 are three steps's threshold fac...
Detects faces in an image, and returns bounding boxes and points for them. img: input image minsize: minimum faces' size pnet, rnet, onet: caffemodel threshold: threshold=[th1, th2, th3], th1-3 are three steps's threshold factor: the factor used to create a scaling pyramid of face sizes to detect in...
detect_face
python
davidsandberg/facenet
src/align/detect_face.py
https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py
MIT
def bulk_detect_face(images, detection_window_size_ratio, pnet, rnet, onet, threshold, factor): """Detects faces in a list of images images: list containing input images detection_window_size_ratio: ratio of minimum face size to smallest image dimension pnet, rnet, onet: caffemodel threshold: thresh...
Detects faces in a list of images images: list containing input images detection_window_size_ratio: ratio of minimum face size to smallest image dimension pnet, rnet, onet: caffemodel threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold [0-1] factor: the factor used to create a scal...
bulk_detect_face
python
davidsandberg/facenet
src/align/detect_face.py
https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py
MIT
def generateBoundingBox(imap, reg, scale, t): """Use heatmap to generate bounding boxes""" stride=2 cellsize=12 imap = np.transpose(imap) dx1 = np.transpose(reg[:,:,0]) dy1 = np.transpose(reg[:,:,1]) dx2 = np.transpose(reg[:,:,2]) dy2 = np.transpose(reg[:,:,3]) y, x = np.where(imap ...
Use heatmap to generate bounding boxes
generateBoundingBox
python
davidsandberg/facenet
src/align/detect_face.py
https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py
MIT
def pad(total_boxes, w, h): """Compute the padding coordinates (pad the bounding boxes to square)""" tmpw = (total_boxes[:,2]-total_boxes[:,0]+1).astype(np.int32) tmph = (total_boxes[:,3]-total_boxes[:,1]+1).astype(np.int32) numbox = total_boxes.shape[0] dx = np.ones((numbox), dtype=np.int32) d...
Compute the padding coordinates (pad the bounding boxes to square)
pad
python
davidsandberg/facenet
src/align/detect_face.py
https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py
MIT
def inception_resnet_v1(inputs, is_training=True, dropout_keep_prob=0.8, bottleneck_layer_size=128, reuse=None, scope='InceptionResnetV1'): """Creates the Inception Resnet V1 model. Args: inputs: a 4-D tensor ...
Creates the Inception Resnet V1 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. num_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the netw...
inception_resnet_v1
python
davidsandberg/facenet
src/models/inception_resnet_v1.py
https://github.com/davidsandberg/facenet/blob/master/src/models/inception_resnet_v1.py
MIT
def inception_resnet_v2(inputs, is_training=True, dropout_keep_prob=0.8, bottleneck_layer_size=128, reuse=None, scope='InceptionResnetV2'): """Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor o...
Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. num_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the netw...
inception_resnet_v2
python
davidsandberg/facenet
src/models/inception_resnet_v2.py
https://github.com/davidsandberg/facenet/blob/master/src/models/inception_resnet_v2.py
MIT
def __init__(self, facePredictor): """ Instantiate an 'AlignDlib' object. :param facePredictor: The path to dlib's :type facePredictor: str """ assert facePredictor is not None #pylint: disable=no-member self.detector = dlib.get_frontal_face_detector() ...
Instantiate an 'AlignDlib' object. :param facePredictor: The path to dlib's :type facePredictor: str
__init__
python
davidsandberg/facenet
tmp/align_dlib.py
https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py
MIT
def getAllFaceBoundingBoxes(self, rgbImg): """ Find all face bounding boxes in an image. :param rgbImg: RGB image to process. Shape: (height, width, 3) :type rgbImg: numpy.ndarray :return: All face bounding boxes in an image. :rtype: dlib.rectangles """ a...
Find all face bounding boxes in an image. :param rgbImg: RGB image to process. Shape: (height, width, 3) :type rgbImg: numpy.ndarray :return: All face bounding boxes in an image. :rtype: dlib.rectangles
getAllFaceBoundingBoxes
python
davidsandberg/facenet
tmp/align_dlib.py
https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py
MIT
def getLargestFaceBoundingBox(self, rgbImg, skipMulti=False): """ Find the largest face bounding box in an image. :param rgbImg: RGB image to process. Shape: (height, width, 3) :type rgbImg: numpy.ndarray :param skipMulti: Skip image if more than one face detected. :type...
Find the largest face bounding box in an image. :param rgbImg: RGB image to process. Shape: (height, width, 3) :type rgbImg: numpy.ndarray :param skipMulti: Skip image if more than one face detected. :type skipMulti: bool :return: The largest face bounding box in an ima...
getLargestFaceBoundingBox
python
davidsandberg/facenet
tmp/align_dlib.py
https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py
MIT
def findLandmarks(self, rgbImg, bb): """ Find the landmarks of a face. :param rgbImg: RGB image to process. Shape: (height, width, 3) :type rgbImg: numpy.ndarray :param bb: Bounding box around the face to find landmarks for. :type bb: dlib.rectangle :return: Dete...
Find the landmarks of a face. :param rgbImg: RGB image to process. Shape: (height, width, 3) :type rgbImg: numpy.ndarray :param bb: Bounding box around the face to find landmarks for. :type bb: dlib.rectangle :return: Detected landmark locations. :rtype: list of...
findLandmarks
python
davidsandberg/facenet
tmp/align_dlib.py
https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py
MIT
def align(self, imgDim, rgbImg, bb=None, landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP, skipMulti=False, scale=1.0): r"""align(imgDim, rgbImg, bb=None, landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP) Transform and align a face in an image. :pa...
align(imgDim, rgbImg, bb=None, landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP) Transform and align a face in an image. :param imgDim: The edge length in pixels of the square the image is resized to. :type imgDim: int :param rgbImg: RGB image to process. Shape: (height, width...
align
python
davidsandberg/facenet
tmp/align_dlib.py
https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py
MIT
def tffunc(*argtypes): '''Helper that transforms TF-graph generating function into a regular one. See "resize" function below. ''' placeholders = list(map(tf.placeholder, argtypes)) def wrap(f): out = f(*placeholders) def wrapper(*args, **kw): ...
Helper that transforms TF-graph generating function into a regular one. See "resize" function below.
tffunc
python
davidsandberg/facenet
tmp/deepdream.py
https://github.com/davidsandberg/facenet/blob/master/tmp/deepdream.py
MIT
def calc_grad_tiled(img, t_grad, tile_size=512): '''Compute the value of tensor t_grad over the image in a tiled way. Random shifts are applied to the image to blur tile boundaries over multiple iterations.''' sz = tile_size h, w = img.shape[:2] sx, sy = np.random.randin...
Compute the value of tensor t_grad over the image in a tiled way. Random shifts are applied to the image to blur tile boundaries over multiple iterations.
calc_grad_tiled
python
davidsandberg/facenet
tmp/deepdream.py
https://github.com/davidsandberg/facenet/blob/master/tmp/deepdream.py
MIT
def lap_split(img): '''Split the image into lo and hi frequency components''' with tf.name_scope('split'): lo = tf.nn.conv2d(img, k5x5, [1,2,2,1], 'SAME') lo2 = tf.nn.conv2d_transpose(lo, k5x5*4, tf.shape(img), [1,2,2,1]) hi = img-lo2 return lo, hi
Split the image into lo and hi frequency components
lap_split
python
davidsandberg/facenet
tmp/deepdream.py
https://github.com/davidsandberg/facenet/blob/master/tmp/deepdream.py
MIT
def normalize_std(img, eps=1e-10): '''Normalize image by making its standard deviation = 1.0''' with tf.name_scope('normalize'): std = tf.sqrt(tf.reduce_mean(tf.square(img))) return img/tf.maximum(std, eps)
Normalize image by making its standard deviation = 1.0
normalize_std
python
davidsandberg/facenet
tmp/deepdream.py
https://github.com/davidsandberg/facenet/blob/master/tmp/deepdream.py
MIT
def data_type(): """Return the type of the activations, weights, and placeholder variables.""" if FLAGS.use_fp16: return tf.float16 else: return tf.float32
Return the type of the activations, weights, and placeholder variables.
data_type
python
davidsandberg/facenet
tmp/mnist_center_loss.py
https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py
MIT
def maybe_download(filename): """Download the data from Yann's website, unless it's already here.""" if not tf.gfile.Exists(WORK_DIRECTORY): tf.gfile.MakeDirs(WORK_DIRECTORY) filepath = os.path.join(WORK_DIRECTORY, filename) if not tf.gfile.Exists(filepath): filepath, _ = urllib.request....
Download the data from Yann's website, unless it's already here.
maybe_download
python
davidsandberg/facenet
tmp/mnist_center_loss.py
https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py
MIT
def extract_data(filename, num_images): """Extract the images into a 4D tensor [image index, y, x, channels]. Values are rescaled from [0, 255] down to [-0.5, 0.5]. """ print('Extracting', filename) with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read(IMA...
Extract the images into a 4D tensor [image index, y, x, channels]. Values are rescaled from [0, 255] down to [-0.5, 0.5].
extract_data
python
davidsandberg/facenet
tmp/mnist_center_loss.py
https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py
MIT
def extract_labels(filename, num_images): """Extract the labels into a vector of int64 label IDs.""" print('Extracting', filename) with gzip.open(filename) as bytestream: bytestream.read(8) buf = bytestream.read(1 * num_images) labels = np.frombuffer(buf, dtype=np.uint8).astype(np.in...
Extract the labels into a vector of int64 label IDs.
extract_labels
python
davidsandberg/facenet
tmp/mnist_center_loss.py
https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py
MIT
def fake_data(num_images): """Generate a fake dataset that matches the dimensions of MNIST.""" data = np.ndarray( shape=(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS), dtype=np.float32) labels = np.zeros(shape=(num_images,), dtype=np.int64) for image in range(num_images): lab...
Generate a fake dataset that matches the dimensions of MNIST.
fake_data
python
davidsandberg/facenet
tmp/mnist_center_loss.py
https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py
MIT
def error_rate(predictions, labels): """Return the error rate based on dense predictions and sparse labels.""" return 100.0 - ( 100.0 * np.sum(np.argmax(predictions, 1) == labels) / predictions.shape[0])
Return the error rate based on dense predictions and sparse labels.
error_rate
python
davidsandberg/facenet
tmp/mnist_center_loss.py
https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py
MIT
def batch_norm(x, phase_train): #pylint: disable=unused-variable """ Batch normalization on convolutional maps. Args: x: Tensor, 4D BHWD input maps n_out: integer, depth of input maps phase_train: boolean tf.Variable, true indicates training p...
Batch normalization on convolutional maps. Args: x: Tensor, 4D BHWD input maps n_out: integer, depth of input maps phase_train: boolean tf.Variable, true indicates training phase scope: string, variable scope affn: w...
batch_norm
python
davidsandberg/facenet
tmp/mnist_center_loss.py
https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py
MIT
def eval_in_batches(data, sess): """Get all predictions for a dataset by running it in small batches.""" size = data.shape[0] if size < EVAL_BATCH_SIZE: raise ValueError("batch size for evals larger than dataset: %d" % size) predictions = np.ndarray(shape=(size, NUM_LABELS), ...
Get all predictions for a dataset by running it in small batches.
eval_in_batches
python
davidsandberg/facenet
tmp/mnist_center_loss.py
https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py
MIT
def l2_loss(tensor, weight=1.0, scope=None): """Define a L2Loss, useful for regularize, i.e. weight decay. Args: tensor: tensor to regularize. weight: an optional weight to modulate the loss. scope: Optional scope for op_scope. Returns: the L2 loss op. """ with tf.name_scope(...
Define a L2Loss, useful for regularize, i.e. weight decay. Args: tensor: tensor to regularize. weight: an optional weight to modulate the loss. scope: Optional scope for op_scope. Returns: the L2 loss op.
l2_loss
python
davidsandberg/facenet
tmp/network.py
https://github.com/davidsandberg/facenet/blob/master/tmp/network.py
MIT
def batch_norm(x, phase_train): """ Batch normalization on convolutional maps. Args: x: Tensor, 4D BHWD input maps n_out: integer, depth of input maps phase_train: boolean tf.Variable, true indicates training phase scope: string, variable scope a...
Batch normalization on convolutional maps. Args: x: Tensor, 4D BHWD input maps n_out: integer, depth of input maps phase_train: boolean tf.Variable, true indicates training phase scope: string, variable scope affn: whether to affn-transform out...
batch_norm
python
davidsandberg/facenet
tmp/network.py
https://github.com/davidsandberg/facenet/blob/master/tmp/network.py
MIT
def inference(images, keep_probability, phase_train=True, weight_decay=0.0): """ Define an inference network for face recognition based on inception modules using batch normalization Args: images: The images to run inference on, dimensions batch_size x height x width x channels phas...
Define an inference network for face recognition based on inception modules using batch normalization Args: images: The images to run inference on, dimensions batch_size x height x width x channels phase_train: True if batch normalization should operate in training mode
inference
python
davidsandberg/facenet
tmp/nn2.py
https://github.com/davidsandberg/facenet/blob/master/tmp/nn2.py
MIT
def gradients(ys, xs, grad_ys=None, checkpoints='collection', **kwargs): ''' Authors: Tim Salimans & Yaroslav Bulatov memory efficient gradient implementation inspired by "Training Deep Nets with Sublinear Memory Cost" by Chen et al. 2016 (https://arxiv.org/abs/1604.06174) ys,xs,grad_ys,kwargs are...
Authors: Tim Salimans & Yaroslav Bulatov memory efficient gradient implementation inspired by "Training Deep Nets with Sublinear Memory Cost" by Chen et al. 2016 (https://arxiv.org/abs/1604.06174) ys,xs,grad_ys,kwargs are the arguments to standard tensorflow tf.gradients (https://www.tensorflow.o...
gradients
python
openai/glow
memory_saving_gradients.py
https://github.com/openai/glow/blob/master/memory_saving_gradients.py
MIT
def capture_ops(): """Decorator to capture ops created in the block. with capture_ops() as ops: # create some ops print(ops) # => prints ops created. """ micros = int(time.time()*10**6) scope_name = str(micros) op_list = [] with tf.name_scope(scope_name): yield op_list ...
Decorator to capture ops created in the block. with capture_ops() as ops: # create some ops print(ops) # => prints ops created.
capture_ops
python
openai/glow
memory_saving_gradients.py
https://github.com/openai/glow/blob/master/memory_saving_gradients.py
MIT
def debug_print(s, *args): """Like logger.log, but also replaces all TensorFlow ops/tensors with their names. Sensitive to value of DEBUG_LOGGING, see enable_debug/disable_debug Usage: debug_print("see tensors %s for %s", tensorlist, [1,2,3]) """ if DEBUG_LOGGING: formatted_args = [f...
Like logger.log, but also replaces all TensorFlow ops/tensors with their names. Sensitive to value of DEBUG_LOGGING, see enable_debug/disable_debug Usage: debug_print("see tensors %s for %s", tensorlist, [1,2,3])
debug_print
python
openai/glow
memory_saving_gradients.py
https://github.com/openai/glow/blob/master/memory_saving_gradients.py
MIT
def format_ops(ops, sort_outputs=True): """Helper method for printing ops. Converts Tensor/Operation op to op.name, rest to str(op).""" if hasattr(ops, '__iter__') and not isinstance(ops, str): l = [(op.name if hasattr(op, "name") else str(op)) for op in ops] if sort_outputs: re...
Helper method for printing ops. Converts Tensor/Operation op to op.name, rest to str(op).
format_ops
python
openai/glow
memory_saving_gradients.py
https://github.com/openai/glow/blob/master/memory_saving_gradients.py
MIT
def _symmetric_matrix_square_root(mat, eps=1e-10): """Compute square root of a symmetric matrix. Note that this is different from an elementwise square root. We want to compute M' where M' = sqrt(mat) such that M' * M' = mat. Also note that this method **only** works for symmetric matrices. Args: ...
Compute square root of a symmetric matrix. Note that this is different from an elementwise square root. We want to compute M' where M' = sqrt(mat) such that M' * M' = mat. Also note that this method **only** works for symmetric matrices. Args: mat: Matrix to take the square root of. eps: Sma...
_symmetric_matrix_square_root
python
openai/glow
tfops.py
https://github.com/openai/glow/blob/master/tfops.py
MIT
def forward(self, x: Tensor, edge_index: Adj, edge_attr: OptTensor = None, batch: Adj = None, angle_data: List = None, size: Size = None) -> Tensor: """ Inputs: * x: (n_points, d) where d is pos_dims + feat_dims * edge_index: (2, n_edges) * ...
Inputs: * x: (n_points, d) where d is pos_dims + feat_dims * edge_index: (2, n_edges) * edge_attr: tensor (n_edges, n_feats) excluding basic distance feats. * batch: (n_points,) long tensor. specifies xloud belonging for each point * angle_data: list of tens...
forward
python
lucidrains/egnn-pytorch
egnn_pytorch/egnn_pytorch_geometric.py
https://github.com/lucidrains/egnn-pytorch/blob/master/egnn_pytorch/egnn_pytorch_geometric.py
MIT
def make_jobfile_from_command_list(jobfile_path, commands): """ Save a jobfile containing commands to run. Parameters ---------- jobfile_path : str or path commands : list of str """ # Creating a jobfile containing all commands to run jobfile_content = ''.join('%s\n' % com for com in...
Save a jobfile containing commands to run. Parameters ---------- jobfile_path : str or path commands : list of str
make_jobfile_from_command_list
python
WassimTenachi/PhySO
benchmarking/utils.py
https://github.com/WassimTenachi/PhySO/blob/master/benchmarking/utils.py
MIT
def assess_equivalence (pareto_df, Feynman_pb, check_only_most_acc = False, verbose = False): """ Checks if at least one expression in the Pareto front is symbolically equivalent to target expression, following a similar methodology as SRBench (see https://github.com/cavalab/srbench). I.e, an expression...
Checks if at least one expression in the Pareto front is symbolically equivalent to target expression, following a similar methodology as SRBench (see https://github.com/cavalab/srbench). I.e, an expression is deemed equivalent if: - the symbolic difference simplifies to 0 - OR the symbolic...
assess_equivalence
python
WassimTenachi/PhySO
benchmarking/FeynmanBenchmark/feynman_results_analysis.py
https://github.com/WassimTenachi/PhySO/blob/master/benchmarking/FeynmanBenchmark/feynman_results_analysis.py
MIT
def assess_metric_test (pareto_df, Feynman_pb, metric_func, i_pareto=-1): """ Computes metric value of the best Pareto front expression on noiseless test data. Parameters ---------- pareto_df : pd.DataFrame Pareto front dataframe generated by PhySO. Feynman_pb : physo.benchmark.FeynmanDa...
Computes metric value of the best Pareto front expression on noiseless test data. Parameters ---------- pareto_df : pd.DataFrame Pareto front dataframe generated by PhySO. Feynman_pb : physo.benchmark.FeynmanDataset.FeynmanProblem.FeynmanProblem Related Feynman problem. metric_f...
assess_metric_test
python
WassimTenachi/PhySO
benchmarking/FeynmanBenchmark/feynman_results_analysis.py
https://github.com/WassimTenachi/PhySO/blob/master/benchmarking/FeynmanBenchmark/feynman_results_analysis.py
MIT
def get_symbolic_result (pareto_df, Feynman_pb, i_pareto = -1): """ Produces an SRBench style dictionary characterizing the best expression found. Parameters ---------- pareto_df : pd.DataFrame Pareto front dataframe generated by PhySO. Feynman_pb : physo.benchmark.FeynmanDataset.Feynman...
Produces an SRBench style dictionary characterizing the best expression found. Parameters ---------- pareto_df : pd.DataFrame Pareto front dataframe generated by PhySO. Feynman_pb : physo.benchmark.FeynmanDataset.FeynmanProblem.FeynmanProblem Related Feynman problem. i_pareto : ...
get_symbolic_result
python
WassimTenachi/PhySO
benchmarking/FeynmanBenchmark/feynman_results_analysis.py
https://github.com/WassimTenachi/PhySO/blob/master/benchmarking/FeynmanBenchmark/feynman_results_analysis.py
MIT
def load_run_data (pb_folder_prefix): """ Safely loads pareto front .csv and curves data .csv into dataframes if possible return None otherwise. Also returns noise level encoded into folder name. Parameters ---------- pb_folder_prefix : str or path Starting name of folder containing run ...
Safely loads pareto front .csv and curves data .csv into dataframes if possible return None otherwise. Also returns noise level encoded into folder name. Parameters ---------- pb_folder_prefix : str or path Starting name of folder containing run data (there should only be one folder startin...
load_run_data
python
WassimTenachi/PhySO
benchmarking/FeynmanBenchmark/feynman_results_analysis.py
https://github.com/WassimTenachi/PhySO/blob/master/benchmarking/FeynmanBenchmark/feynman_results_analysis.py
MIT
def load_class_equations_csv (filepath_eqs ="ClassEquations.csv"): """ Loads ClassEquations.csv into a pd.DataFrame. Parameters ---------- filepath_eqs : str Path to ClassEquations.csv. Returns ------- eqs_class_df : pd.DataFrame """ eqs_class_df = pd.read_csv(filepath_e...
Loads ClassEquations.csv into a pd.DataFrame. Parameters ---------- filepath_eqs : str Path to ClassEquations.csv. Returns ------- eqs_class_df : pd.DataFrame
load_class_equations_csv
python
WassimTenachi/PhySO
physo/benchmark/ClassDataset/ClassProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/ClassDataset/ClassProblem.py
MIT
def get_units (i_eq, i_var = 0, output_var = False): """ Gets units of variable. Parameters ---------- i_eq : int Equation number in the set of equations. i_var : int Variable id in its equation line. output_var : bool If True, returns units of output variable, otherw...
Gets units of variable. Parameters ---------- i_eq : int Equation number in the set of equations. i_var : int Variable id in its equation line. output_var : bool If True, returns units of output variable, otherwise returns units of input variable specified by i_var. ...
get_units
python
WassimTenachi/PhySO
physo/benchmark/ClassDataset/ClassProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/ClassDataset/ClassProblem.py
MIT
def __init__(self, i_eq = None, eq_name = None, original_var_names = False): """ Loads a Class problem based on its number in the set or its equation name. Parameters ---------- i_eq : int Equation number in the set of equations. eq_name : str Equa...
Loads a Class problem based on its number in the set or its equation name. Parameters ---------- i_eq : int Equation number in the set of equations. eq_name : str Equation name in the set of equations (e.g. 'Harmonic Oscillator'). original_var_nam...
__init__
python
WassimTenachi/PhySO
physo/benchmark/ClassDataset/ClassProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/ClassDataset/ClassProblem.py
MIT
def target_function(self, X, K): """ Evaluates X with target function, using K values. Parameters ---------- X : numpy.array of shape (n_vars, ?,) of floats Input variables. K : numpy.array of shape (n_spe,) of floats Spe free consts. Retur...
Evaluates X with target function, using K values. Parameters ---------- X : numpy.array of shape (n_vars, ?,) of floats Input variables. K : numpy.array of shape (n_spe,) of floats Spe free consts. Returns ------- y : numpy.array o...
target_function
python
WassimTenachi/PhySO
physo/benchmark/ClassDataset/ClassProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/ClassDataset/ClassProblem.py
MIT
def generate_data_points (self, n_samples = 1_000, n_realizations = 10, return_K = False): """ Generates data points accordingly for this Class problem. Parameters ---------- n_samples : int Number of samples to draw. By default, 1e3. n_realizations : int ...
Generates data points accordingly for this Class problem. Parameters ---------- n_samples : int Number of samples to draw. By default, 1e3. n_realizations : int Number of realizations to draw. By default, 10. return_K : bool If True, r...
generate_data_points
python
WassimTenachi/PhySO
physo/benchmark/ClassDataset/ClassProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/ClassDataset/ClassProblem.py
MIT
def get_sympy(self, K_vals=None): """ Gets sympy expression of the formula evaluated with spe free consts. Parameters ---------- K_vals : numpy.array of shape (?, n_spe,) of floats or None Values to evaluate spe free consts with, if None, uses random values and return...
Gets sympy expression of the formula evaluated with spe free consts. Parameters ---------- K_vals : numpy.array of shape (?, n_spe,) of floats or None Values to evaluate spe free consts with, if None, uses random values and returns only one realization. Returns ...
get_sympy
python
WassimTenachi/PhySO
physo/benchmark/ClassDataset/ClassProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/ClassDataset/ClassProblem.py
MIT
def get_units (var_name): """ Gets units of variable var_name. Example: get_units("kb") Parameters ---------- var_name : str original variable name. Returns ------- units : numpy.array of shape (FEYN_UNITS_VECTOR_SIZE,) of floats Units of variable. """ assert not ...
Gets units of variable var_name. Example: get_units("kb") Parameters ---------- var_name : str original variable name. Returns ------- units : numpy.array of shape (FEYN_UNITS_VECTOR_SIZE,) of floats Units of variable.
get_units
python
WassimTenachi/PhySO
physo/benchmark/FeynmanDataset/FeynmanProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/FeynmanDataset/FeynmanProblem.py
MIT
def __init__(self, i_eq = None, eq_name = None, original_var_names = False): """ Loads a Feynman problem based on its number in the set or its equation name Parameters ---------- i_eq : int Equation number in the whole set of equations (0 to 99 for bulk eqs and 100 to...
Loads a Feynman problem based on its number in the set or its equation name Parameters ---------- i_eq : int Equation number in the whole set of equations (0 to 99 for bulk eqs and 100 to 119 for bonus eqs). eq_name : str Equation name in the set of equat...
__init__
python
WassimTenachi/PhySO
physo/benchmark/FeynmanDataset/FeynmanProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/FeynmanDataset/FeynmanProblem.py
MIT
def target_function(self, X): """ Evaluates X with target function. Parameters ---------- X : numpy.array of shape (n_vars, ?,) of floats Returns ------- y : numpy.array of shape (?,) of floats """ # Getting sympy function f = sympy...
Evaluates X with target function. Parameters ---------- X : numpy.array of shape (n_vars, ?,) of floats Returns ------- y : numpy.array of shape (?,) of floats
target_function
python
WassimTenachi/PhySO
physo/benchmark/FeynmanDataset/FeynmanProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/FeynmanDataset/FeynmanProblem.py
MIT
def compare_expression (self, trial_expr, handle_trigo = True, prevent_zero_frac = True, prevent_inf_equivalence = True, round_decimal = 2, verbose=False...
Checks if trial_expr is symbolically equivalent to the target expression of this Feynman problem, following a similar methodology as SRBench (see https://github.com/cavalab/srbench). I.e, it is deemed equivalent if: - the symbolic difference simplifies to 0 - OR the symb...
compare_expression
python
WassimTenachi/PhySO
physo/benchmark/FeynmanDataset/FeynmanProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/FeynmanDataset/FeynmanProblem.py
MIT
def trial_function (self, trial_expr, X): """ Evaluates X on a trial expression mapping X to input variables names in sympy. Parameters ---------- trial_expr : Sympy Expression Trial sympy expression with evaluated numeric free constants and assumptions regarding vari...
Evaluates X on a trial expression mapping X to input variables names in sympy. Parameters ---------- trial_expr : Sympy Expression Trial sympy expression with evaluated numeric free constants and assumptions regarding variables (positivity etc.) encoded in expres...
trial_function
python
WassimTenachi/PhySO
physo/benchmark/FeynmanDataset/FeynmanProblem.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/FeynmanDataset/FeynmanProblem.py
MIT
def read_pareto_csv (pareto_csv_path, sympy_X_symbols_dict = None, return_df = False): """ Loads a Pareto front csv generated by PhySO into sympy expressions with evaluated free constants. Only works for expressions not using dataset spe free constants (ie. Class SR tasks), in those cases, pkl loading i...
Loads a Pareto front csv generated by PhySO into sympy expressions with evaluated free constants. Only works for expressions not using dataset spe free constants (ie. Class SR tasks), in those cases, pkl loading is recommended instead (physo.read_pareto_pkl). Parameters ---------- pareto_csv_pa...
read_pareto_csv
python
WassimTenachi/PhySO
physo/benchmark/utils/read_logs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/read_logs.py
MIT
def get_pareto_expressions_from_df (pareto_df, sympy_X_symbols_dict = None): """ Loads a Pareto front dataframe generated by PhySO into sympy expressions with evaluated free constants. Only works for expressions not using dataset spe free constants (ie. Class SR tasks). Parameters ---------- par...
Loads a Pareto front dataframe generated by PhySO into sympy expressions with evaluated free constants. Only works for expressions not using dataset spe free constants (ie. Class SR tasks). Parameters ---------- pareto_df : pd.DataFrame Pareto front dataframe generated by PhySO. sympy_X...
get_pareto_expressions_from_df
python
WassimTenachi/PhySO
physo/benchmark/utils/read_logs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/read_logs.py
MIT
def replace_sin_by_cos (expr): """ Replaces sin(...) by cos(pi/2 - ...) in a sympy expression. Parameters ---------- expr : Sympy Expression Returns ------- ex1 : Sympy Expression """ ex1 = expr # If sin(...) is encountered, replacing it by cos(pi/2 - ...) for a in sympy....
Replaces sin(...) by cos(pi/2 - ...) in a sympy expression. Parameters ---------- expr : Sympy Expression Returns ------- ex1 : Sympy Expression
replace_sin_by_cos
python
WassimTenachi/PhySO
physo/benchmark/utils/symbolic_utils.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/symbolic_utils.py
MIT
def replace_cos_by_sin (expr): """ Replaces cos(...) by sin(pi/2 - ...) in a sympy expression. Parameters ---------- expr : Sympy Expression Returns ------- ex1 : Sympy Expression """ ex1 = expr # If cos(...) is encountered, replacing it by sin(pi/2 - ...) for a in sympy....
Replaces cos(...) by sin(pi/2 - ...) in a sympy expression. Parameters ---------- expr : Sympy Expression Returns ------- ex1 : Sympy Expression
replace_cos_by_sin
python
WassimTenachi/PhySO
physo/benchmark/utils/symbolic_utils.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/symbolic_utils.py
MIT
def round_floats(expr, round_decimal = 2): """ Rounds the floats in a sympy expression as in SRBench (see https://github.com/cavalab/srbench). Parameters ---------- expr : Sympy Expression round_decimal : int Rounding up to this decimal. Use round_decimal = 2 for SRBench-like beh...
Rounds the floats in a sympy expression as in SRBench (see https://github.com/cavalab/srbench). Parameters ---------- expr : Sympy Expression round_decimal : int Rounding up to this decimal. Use round_decimal = 2 for SRBench-like behavior (as they actually round up to 2 decimals). ...
round_floats
python
WassimTenachi/PhySO
physo/benchmark/utils/symbolic_utils.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/symbolic_utils.py
MIT
def clean_sympy_expr(expr, round_decimal = 2): """ Cleans (rounds floats, simplifies) sympy expression for symbolic comparison purposes as in SRBench (see https://github.com/cavalab/srbench). Parameters ---------- expr : Sympy Expression round_decimal : int Rounding up to this decima...
Cleans (rounds floats, simplifies) sympy expression for symbolic comparison purposes as in SRBench (see https://github.com/cavalab/srbench). Parameters ---------- expr : Sympy Expression round_decimal : int Rounding up to this decimal. Use round_decimal = 2 for SRBench-like beha...
clean_sympy_expr
python
WassimTenachi/PhySO
physo/benchmark/utils/symbolic_utils.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/symbolic_utils.py
MIT
def compare_expression (trial_expr, target_expr, handle_trigo = True, prevent_zero_frac = True, prevent_inf_equivalence = True, round_decimal = 2, verbose=Fals...
Checks if trial_expr is symbolically equivalent to target_expr, following a similar methodology as SRBench (see https://github.com/cavalab/srbench). I.e, it is deemed equivalent if: - the symbolic difference simplifies to 0 - OR the symbolic difference is a constant - OR the symboli...
compare_expression
python
WassimTenachi/PhySO
physo/benchmark/utils/symbolic_utils.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/symbolic_utils.py
MIT
def expression_size(expr): """ Evaluates complexity as in SRBench (see https://github.com/cavalab/srbench). Parameters ---------- expr : Sympy Expression Returns ------- c : int """ c=0 for arg in sympy.preorder_traversal(expr): c += 1 return c
Evaluates complexity as in SRBench (see https://github.com/cavalab/srbench). Parameters ---------- expr : Sympy Expression Returns ------- c : int
expression_size
python
WassimTenachi/PhySO
physo/benchmark/utils/symbolic_utils.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/symbolic_utils.py
MIT
def sympy_to_prefix(sympy_expr): """ Converts a sympy expression to prefix notation. Parameters ---------- sympy_expr : sympy.core Sympy expression Returns ------- dict : tokens_str : numpy.array of str List of tokens in the expression. arities : numpy...
Converts a sympy expression to prefix notation. Parameters ---------- sympy_expr : sympy.core Sympy expression Returns ------- dict : tokens_str : numpy.array of str List of tokens in the expression. arities : numpy.array of int List of aritie...
sympy_to_prefix
python
WassimTenachi/PhySO
physo/benchmark/utils/symbolic_utils.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/symbolic_utils.py
MIT
def sympy_symbol_with_assumptions_from_range(name, low, high): """ Returns a sympy symbol with assumptions from its data range. Parameters ---------- name : str Name of the variable. low : float Lowest value taken by the variable. high : float Highest value taken by t...
Returns a sympy symbol with assumptions from its data range. Parameters ---------- name : str Name of the variable. low : float Lowest value taken by the variable. high : float Highest value taken by the variable. Returns ------- sympy.Symbol
sympy_symbol_with_assumptions_from_range
python
WassimTenachi/PhySO
physo/benchmark/utils/symbolic_utils.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/symbolic_utils.py
MIT
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): """ # Works on UNIX only # https://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish Demo: @timeout(20) def myfunc(n): time.sleep(n) return True myfunc(n>20) will be killed ...
# Works on UNIX only # https://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish Demo: @timeout(20) def myfunc(n): time.sleep(n) return True myfunc(n>20) will be killed
timeout
python
WassimTenachi/PhySO
physo/benchmark/utils/timeout_unix.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/benchmark/utils/timeout_unix.py
MIT
def loss_func(logits_train, ideal_probs_train, R_train, baseline, lengths, gamma_decay, entropy_weight, ): """ Loss function for reinforcing symbolic programs. Parameters ---------- logits_train : torch.tensor of shape (max_time_step, n_train, n_choices,) Probabilities generated by the...
Loss function for reinforcing symbolic programs. Parameters ---------- logits_train : torch.tensor of shape (max_time_step, n_train, n_choices,) Probabilities generated by the rnn (for each step along program length, for each program in training sub-batch, for each choosable token...
loss_func
python
WassimTenachi/PhySO
physo/learn/loss.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/learn/loss.py
MIT
def save_pareto_pkl (pareto_progs, fpath): """ Save pareto programs to pickle file. Parameters ---------- pareto_progs : list of Program.Program List of pareto programs. fpath : str Path to pkl file. """ with open(fpath, 'wb') as f: pickle.dump(pareto_progs, f) ...
Save pareto programs to pickle file. Parameters ---------- pareto_progs : list of Program.Program List of pareto programs. fpath : str Path to pkl file.
save_pareto_pkl
python
WassimTenachi/PhySO
physo/learn/monitoring.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/learn/monitoring.py
MIT
def read_pareto_pkl (fpath): """ Load pareto programs from pickle file. Parameters ---------- fpath : str Path to pkl file. Returns ------- pareto_progs : list of Program.Program List of pareto programs. """ with open(fpath, 'rb') as f: pareto_progs = pick...
Load pareto programs from pickle file. Parameters ---------- fpath : str Path to pkl file. Returns ------- pareto_progs : list of Program.Program List of pareto programs.
read_pareto_pkl
python
WassimTenachi/PhySO
physo/learn/monitoring.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/learn/monitoring.py
MIT
def __init__(self, library_args, priors_config, multi_X, multi_y, rewards_computer, batch_size, max_time_step, multi_y_weights = 1., free_const_opti_args = None, ...
Parameters ---------- library_args: dict Arguments passed to library.__init__ priors_config : list of couples (str : dict) List of priors. List containing couples with prior name as first item in couple (see prior.PRIORS_DICT for list of available pri...
__init__
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def get_sibling_one_hot (self, step = None): """ Get siblings one hot of tokens at step. 0 one hot vectors for dummies. Parameters ---------- step : int Step of token from which sibling one hot should be returned. By default, step = current step Re...
Get siblings one hot of tokens at step. 0 one hot vectors for dummies. Parameters ---------- step : int Step of token from which sibling one hot should be returned. By default, step = current step Returns ------- one_hot : numpy.array of s...
get_sibling_one_hot
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def get_parent_one_hot (self, step = None): """ Get parents one hot of tokens at step. Parameters ---------- step : int Step of token from which parent one hot should be returned. By default, step = current step Returns ------- one_...
Get parents one hot of tokens at step. Parameters ---------- step : int Step of token from which parent one hot should be returned. By default, step = current step Returns ------- one_hot : numpy.array of shape (batch_size, n_choices) of i...
get_parent_one_hot
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def get_previous_tokens_one_hot(self): """ Get previous step tokens as one hot. Returns ------- one_hot : numpy.array of shape (batch_size, n_choices) of int One hot. """ # Return 0 if 0th step if self.programs.curr_step == 0: one_h...
Get previous step tokens as one hot. Returns ------- one_hot : numpy.array of shape (batch_size, n_choices) of int One hot.
get_previous_tokens_one_hot
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def get_sibling_units_obs (self, step = None): """ Get (required) units of sibling of tokens at step. Filling using INTERFACE_UNITS_UNAVAILABLE_FILLER where units are not available. Adding a vector in addition to the units indicating if units are available or not (equal to INTERFACE_UNIT...
Get (required) units of sibling of tokens at step. Filling using INTERFACE_UNITS_UNAVAILABLE_FILLER where units are not available. Adding a vector in addition to the units indicating if units are available or not (equal to INTERFACE_UNITS_AVAILABLE where units are available and equal to INTERFA...
get_sibling_units_obs
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def get_parent_units_obs (self, step = None): """ Get (required) units of parent of tokens at step. Filling using INTERFACE_UNITS_UNAVAILABLE_FILLER where units are not available. Adding a vector in addition to the units indicating if units are available or not (equal to INTERFACE_UNITS_...
Get (required) units of parent of tokens at step. Filling using INTERFACE_UNITS_UNAVAILABLE_FILLER where units are not available. Adding a vector in addition to the units indicating if units are available or not (equal to INTERFACE_UNITS_AVAILABLE where units are available and equal to INTERFAC...
get_parent_units_obs
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def get_previous_tokens_units_obs (self, step = None): """ Get (required) units of tokens before step. Filling using INTERFACE_UNITS_UNAVAILABLE_FILLER where units are not available. Adding a vector in addition to the units indicating if units are available or not (equal to INTERFACE_UNI...
Get (required) units of tokens before step. Filling using INTERFACE_UNITS_UNAVAILABLE_FILLER where units are not available. Adding a vector in addition to the units indicating if units are available or not (equal to INTERFACE_UNITS_AVAILABLE where units are available and equal to INTERFACE_UNIT...
get_previous_tokens_units_obs
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def get_tokens_units_obs (self, step = None): """ Get (required) units of tokens at step. Filling using INTERFACE_UNITS_UNAVAILABLE_FILLER where units are not available. Adding a vector in addition to the units indicating if units are available or not (equal to INTERFACE_UNITS_AVAILABLE ...
Get (required) units of tokens at step. Filling using INTERFACE_UNITS_UNAVAILABLE_FILLER where units are not available. Adding a vector in addition to the units indicating if units are available or not (equal to INTERFACE_UNITS_AVAILABLE where units are available and equal to INTERFACE_UNITS_UN...
get_tokens_units_obs
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def get_obs(self): """ Computes observation of current step for symbolic regression task. Returns ------- obs : numpy.array of shape (batch_size, 3*n_choices+1,) of float """ # Relatives one-hots parent_one_hot = self.get_parent_one_hot() ...
Computes observation of current step for symbolic regression task. Returns ------- obs : numpy.array of shape (batch_size, 3*n_choices+1,) of float
get_obs
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def get_rewards (self): """ Computes rewards of programs contained in batch. Returns ------- rewards : numpy.array of shape (batch_size,) of float Rewards of programs. """ rewards = self.rewards_computer(programs = self.programs, ...
Computes rewards of programs contained in batch. Returns ------- rewards : numpy.array of shape (batch_size,) of float Rewards of programs.
get_rewards
python
WassimTenachi/PhySO
physo/physym/batch.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch.py
MIT
def ParallelExeAvailability(verbose=False): """ Checks if parallel run is available on this system and produces a recommended config. Parameters ---------- verbose : bool Prints log. Returns ------- recommended_config : dict bool recommended_config[parallel_mode] : will p...
Checks if parallel run is available on this system and produces a recommended config. Parameters ---------- verbose : bool Prints log. Returns ------- recommended_config : dict bool recommended_config[parallel_mode] : will parallel mode work on this system ? int rec...
ParallelExeAvailability
python
WassimTenachi/PhySO
physo/physym/batch_execute.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch_execute.py
MIT
def BatchExecution (progs, X, # Realization related i_realization = 0, n_samples_per_dataset = None, # Mask mask = None, pad_with = np.NaN, # Parallel mode related ...
Executes prog(X) for each prog in progs and returns the results. NB: Parallel execution is typically slower because of communication time (parallel_mode = False is recommended). Parallel mode causes inter-process communication errors on some systems (probably due to the large number of information to p...
BatchExecution
python
WassimTenachi/PhySO
physo/physym/batch_execute.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch_execute.py
MIT
def BatchExecutionReduceGather (progs, X, reduce_wrapper, # Realization related i_realization = 0, n_samples_per_dataset = None, # Mask mask = None,...
Executes prog(X) for each prog in progs and gathers reduce_wrapper(prog(X)) as a result. NB: Parallel execution is typically slower because of communication time (even just gathering a float). Parameters ---------- progs : vect_programs.VectPrograms Programs in the batch. X : torch.tens...
BatchExecutionReduceGather
python
WassimTenachi/PhySO
physo/physym/batch_execute.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch_execute.py
MIT
def BatchExecutionReward (progs, X, y_target, reward_function, y_weights = 1., # Realization related i_realization = 0, n_samples_per_dataset = None, # Mask mask = None, ...
Executes prog(X) for each prog in progs and gathers reward_function(y_target, prog(X), y_weights) as a result. NB: Parallel execution is typically slower because of communication time (even just gathering a float). Parameters ---------- progs : vect_programs.VectPrograms Programs in the bat...
BatchExecutionReward
python
WassimTenachi/PhySO
physo/physym/batch_execute.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/batch_execute.py
MIT