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 convert_unet(pipe, args, model_name=None):
""" Converts the UNet component of Stable Diffusion
"""
if args.unet_support_controlnet:
unet_name = "control-unet"
else:
unet_name = model_name or "unet"
out_path = _get_out_path(args, unet_name)
# Check if Unet was previously exp... | Converts the UNet component of Stable Diffusion
| convert_unet | python | apple/ml-stable-diffusion | python_coreml_stable_diffusion/torch2coreml.py | https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py | MIT |
def convert_mmdit(args):
""" Converts the MMDiT component of Stable Diffusion 3
"""
out_path = _get_out_path(args, "mmdit")
if os.path.exists(out_path):
logger.info(
f"`mmdit` already exists at {out_path}, skipping conversion."
)
return
# Convert the MMDiT mo... | Converts the MMDiT component of Stable Diffusion 3
| convert_mmdit | python | apple/ml-stable-diffusion | python_coreml_stable_diffusion/torch2coreml.py | https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py | MIT |
def convert_safety_checker(pipe, args):
""" Converts the Safety Checker component of Stable Diffusion
"""
if pipe.safety_checker is None:
logger.warning(
f"diffusers pipeline for {args.model_version} does not have a `safety_checker` module! " \
"`--convert-safety-checker` wil... | Converts the Safety Checker component of Stable Diffusion
| convert_safety_checker | python | apple/ml-stable-diffusion | python_coreml_stable_diffusion/torch2coreml.py | https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py | MIT |
def convert_controlnet(pipe, args):
""" Converts each ControlNet for Stable Diffusion
"""
if not hasattr(pipe, "unet"):
raise RuntimeError(
"convert_unet() deletes pipe.unet to save RAM. "
"Please use convert_vae_encoder() before convert_unet()")
if not hasattr(pipe, "te... | Converts each ControlNet for Stable Diffusion
| convert_controlnet | python | apple/ml-stable-diffusion | python_coreml_stable_diffusion/torch2coreml.py | https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py | MIT |
def linear_to_conv2d_map(state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs):
""" Unsqueeze twice to map nn.Linear weights to nn.Conv2d weights
"""
for k in state_dict:
if 'weight' in k and len(state_dict[k].shape) == 2:
state_d... | Unsqueeze twice to map nn.Linear weights to nn.Conv2d weights
| linear_to_conv2d_map | python | apple/ml-stable-diffusion | python_coreml_stable_diffusion/unet.py | https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/unet.py | MIT |
def test_torch_to_coreml_conversion(self):
""" Tests:
- PyTorch to CoreML conversion via coremltools
"""
with self.subTest(model="vae_decoder"):
logger.info("Converting vae_decoder")
torch2coreml.convert_vae_decoder(self.pytorch_pipe, self.cli_args)
lo... | Tests:
- PyTorch to CoreML conversion via coremltools
| test_torch_to_coreml_conversion | python | apple/ml-stable-diffusion | tests/test_stable_diffusion.py | https://github.com/apple/ml-stable-diffusion/blob/master/tests/test_stable_diffusion.py | MIT |
def test_end_to_end_image_generation_speed(self):
""" Tests:
- Speed of CoreML runtime across several compute units
- Integration with `diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.py`
"""
latency = {
compute_unit:
self._coreml_text_to_im... | Tests:
- Speed of CoreML runtime across several compute units
- Integration with `diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.py`
| test_end_to_end_image_generation_speed | python | apple/ml-stable-diffusion | tests/test_stable_diffusion.py | https://github.com/apple/ml-stable-diffusion/blob/master/tests/test_stable_diffusion.py | MIT |
def test_image_to_prompt_clip_score(self):
""" Tests:
Affinity of the generated image with the original prompt via CLIP score
"""
logger.warning(
"This test will download the CLIP ViT-B/16 model (approximately 600 MB) from Hugging Face"
)
from transformers im... | Tests:
Affinity of the generated image with the original prompt via CLIP score
| test_image_to_prompt_clip_score | python | apple/ml-stable-diffusion | tests/test_stable_diffusion.py | https://github.com/apple/ml-stable-diffusion/blob/master/tests/test_stable_diffusion.py | MIT |
def test_swift_cli_image_generation(self):
""" Tests:
- The bridge between Python and Swift CLI
- The signal parity of Swift CLI generated image with that of Python CLI
"""
# coremltools to Core ML compute unit mapping
compute_unit_map = {
"ALL": "all",
... | Tests:
- The bridge between Python and Swift CLI
- The signal parity of Swift CLI generated image with that of Python CLI
| test_swift_cli_image_generation | python | apple/ml-stable-diffusion | tests/test_stable_diffusion.py | https://github.com/apple/ml-stable-diffusion/blob/master/tests/test_stable_diffusion.py | MIT |
def _init_coreml_pipe(self, compute_unit):
""" Initializes CoreML pipe for the requested compute_unit
"""
assert compute_unit in ct.ComputeUnit._member_names_, f"Not a valid coremltools.ComputeUnit: {compute_unit}"
if self.active_compute_unit == compute_unit:
logger.info(
... | Initializes CoreML pipe for the requested compute_unit
| _init_coreml_pipe | python | apple/ml-stable-diffusion | tests/test_stable_diffusion.py | https://github.com/apple/ml-stable-diffusion/blob/master/tests/test_stable_diffusion.py | MIT |
def _coreml_text_to_image_with_compute_unit(self, compute_unit):
""" Benchmark end-to-end text-to-image generation with the requested compute_unit
"""
self._init_coreml_pipe(compute_unit)
# Warm up (not necessary in all settings but improves consistency for benchmarking)
logger.... | Benchmark end-to-end text-to-image generation with the requested compute_unit
| _coreml_text_to_image_with_compute_unit | python | apple/ml-stable-diffusion | tests/test_stable_diffusion.py | https://github.com/apple/ml-stable-diffusion/blob/master/tests/test_stable_diffusion.py | MIT |
def test_coreml_text_to_image_speed():
""" Execute Core ML based image generation
"""
_reset_seed()
image = self.coreml_pipe(TEST_PROMPT)["images"][0]
out_path = pipeline.get_image_path(self.cli_args,
prompt=TEST_PROMPT,... | Execute Core ML based image generation
| test_coreml_text_to_image_speed | python | apple/ml-stable-diffusion | tests/test_stable_diffusion.py | https://github.com/apple/ml-stable-diffusion/blob/master/tests/test_stable_diffusion.py | MIT |
def classify(self, input):
"""return the index of the cluster closest to the input"""
return min(range(self.k),
key=lambda i: squared_distance(input, self.means[i])) | return the index of the cluster closest to the input | classify | python | joelgrus/data-science-from-scratch | first-edition/code/clustering.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/clustering.py | MIT |
def squared_clustering_errors(inputs, k):
"""finds the total squared error from k-means clustering the inputs"""
clusterer = KMeans(k)
clusterer.train(inputs)
means = clusterer.means
assignments = map(clusterer.classify, inputs)
return sum(squared_distance(input,means[cluster])
... | finds the total squared error from k-means clustering the inputs | squared_clustering_errors | python | joelgrus/data-science-from-scratch | first-edition/code/clustering.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/clustering.py | MIT |
def get_children(cluster):
"""returns the two children of this cluster if it's a merged cluster;
raises an exception if this is a leaf cluster"""
if is_leaf(cluster):
raise TypeError("a leaf cluster has no children")
else:
return cluster[1] | returns the two children of this cluster if it's a merged cluster;
raises an exception if this is a leaf cluster | get_children | python | joelgrus/data-science-from-scratch | first-edition/code/clustering.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/clustering.py | MIT |
def get_values(cluster):
"""returns the value in this cluster (if it's a leaf cluster)
or all the values in the leaf clusters below it (if it's not)"""
if is_leaf(cluster):
return cluster # is already a 1-tuple containing value
else:
return [value
for child in get_childre... | returns the value in this cluster (if it's a leaf cluster)
or all the values in the leaf clusters below it (if it's not) | get_values | python | joelgrus/data-science-from-scratch | first-edition/code/clustering.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/clustering.py | MIT |
def cluster_distance(cluster1, cluster2, distance_agg=min):
"""finds the aggregate distance between elements of cluster1
and elements of cluster2"""
return distance_agg([distance(input1, input2)
for input1 in get_values(cluster1)
for input2 in get_values(clust... | finds the aggregate distance between elements of cluster1
and elements of cluster2 | cluster_distance | python | joelgrus/data-science-from-scratch | first-edition/code/clustering.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/clustering.py | MIT |
def where(self, predicate=lambda row: True):
"""return only the rows that satisfy the supplied predicate"""
where_table = Table(self.columns)
where_table.rows = filter(predicate, self.rows)
return where_table | return only the rows that satisfy the supplied predicate | where | python | joelgrus/data-science-from-scratch | first-edition/code/databases.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/databases.py | MIT |
def partition_entropy(subsets):
"""find the entropy from this partition of data into subsets"""
total_count = sum(len(subset) for subset in subsets)
return sum( data_entropy(subset) * len(subset) / total_count
for subset in subsets ) | find the entropy from this partition of data into subsets | partition_entropy | python | joelgrus/data-science-from-scratch | first-edition/code/decision_trees.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/decision_trees.py | MIT |
def group_by(items, key_fn):
"""returns a defaultdict(list), where each input item
is in the list whose key is key_fn(item)"""
groups = defaultdict(list)
for item in items:
key = key_fn(item)
groups[key].append(item)
return groups | returns a defaultdict(list), where each input item
is in the list whose key is key_fn(item) | group_by | python | joelgrus/data-science-from-scratch | first-edition/code/decision_trees.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/decision_trees.py | MIT |
def classify(tree, input):
"""classify the input using the given decision tree"""
# if this is a leaf node, return its value
if tree in [True, False]:
return tree
# otherwise find the correct subtree
attribute, subtree_dict = tree
subtree_key = input.get(attribute) # None ... | classify the input using the given decision tree | classify | python | joelgrus/data-science-from-scratch | first-edition/code/decision_trees.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/decision_trees.py | MIT |
def is_video(td):
"""it's a video if it has exactly one pricelabel, and if
the stripped text inside that pricelabel starts with 'Video'"""
pricelabels = td('span', 'pricelabel')
return (len(pricelabels) == 1 and
pricelabels[0].text.strip().startswith("Video")) | it's a video if it has exactly one pricelabel, and if
the stripped text inside that pricelabel starts with 'Video' | is_video | python | joelgrus/data-science-from-scratch | first-edition/code/getting_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/getting_data.py | MIT |
def book_info(td):
"""given a BeautifulSoup <td> Tag representing a book,
extract the book's details and return a dict"""
title = td.find("div", "thumbheader").a.text
by_author = td.find('div', 'AuthorName').text
authors = [x.strip() for x in re.sub("^By ", "", by_author).split(",")]
isbn_l... | given a BeautifulSoup <td> Tag representing a book,
extract the book's details and return a dict | book_info | python | joelgrus/data-science-from-scratch | first-edition/code/getting_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/getting_data.py | MIT |
def on_success(self, data):
"""what do we do when twitter sends us data?
here data will be a Python object representing a tweet"""
# only want to collect English-language tweets
if data['lang'] == 'en':
tweets.append(data)
# stop when we've collected enough
... | what do we do when twitter sends us data?
here data will be a Python object representing a tweet | on_success | python | joelgrus/data-science-from-scratch | first-edition/code/getting_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/getting_data.py | MIT |
def safe(f):
"""define a new function that wraps f and return it"""
def safe_f(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
return float('inf') # this means "infinity" in Python
return safe_f | define a new function that wraps f and return it | safe | python | joelgrus/data-science-from-scratch | first-edition/code/gradient_descent.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/gradient_descent.py | MIT |
def minimize_batch(target_fn, gradient_fn, theta_0, tolerance=0.000001):
"""use gradient descent to find theta that minimizes target function"""
step_sizes = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001]
theta = theta_0 # set theta to initial value
target_fn = safe(... | use gradient descent to find theta that minimizes target function | minimize_batch | python | joelgrus/data-science-from-scratch | first-edition/code/gradient_descent.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/gradient_descent.py | MIT |
def in_random_order(data):
"""generator that returns the elements of data in random order"""
indexes = [i for i, _ in enumerate(data)] # create a list of indexes
random.shuffle(indexes) # shuffle them
for i in indexes: # return the data in that order
... | generator that returns the elements of data in random order | in_random_order | python | joelgrus/data-science-from-scratch | first-edition/code/gradient_descent.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/gradient_descent.py | MIT |
def normal_approximation_to_binomial(n, p):
"""finds mu and sigma corresponding to a Binomial(n, p)"""
mu = p * n
sigma = math.sqrt(p * (1 - p) * n)
return mu, sigma | finds mu and sigma corresponding to a Binomial(n, p) | normal_approximation_to_binomial | python | joelgrus/data-science-from-scratch | first-edition/code/hypothesis_and_inference.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/hypothesis_and_inference.py | MIT |
def normal_two_sided_bounds(probability, mu=0, sigma=1):
"""returns the symmetric (about the mean) bounds
that contain the specified probability"""
tail_probability = (1 - probability) / 2
# upper bound should have tail_probability above it
upper_bound = normal_lower_bound(tail_probability, mu, si... | returns the symmetric (about the mean) bounds
that contain the specified probability | normal_two_sided_bounds | python | joelgrus/data-science-from-scratch | first-edition/code/hypothesis_and_inference.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/hypothesis_and_inference.py | MIT |
def not_friends(user, other_user):
"""other_user is not a friend if he's not in user["friends"];
that is, if he's not_the_same as all the people in user["friends"]"""
return all(not_the_same(friend, other_user)
for friend in user["friends"]) | other_user is not a friend if he's not in user["friends"];
that is, if he's not_the_same as all the people in user["friends"] | not_friends | python | joelgrus/data-science-from-scratch | first-edition/code/introduction.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/introduction.py | MIT |
def vector_mean(vectors):
"""compute the vector whose i-th element is the mean of the
i-th elements of the input vectors"""
n = len(vectors)
return scalar_multiply(1/n, vector_sum(vectors)) | compute the vector whose i-th element is the mean of the
i-th elements of the input vectors | vector_mean | python | joelgrus/data-science-from-scratch | first-edition/code/linear_algebra.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/linear_algebra.py | MIT |
def make_matrix(num_rows, num_cols, entry_fn):
"""returns a num_rows x num_cols matrix
whose (i,j)-th entry is entry_fn(i, j)"""
return [[entry_fn(i, j) for j in range(num_cols)]
for i in range(num_rows)] | returns a num_rows x num_cols matrix
whose (i,j)-th entry is entry_fn(i, j) | make_matrix | python | joelgrus/data-science-from-scratch | first-edition/code/linear_algebra.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/linear_algebra.py | MIT |
def logistic_log_gradient_i(x_i, y_i, beta):
"""the gradient of the log likelihood
corresponding to the i-th data point"""
return [logistic_log_partial_ij(x_i, y_i, beta, j)
for j, _ in enumerate(beta)] | the gradient of the log likelihood
corresponding to the i-th data point | logistic_log_gradient_i | python | joelgrus/data-science-from-scratch | first-edition/code/logistic_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/logistic_regression.py | MIT |
def split_data(data, prob):
"""split data into fractions [prob, 1 - prob]"""
results = [], []
for row in data:
results[0 if random.random() < prob else 1].append(row)
return results | split data into fractions [prob, 1 - prob] | split_data | python | joelgrus/data-science-from-scratch | first-edition/code/machine_learning.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/machine_learning.py | MIT |
def word_count(documents):
"""count the words in the input documents using MapReduce"""
# place to store grouped values
collector = defaultdict(list)
for document in documents:
for word, count in wc_mapper(document):
collector[word].append(count)
return [output
fo... | count the words in the input documents using MapReduce | word_count | python | joelgrus/data-science-from-scratch | first-edition/code/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/mapreduce.py | MIT |
def map_reduce(inputs, mapper, reducer):
"""runs MapReduce on the inputs using mapper and reducer"""
collector = defaultdict(list)
for input in inputs:
for key, value in mapper(input):
collector[key].append(value)
return [output
for key, values in collector.iteritems()
... | runs MapReduce on the inputs using mapper and reducer | map_reduce | python | joelgrus/data-science-from-scratch | first-edition/code/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/mapreduce.py | MIT |
def most_popular_word_reducer(user, words_and_counts):
"""given a sequence of (word, count) pairs,
return the word with the highest total count"""
word_counts = Counter()
for word, count in words_and_counts:
word_counts[word] += count
word, count = word_counts.most_common(1)[0]
... | given a sequence of (word, count) pairs,
return the word with the highest total count | most_popular_word_reducer | python | joelgrus/data-science-from-scratch | first-edition/code/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/mapreduce.py | MIT |
def matrix_multiply_mapper(m, element):
"""m is the common dimension (columns of A, rows of B)
element is a tuple (matrix_name, i, j, value)"""
matrix, i, j, value = element
if matrix == "A":
for column in range(m):
# A_ij is the jth entry in the sum for each C_i_column
... | m is the common dimension (columns of A, rows of B)
element is a tuple (matrix_name, i, j, value) | matrix_multiply_mapper | python | joelgrus/data-science-from-scratch | first-edition/code/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/mapreduce.py | MIT |
def squared_error_gradient(x_i, y_i, beta):
"""the gradient corresponding to the ith squared error term"""
return [-2 * x_ij * error(x_i, y_i, beta)
for x_ij in x_i] | the gradient corresponding to the ith squared error term | squared_error_gradient | python | joelgrus/data-science-from-scratch | first-edition/code/multiple_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/multiple_regression.py | MIT |
def bootstrap_statistic(data, stats_fn, num_samples):
"""evaluates stats_fn on num_samples bootstrap samples from data"""
return [stats_fn(bootstrap_sample(data))
for _ in range(num_samples)] | evaluates stats_fn on num_samples bootstrap samples from data | bootstrap_statistic | python | joelgrus/data-science-from-scratch | first-edition/code/multiple_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/multiple_regression.py | MIT |
def estimate_beta_ridge(x, y, alpha):
"""use gradient descent to fit a ridge regression
with penalty alpha"""
beta_initial = [random.random() for x_i in x[0]]
return minimize_stochastic(partial(squared_error_ridge, alpha=alpha),
partial(squared_error_ridge_gradient,
... | use gradient descent to fit a ridge regression
with penalty alpha | estimate_beta_ridge | python | joelgrus/data-science-from-scratch | first-edition/code/multiple_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/multiple_regression.py | MIT |
def count_words(training_set):
"""training set consists of pairs (message, is_spam)"""
counts = defaultdict(lambda: [0, 0])
for message, is_spam in training_set:
for word in tokenize(message):
counts[word][0 if is_spam else 1] += 1
return counts | training set consists of pairs (message, is_spam) | count_words | python | joelgrus/data-science-from-scratch | first-edition/code/naive_bayes.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/naive_bayes.py | MIT |
def word_probabilities(counts, total_spams, total_non_spams, k=0.5):
"""turn the word_counts into a list of triplets
w, p(w | spam) and p(w | ~spam)"""
return [(w,
(spam + k) / (total_spams + 2 * k),
(non_spam + k) / (total_non_spams + 2 * k))
for w, (spam, non_spam) ... | turn the word_counts into a list of triplets
w, p(w | spam) and p(w | ~spam) | word_probabilities | python | joelgrus/data-science-from-scratch | first-edition/code/naive_bayes.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/naive_bayes.py | MIT |
def p_topic_given_document(topic, d, alpha=0.1):
"""the fraction of words in document _d_
that are assigned to _topic_ (plus some smoothing)"""
return ((document_topic_counts[d][topic] + alpha) /
(document_lengths[d] + K * alpha)) | the fraction of words in document _d_
that are assigned to _topic_ (plus some smoothing) | p_topic_given_document | python | joelgrus/data-science-from-scratch | first-edition/code/natural_language_processing.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/natural_language_processing.py | MIT |
def p_word_given_topic(word, topic, beta=0.1):
"""the fraction of words assigned to _topic_
that equal _word_ (plus some smoothing)"""
return ((topic_word_counts[topic][word] + beta) /
(topic_counts[topic] + W * beta)) | the fraction of words assigned to _topic_
that equal _word_ (plus some smoothing) | p_word_given_topic | python | joelgrus/data-science-from-scratch | first-edition/code/natural_language_processing.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/natural_language_processing.py | MIT |
def majority_vote(labels):
"""assumes that labels are ordered from nearest to farthest"""
vote_counts = Counter(labels)
winner, winner_count = vote_counts.most_common(1)[0]
num_winners = len([count
for count in vote_counts.values()
if count == winner_count]... | assumes that labels are ordered from nearest to farthest | majority_vote | python | joelgrus/data-science-from-scratch | first-edition/code/nearest_neighbors.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/nearest_neighbors.py | MIT |
def knn_classify(k, labeled_points, new_point):
"""each labeled point should be a pair (point, label)"""
# order the labeled points from nearest to farthest
by_distance = sorted(labeled_points,
key=lambda (point, _): distance(point, new_point))
# find the labels for the k ... | each labeled point should be a pair (point, label) | knn_classify | python | joelgrus/data-science-from-scratch | first-edition/code/nearest_neighbors.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/nearest_neighbors.py | MIT |
def farness(user):
"""the sum of the lengths of the shortest paths to each other user"""
return sum(len(paths[0])
for paths in user["shortest_paths"].values()) | the sum of the lengths of the shortest paths to each other user | farness | python | joelgrus/data-science-from-scratch | first-edition/code/network_analysis.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/network_analysis.py | MIT |
def feed_forward(neural_network, input_vector):
"""takes in a neural network (represented as a list of lists of lists of weights)
and returns the output from forward-propagating the input"""
outputs = []
for layer in neural_network:
input_with_bias = input_vector + [1] # add a bia... | takes in a neural network (represented as a list of lists of lists of weights)
and returns the output from forward-propagating the input | feed_forward | python | joelgrus/data-science-from-scratch | first-edition/code/neural_networks.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/neural_networks.py | MIT |
def patch(x, y, hatch, color):
"""return a matplotlib 'patch' object with the specified
location, crosshatch pattern, and color"""
return matplotlib.patches.Rectangle((x - 0.5, y - 0.5), 1, 1,
hatch=hatch, fill=False, color=color) | return a matplotlib 'patch' object with the specified
location, crosshatch pattern, and color | patch | python | joelgrus/data-science-from-scratch | first-edition/code/neural_networks.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/neural_networks.py | MIT |
def uniform_cdf(x):
"returns the probability that a uniform random variable is less than x"
if x < 0: return 0 # uniform random is never less than 0
elif x < 1: return x # e.g. P(X < 0.4) = 0.4
else: return 1 # uniform random is always less than 1 | returns the probability that a uniform random variable is less than x | uniform_cdf | python | joelgrus/data-science-from-scratch | first-edition/code/probability.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/probability.py | MIT |
def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=0.00001):
"""find approximate inverse using binary search"""
# if not standard, compute standard and rescale
if mu != 0 or sigma != 1:
return mu + sigma * inverse_normal_cdf(p, tolerance=tolerance)
low_z, low_p = -10.0, 0 # norm... | find approximate inverse using binary search | inverse_normal_cdf | python | joelgrus/data-science-from-scratch | first-edition/code/probability.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/probability.py | MIT |
def make_user_interest_vector(user_interests):
"""given a list of interests, produce a vector whose i-th element is 1
if unique_interests[i] is in the list, 0 otherwise"""
return [1 if interest in user_interests else 0
for interest in unique_interests] | given a list of interests, produce a vector whose i-th element is 1
if unique_interests[i] is in the list, 0 otherwise | make_user_interest_vector | python | joelgrus/data-science-from-scratch | first-edition/code/recommender_systems.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/recommender_systems.py | MIT |
def least_squares_fit(x,y):
"""given training values for x and y,
find the least-squares values of alpha and beta"""
beta = correlation(x, y) * standard_deviation(y) / standard_deviation(x)
alpha = mean(y) - beta * mean(x)
return alpha, beta | given training values for x and y,
find the least-squares values of alpha and beta | least_squares_fit | python | joelgrus/data-science-from-scratch | first-edition/code/simple_linear_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/simple_linear_regression.py | MIT |
def median(v):
"""finds the 'middle-most' value of v"""
n = len(v)
sorted_v = sorted(v)
midpoint = n // 2
if n % 2 == 1:
# if odd, return the middle value
return sorted_v[midpoint]
else:
# if even, return the average of the middle values
lo = midpoint - 1
... | finds the 'middle-most' value of v | median | python | joelgrus/data-science-from-scratch | first-edition/code/statistics.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/statistics.py | MIT |
def mode(x):
"""returns a list, might be more than one mode"""
counts = Counter(x)
max_count = max(counts.values())
return [x_i for x_i, count in counts.iteritems()
if count == max_count] | returns a list, might be more than one mode | mode | python | joelgrus/data-science-from-scratch | first-edition/code/statistics.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/statistics.py | MIT |
def de_mean(x):
"""translate x by subtracting its mean (so the result has mean 0)"""
x_bar = mean(x)
return [x_i - x_bar for x_i in x] | translate x by subtracting its mean (so the result has mean 0) | de_mean | python | joelgrus/data-science-from-scratch | first-edition/code/statistics.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/statistics.py | MIT |
def variance(x):
"""assumes x has at least two elements"""
n = len(x)
deviations = de_mean(x)
return sum_of_squares(deviations) / (n - 1) | assumes x has at least two elements | variance | python | joelgrus/data-science-from-scratch | first-edition/code/statistics.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/statistics.py | MIT |
def correlation_matrix(data):
"""returns the num_columns x num_columns matrix whose (i, j)th entry
is the correlation between columns i and j of data"""
_, num_columns = shape(data)
def matrix_entry(i, j):
return correlation(get_column(data, i), get_column(data, j))
return make_matrix(num... | returns the num_columns x num_columns matrix whose (i, j)th entry
is the correlation between columns i and j of data | correlation_matrix | python | joelgrus/data-science-from-scratch | first-edition/code/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/working_with_data.py | MIT |
def parse_row(input_row, parsers):
"""given a list of parsers (some of which may be None)
apply the appropriate one to each element of the input_row"""
return [parser(value) if parser is not None else value
for value, parser in zip(input_row, parsers)] | given a list of parsers (some of which may be None)
apply the appropriate one to each element of the input_row | parse_row | python | joelgrus/data-science-from-scratch | first-edition/code/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/working_with_data.py | MIT |
def parse_rows_with(reader, parsers):
"""wrap a reader to apply the parsers to each of its rows"""
for row in reader:
yield parse_row(row, parsers) | wrap a reader to apply the parsers to each of its rows | parse_rows_with | python | joelgrus/data-science-from-scratch | first-edition/code/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/working_with_data.py | MIT |
def try_or_none(f):
"""wraps f to return None if f raises an exception
assumes f takes only one input"""
def f_or_none(x):
try: return f(x)
except: return None
return f_or_none | wraps f to return None if f raises an exception
assumes f takes only one input | try_or_none | python | joelgrus/data-science-from-scratch | first-edition/code/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/working_with_data.py | MIT |
def try_parse_field(field_name, value, parser_dict):
"""try to parse value using the appropriate function from parser_dict"""
parser = parser_dict.get(field_name) # None if no such entry
if parser is not None:
return try_or_none(parser)(value)
else:
return value | try to parse value using the appropriate function from parser_dict | try_parse_field | python | joelgrus/data-science-from-scratch | first-edition/code/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/working_with_data.py | MIT |
def rescale(data_matrix):
"""rescales the input data so that each column
has mean 0 and standard deviation 1
ignores columns with no deviation"""
means, stdevs = scale(data_matrix)
def rescaled(i, j):
if stdevs[j] > 0:
return (data_matrix[i][j] - means[j]) / stdevs[j]
e... | rescales the input data so that each column
has mean 0 and standard deviation 1
ignores columns with no deviation | rescale | python | joelgrus/data-science-from-scratch | first-edition/code/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/working_with_data.py | MIT |
def de_mean_matrix(A):
"""returns the result of subtracting from every value in A the mean
value of its column. the resulting matrix has mean 0 in every column"""
nr, nc = shape(A)
column_means, _ = scale(A)
return make_matrix(nr, nc, lambda i, j: A[i][j] - column_means[j]) | returns the result of subtracting from every value in A the mean
value of its column. the resulting matrix has mean 0 in every column | de_mean_matrix | python | joelgrus/data-science-from-scratch | first-edition/code/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/working_with_data.py | MIT |
def directional_variance_gradient_i(x_i, w):
"""the contribution of row x_i to the gradient of
the direction-w variance"""
projection_length = dot(x_i, direction(w))
return [2 * projection_length * x_ij for x_ij in x_i] | the contribution of row x_i to the gradient of
the direction-w variance | directional_variance_gradient_i | python | joelgrus/data-science-from-scratch | first-edition/code/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code/working_with_data.py | MIT |
def group_by(items, key_fn):
"""returns a defaultdict(list), where each input item
is in the list whose key is key_fn(item)"""
groups = defaultdict(list)
for item in items:
key = key_fn(item)
groups[key].append(item)
return groups | returns a defaultdict(list), where each input item
is in the list whose key is key_fn(item) | group_by | python | joelgrus/data-science-from-scratch | first-edition/code-python3/decision_trees.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code-python3/decision_trees.py | MIT |
def normal_two_sided_bounds(probability, mu=0, sigma=1):
"""returns the symmetric (about the mean) bounds
that contain the specified probability"""
tail_probability = (1 - probability) / 2
# upper bound should have tail_probability above it
upper_bound = normal_lower_bound(tail_probability, mu, sig... | returns the symmetric (about the mean) bounds
that contain the specified probability | normal_two_sided_bounds | python | joelgrus/data-science-from-scratch | first-edition/code-python3/hypothesis_and_inference.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code-python3/hypothesis_and_inference.py | MIT |
def make_matrix(num_rows, num_cols, entry_fn):
"""returns a num_rows x num_cols matrix
whose (i,j)-th entry is entry_fn(i, j)"""
return [[entry_fn(i, j) for j in range(num_cols)]
for i in range(num_rows)] | returns a num_rows x num_cols matrix
whose (i,j)-th entry is entry_fn(i, j) | make_matrix | python | joelgrus/data-science-from-scratch | first-edition/code-python3/linear_algebra.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code-python3/linear_algebra.py | MIT |
def logistic_log_gradient_i(x_i, y_i, beta):
"""the gradient of the log likelihood
corresponding to the i-th data point"""
return [logistic_log_partial_ij(x_i, y_i, beta, j)
for j, _ in enumerate(beta)] | the gradient of the log likelihood
corresponding to the i-th data point | logistic_log_gradient_i | python | joelgrus/data-science-from-scratch | first-edition/code-python3/logistic_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code-python3/logistic_regression.py | MIT |
def most_popular_word_reducer(user, words_and_counts):
"""given a sequence of (word, count) pairs,
return the word with the highest total count"""
word_counts = Counter()
for word, count in words_and_counts:
word_counts[word] += count
word, count = word_counts.most_common(1)[0]
yield ... | given a sequence of (word, count) pairs,
return the word with the highest total count | most_popular_word_reducer | python | joelgrus/data-science-from-scratch | first-edition/code-python3/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code-python3/mapreduce.py | MIT |
def word_probabilities(counts, total_spams, total_non_spams, k=0.5):
"""turn the word_counts into a list of triplets
w, p(w | spam) and p(w | ~spam)"""
return [(w,
(spam + k) / (total_spams + 2 * k),
(non_spam + k) / (total_non_spams + 2 * k))
for w, (spam, non_spam) i... | turn the word_counts into a list of triplets
w, p(w | spam) and p(w | ~spam) | word_probabilities | python | joelgrus/data-science-from-scratch | first-edition/code-python3/naive_bayes.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code-python3/naive_bayes.py | MIT |
def cluster_distance(cluster1: Cluster,
cluster2: Cluster,
distance_agg: Callable = min) -> float:
"""
compute all the pairwise distances between cluster1 and cluster2
and apply the aggregation function _distance_agg_ to the resulting list
"""
return distanc... |
compute all the pairwise distances between cluster1 and cluster2
and apply the aggregation function _distance_agg_ to the resulting list
| cluster_distance | python | joelgrus/data-science-from-scratch | scratch/clustering.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/clustering.py | MIT |
def doubler_correct(f):
"""works no matter what kind of inputs f expects"""
def g(*args, **kwargs):
"""whatever arguments g is supplied, pass them through to f"""
return 2 * f(*args, **kwargs)
return g | works no matter what kind of inputs f expects | doubler_correct | python | joelgrus/data-science-from-scratch | scratch/crash_course_in_python.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/crash_course_in_python.py | MIT |
def where(self, predicate: WhereClause = lambda row: True) -> 'Table':
"""Return only the rows that satisfy the supplied predicate"""
where_table = Table(self.columns, self.types)
for row in self.rows:
if predicate(row):
values = [row[column] for column in self.column... | Return only the rows that satisfy the supplied predicate | where | python | joelgrus/data-science-from-scratch | scratch/databases.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/databases.py | MIT |
def entropy(class_probabilities: List[float]) -> float:
"""Given a list of class probabilities, compute the entropy"""
return sum(-p * math.log(p, 2)
for p in class_probabilities
if p > 0) # ignore zero probabilities | Given a list of class probabilities, compute the entropy | entropy | python | joelgrus/data-science-from-scratch | scratch/decision_trees.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/decision_trees.py | MIT |
def partition_entropy(subsets: List[List[Any]]) -> float:
"""Returns the entropy from this partition of data into subsets"""
total_count = sum(len(subset) for subset in subsets)
return sum(data_entropy(subset) * len(subset) / total_count
for subset in subsets) | Returns the entropy from this partition of data into subsets | partition_entropy | python | joelgrus/data-science-from-scratch | scratch/decision_trees.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/decision_trees.py | MIT |
def partition_by(inputs: List[T], attribute: str) -> Dict[Any, List[T]]:
"""Partition the inputs into lists based on the specified attribute."""
partitions: Dict[Any, List[T]] = defaultdict(list)
for input in inputs:
key = getattr(input, attribute) # value of the specified attribute
partiti... | Partition the inputs into lists based on the specified attribute. | partition_by | python | joelgrus/data-science-from-scratch | scratch/decision_trees.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/decision_trees.py | MIT |
def partition_entropy_by(inputs: List[Any],
attribute: str,
label_attribute: str) -> float:
"""Compute the entropy corresponding to the given partition"""
# partitions consist of our inputs
partitions = partition_by(inputs, attribute)
# but partition_en... | Compute the entropy corresponding to the given partition | partition_entropy_by | python | joelgrus/data-science-from-scratch | scratch/decision_trees.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/decision_trees.py | MIT |
def tensor_sum(tensor: Tensor) -> float:
"""Sums up all the values in the tensor"""
if is_1d(tensor):
return sum(tensor) # just a list of floats, use Python sum
else:
return sum(tensor_sum(tensor_i) # Call tensor_sum on each row
for tensor_i in tensor) # and sum up... | Sums up all the values in the tensor | tensor_sum | python | joelgrus/data-science-from-scratch | scratch/deep_learning.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/deep_learning.py | MIT |
def tensor_combine(f: Callable[[float, float], float],
t1: Tensor,
t2: Tensor) -> Tensor:
"""Applies f to corresponding elements of t1 and t2"""
if is_1d(t1):
return [f(x, y) for x, y in zip(t1, t2)]
else:
return [tensor_combine(f, t1_i, t2_i)
... | Applies f to corresponding elements of t1 and t2 | tensor_combine | python | joelgrus/data-science-from-scratch | scratch/deep_learning.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/deep_learning.py | MIT |
def __init__(self, input_dim: int, output_dim: int, init: str = 'xavier') -> None:
"""
A layer of output_dim neurons, each with input_dim weights
(and a bias).
"""
self.input_dim = input_dim
self.output_dim = output_dim
# self.w[o] is the weights for the o-th neu... |
A layer of output_dim neurons, each with input_dim weights
(and a bias).
| __init__ | python | joelgrus/data-science-from-scratch | scratch/deep_learning.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/deep_learning.py | MIT |
def forward(self, input):
"""Just forward the input through the layers in order."""
for layer in self.layers:
input = layer.forward(input)
return input | Just forward the input through the layers in order. | forward | python | joelgrus/data-science-from-scratch | scratch/deep_learning.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/deep_learning.py | MIT |
def backward(self, gradient):
"""Just backpropagate the gradient through the layers in reverse."""
for layer in reversed(self.layers):
gradient = layer.backward(gradient)
return gradient | Just backpropagate the gradient through the layers in reverse. | backward | python | joelgrus/data-science-from-scratch | scratch/deep_learning.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/deep_learning.py | MIT |
def paragraph_mentions(text: str, keyword: str) -> bool:
"""
Returns True if a <p> inside the text mentions {keyword}
"""
soup = BeautifulSoup(text, 'html5lib')
paragraphs = [p.get_text() for p in soup('p')]
return any(keyword.lower() in paragraph.lower()
for paragraph in paragra... |
Returns True if a <p> inside the text mentions {keyword}
| paragraph_mentions | python | joelgrus/data-science-from-scratch | scratch/getting_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/getting_data.py | MIT |
def on_success(self, data):
"""
What do we do when twitter sends us data?
Here data will be a Python dict representing a tweet
"""
# We only want to collect English-language tweets
if data.get('lang') == 'en':
tweets.append(data)
... |
What do we do when twitter sends us data?
Here data will be a Python dict representing a tweet
| on_success | python | joelgrus/data-science-from-scratch | scratch/getting_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/getting_data.py | MIT |
def gradient_step(v: Vector, gradient: Vector, step_size: float) -> Vector:
"""Moves `step_size` in the `gradient` direction from `v`"""
assert len(v) == len(gradient)
step = scalar_multiply(step_size, gradient)
return add(v, step) | Moves `step_size` in the `gradient` direction from `v` | gradient_step | python | joelgrus/data-science-from-scratch | scratch/gradient_descent.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/gradient_descent.py | MIT |
def minibatches(dataset: List[T],
batch_size: int,
shuffle: bool = True) -> Iterator[List[T]]:
"""Generates `batch_size`-sized minibatches from the dataset"""
# Start indexes 0, batch_size, 2 * batch_size, ...
batch_starts = [start for start in range(0, len(dataset), batch_si... | Generates `batch_size`-sized minibatches from the dataset | minibatches | python | joelgrus/data-science-from-scratch | scratch/gradient_descent.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/gradient_descent.py | MIT |
def partial_difference_quotient(f: Callable[[Vector], float],
v: Vector,
i: int,
h: float) -> float:
"""Returns the i-th partial difference quotient of f at v"""
w = [v_j + (h if j == i else 0) ... | Returns the i-th partial difference quotient of f at v | partial_difference_quotient | python | joelgrus/data-science-from-scratch | scratch/gradient_descent.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/gradient_descent.py | MIT |
def normal_approximation_to_binomial(n: int, p: float) -> Tuple[float, float]:
"""Returns mu and sigma corresponding to a Binomial(n, p)"""
mu = p * n
sigma = math.sqrt(p * (1 - p) * n)
return mu, sigma | Returns mu and sigma corresponding to a Binomial(n, p) | normal_approximation_to_binomial | python | joelgrus/data-science-from-scratch | scratch/inference.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/inference.py | MIT |
def normal_probability_above(lo: float,
mu: float = 0,
sigma: float = 1) -> float:
"""The probability that a N(mu, sigma) is greater than lo."""
return 1 - normal_cdf(lo, mu, sigma) | The probability that a N(mu, sigma) is greater than lo. | normal_probability_above | python | joelgrus/data-science-from-scratch | scratch/inference.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/inference.py | MIT |
def normal_probability_between(lo: float,
hi: float,
mu: float = 0,
sigma: float = 1) -> float:
"""The probability that a N(mu, sigma) is between lo and hi."""
return normal_cdf(hi, mu, sigma) - normal_cdf(lo, mu, sigma... | The probability that a N(mu, sigma) is between lo and hi. | normal_probability_between | python | joelgrus/data-science-from-scratch | scratch/inference.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/inference.py | MIT |
def normal_probability_outside(lo: float,
hi: float,
mu: float = 0,
sigma: float = 1) -> float:
"""The probability that a N(mu, sigma) is not between lo and hi."""
return 1 - normal_probability_between(lo, hi, mu, sigma... | The probability that a N(mu, sigma) is not between lo and hi. | normal_probability_outside | python | joelgrus/data-science-from-scratch | scratch/inference.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/inference.py | MIT |
def normal_two_sided_bounds(probability: float,
mu: float = 0,
sigma: float = 1) -> Tuple[float, float]:
"""
Returns the symmetric (about the mean) bounds
that contain the specified probability
"""
tail_probability = (1 - probability) / 2
... |
Returns the symmetric (about the mean) bounds
that contain the specified probability
| normal_two_sided_bounds | python | joelgrus/data-science-from-scratch | scratch/inference.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/inference.py | MIT |
def two_sided_p_value(x: float, mu: float = 0, sigma: float = 1) -> float:
"""
How likely are we to see a value at least as extreme as x (in either
direction) if our values are from a N(mu, sigma)?
"""
if x >= mu:
# x is greater than the mean, so the tail is everything greater than x
... |
How likely are we to see a value at least as extreme as x (in either
direction) if our values are from a N(mu, sigma)?
| two_sided_p_value | python | joelgrus/data-science-from-scratch | scratch/inference.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/inference.py | MIT |
def foaf_ids_bad(user):
"""foaf is short for "friend of a friend" """
return [foaf_id
for friend_id in friendships[user["id"]]
for foaf_id in friendships[friend_id]] | foaf is short for "friend of a friend" | foaf_ids_bad | python | joelgrus/data-science-from-scratch | scratch/introduction.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/introduction.py | MIT |
def data_scientists_who_like(target_interest):
"""Find the ids of all users who like the target interest."""
return [user_id
for user_id, user_interest in interests
if user_interest == target_interest] | Find the ids of all users who like the target interest. | data_scientists_who_like | python | joelgrus/data-science-from-scratch | scratch/introduction.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/introduction.py | MIT |
def majority_vote(labels: List[str]) -> str:
"""Assumes that labels are ordered from nearest to farthest."""
vote_counts = Counter(labels)
winner, winner_count = vote_counts.most_common(1)[0]
num_winners = len([count
for count in vote_counts.values()
if coun... | Assumes that labels are ordered from nearest to farthest. | majority_vote | python | joelgrus/data-science-from-scratch | scratch/k_nearest_neighbors.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/k_nearest_neighbors.py | MIT |
def shape(A: Matrix) -> Tuple[int, int]:
"""Returns (# of rows of A, # of columns of A)"""
num_rows = len(A)
num_cols = len(A[0]) if A else 0 # number of elements in first row
return num_rows, num_cols | Returns (# of rows of A, # of columns of A) | shape | python | joelgrus/data-science-from-scratch | scratch/linear_algebra.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/linear_algebra.py | MIT |
def get_column(A: Matrix, j: int) -> Vector:
"""Returns the j-th column of A (as a Vector)"""
return [A_i[j] # jth element of row A_i
for A_i in A] # for each row A_i | Returns the j-th column of A (as a Vector) | get_column | python | joelgrus/data-science-from-scratch | scratch/linear_algebra.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/linear_algebra.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.