markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
对填补好的数据进行建模 | #对所有数据进行建模,取得MSE结果
X = [X_full,X_missing_mean,X_missing_0,X_missing_reg]
mse = []
std = []
for x in X:
estimator = RandomForestRegressor(random_state=0, n_estimators=100)
scores = cross_val_score(estimator,x,y_full,scoring='neg_mean_squared_error',cv=5).mean()
mse.append(scores * -1)
x_labels = ['Full data... | _____no_output_____ | MIT | code/randomForest/bostonRegression.ipynb | Knowledge-Precipitation-Tribe/Machine-Learning |
Gradient-boosting decision tree (GBDT)In this notebook, we will present the gradient boosting decision treealgorithm and contrast it with AdaBoost.Gradient-boosting differs from AdaBoost due to the following reason: insteadof assigning weights to specific samples, GBDT will fit a decision tree onthe residuals error (h... | import pandas as pd
import numpy as np
# Create a random number generator that will be used to set the randomness
rng = np.random.RandomState(0)
def generate_data(n_samples=50):
"""Generate synthetic dataset. Returns `data_train`, `data_test`,
`target_train`."""
x_max, x_min = 1.4, -1.4
len_x = x_max... | _____no_output_____ | MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
As we previously discussed, boosting will be based on assembling a sequenceof learners. We will start by creating a decision tree regressor. We will setthe depth of the tree so that the resulting learner will underfit the data. | from sklearn.tree import DecisionTreeRegressor
tree = DecisionTreeRegressor(max_depth=3, random_state=0)
tree.fit(data_train, target_train)
target_train_predicted = tree.predict(data_train)
target_test_predicted = tree.predict(data_test) | _____no_output_____ | MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
Using the term "test" here refers to data that was not used for training.It should not be confused with data coming from a train-test split, as itwas generated in equally-spaced intervals for the visual evaluation of thepredictions. | # plot the data
sns.scatterplot(x=data_train["Feature"], y=target_train, color="black",
alpha=0.5)
# plot the predictions
line_predictions = plt.plot(data_test["Feature"], target_test_predicted, "--")
# plot the residuals
for value, true, predicted in zip(data_train["Feature"],
... | _____no_output_____ | MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
TipIn the cell above, we manually edited the legend to get only a single labelfor all the residual lines.Since the tree underfits the data, its accuracy is far from perfect on thetraining data. We can observe this in the figure by looking at the differencebetween the predictions and the ground-truth data. We represent ... | residuals = target_train - target_train_predicted
tree_residuals = DecisionTreeRegressor(max_depth=5, random_state=0)
tree_residuals.fit(data_train, residuals)
target_train_predicted_residuals = tree_residuals.predict(data_train)
target_test_predicted_residuals = tree_residuals.predict(data_test)
sns.scatterplot(x=da... | _____no_output_____ | MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
We see that this new tree only manages to fit some of the residuals. We willfocus on a specific sample from the training set (i.e. we know that thesample will be well predicted using two successive trees). We will use thissample to explain how the predictions of both trees are combined. Let's firstselect this sample in... | sample = data_train.iloc[[-2]]
x_sample = sample['Feature'].iloc[0]
target_true = target_train.iloc[-2]
target_true_residual = residuals.iloc[-2] | _____no_output_____ | MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
Let's plot the previous information and highlight our sample of interest.Let's start by plotting the original data and the prediction of the firstdecision tree. | # Plot the previous information:
# * the dataset
# * the predictions
# * the residuals
sns.scatterplot(x=data_train["Feature"], y=target_train, color="black",
alpha=0.5)
plt.plot(data_test["Feature"], target_test_predicted, "--")
for value, true, predicted in zip(data_train["Feature"],
... | _____no_output_____ | MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
Now, let's plot the residuals information. We will plot the residualscomputed from the first decision tree and show the residual predictions. | # Plot the previous information:
# * the residuals committed by the first tree
# * the residual predictions
# * the residuals of the residual predictions
sns.scatterplot(x=data_train["Feature"], y=residuals,
color="black", alpha=0.5)
plt.plot(data_test["Feature"], target_test_predicted_residuals,... | _____no_output_____ | MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
For our sample of interest, our initial tree is making an error (smallresidual). When fitting the second tree, the residual in this case isperfectly fitted and predicted. We will quantitatively check this predictionusing the fitted tree. First, let's check the prediction of the initial treeand compare it with the true ... | print(f"True value to predict for "
f"f(x={x_sample:.3f}) = {target_true:.3f}")
y_pred_first_tree = tree.predict(sample)[0]
print(f"Prediction of the first decision tree for x={x_sample:.3f}: "
f"y={y_pred_first_tree:.3f}")
print(f"Error of the tree: {target_true - y_pred_first_tree:.3f}") | True value to predict for f(x=-0.517) = -0.393
Prediction of the first decision tree for x=-0.517: y=-0.145
Error of the tree: -0.248
| MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
As we visually observed, we have a small error. Now, we can use the secondtree to try to predict this residual. | print(f"Prediction of the residual for x={x_sample:.3f}: "
f"{tree_residuals.predict(sample)[0]:.3f}") | Prediction of the residual for x=-0.517: -0.248
| MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
We see that our second tree is capable of predicting the exact residual(error) of our first tree. Therefore, we can predict the value of `x` bysumming the prediction of all the trees in the ensemble. | y_pred_first_and_second_tree = (
y_pred_first_tree + tree_residuals.predict(sample)[0]
)
print(f"Prediction of the first and second decision trees combined for "
f"x={x_sample:.3f}: y={y_pred_first_and_second_tree:.3f}")
print(f"Error of the tree: {target_true - y_pred_first_and_second_tree:.3f}") | Prediction of the first and second decision trees combined for x=-0.517: y=-0.393
Error of the tree: 0.000
| MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
We chose a sample for which only two trees were enough to make the perfectprediction. However, we saw in the previous plot that two trees were notenough to correct the residuals of all samples. Therefore, one needs toadd several trees to the ensemble to successfully correct the error(i.e. the second tree corrects the f... | from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import cross_validate
data, target = fetch_california_housing(return_X_y=True, as_frame=True)
target *= 100 # rescale the target in k$
from sklearn.ensemble import GradientBoostingRegressor
gradient_boosting = GradientBoostingRegresso... | _____no_output_____ | MIT | sklearn/notes/ensemble_gradient_boosting.ipynb | shamik-biswas-rft/CodeSnippets |
Untill now, we overview the functionality that Jupyter notebook provides for us. How does length of employee titles correlate to salary? | position_title = white_house["Position Title"]
title_length = position_title.apply(len)
salary = white_house["Salary"]
from scipy.stats.stats import pearsonr
pearsonr(title_length, salary)
plt.scatter(title_length, salary)
plt.xlabel("title length")
plt.ylabel("salary")
plt.title("Title length - Salary Scatter Plot")
p... | _____no_output_____ | MIT | White House/White House.ipynb | frankbearzou/Data-analysis |
How much does the White House pay in total salary? | white_house["Salary"].sum() | _____no_output_____ | MIT | White House/White House.ipynb | frankbearzou/Data-analysis |
Who are the highest and lowest paid staffers? | max_salary = white_house["Salary"].max()
max_salary_column = white_house["Salary"] == max_salary
white_house.loc[max_salary_column].reset_index(drop = True)
min_salary = white_house["Salary"].min()
min_salary_column = white_house["Salary"] == min_salary
white_house.loc[min_salary_column].reset_index(drop = True) | _____no_output_____ | MIT | White House/White House.ipynb | frankbearzou/Data-analysis |
What words are the most common in titles? | words = {}
for title in position_title:
title_list = title.split()
for word in title_list:
if word not in words:
words[word] = 1
else:
words[word] += 1
import operator
sorted_words = sorted(words.items(), key=operator.itemgetter(1), reverse = True)
sorted_words | _____no_output_____ | MIT | White House/White House.ipynb | frankbearzou/Data-analysis |
Saving frames in parallel | import xarray as xr
from xmovie import Movie
ds = xr.tutorial.open_dataset('air_temperature').isel(time=slice(0,200))
# Creating the movie object
mov = Movie(ds.air, vmin=230, vmax=310) | _____no_output_____ | MIT | docs/examples/parallel.ipynb | zmoon/xmovie |
The creation of a movie can take quite long for datasets with many timesteps, creating many frames in a loop. | %%time
mov.save('movie.mov', overwrite_existing=True) | Movie created at movie.mov
CPU times: user 34.7 s, sys: 1.02 s, total: 35.7 s
Wall time: 59.4 s
| MIT | docs/examples/parallel.ipynb | zmoon/xmovie |
You can speed up the frame creation by activating the `parallel` option. This will save the frames using dask.For this to work you need to chunk the input dataarray with a single step along the dimension that represent your frames (`framedim`). | mov_parallel = Movie(ds.air.chunk({'time':1}), vmin=230, vmax=310)
%%time
mov_parallel.save(
'movie_parallel.mov',
parallel=True,
overwrite_existing=True,
) | Movie created at movie_parallel.mov
CPU times: user 38.8 s, sys: 1.46 s, total: 40.3 s
Wall time: 48.3 s
| MIT | docs/examples/parallel.ipynb | zmoon/xmovie |
You can pass arguments to the dask `.compute()` call with `parallel_compute_kwargs` to tune for your particular setup. | %%time
mov_parallel.save(
'movie_parallel_modified.mov',
parallel=True,
overwrite_existing=True,
parallel_compute_kwargs=dict(scheduler="processes", num_workers=8)
) | Movie created at movie_parallel.mov
CPU times: user 4.84 s, sys: 249 ms, total: 5.09 s
Wall time: 33.6 s
| MIT | docs/examples/parallel.ipynb | zmoon/xmovie |
2A.i - Modèle relationnel, analyse d'incidents dans le transport aérien - correctionManipulation de données avec les dataframes, jointures. Correction inachevée... | from jyquickhelper import add_notebook_menu
add_notebook_menu() | _____no_output_____ | MIT | _doc/notebooks/td2a/td2a_correction_session_5.ipynb | mohamedelkansouli/Ensae_py |
DonnéesLe code suivant télécharge les données nécessaires [tp_2a_5_compagnies.zip](http://www.xavierdupre.fr/enseignement/complements/tp_2a_5_compagnies.zip). | import pyensae
pyensae.download_data("tp_2a_5_compagnies.zip") | _____no_output_____ | MIT | _doc/notebooks/td2a/td2a_correction_session_5.ipynb | mohamedelkansouli/Ensae_py |
Introduction 1.1 Some Apparently Simple Questions 1.2 An Alternative Analytic FrameworkSolved to a high degree of accuracy using numerical method | !pip install --user quantecon
import numpy as np
import numpy.linalg as la
from numba import *
from __future__ import division
#from quantecon.quad import qnwnorm
| _____no_output_____ | MIT | Chapter01.ipynb | lnsongxf/Applied_Computational_Economics_and_Finance |
Suppose now that the economist is presented with a demand function$$q = 0.5* p^{-0.2} + 0.5*p^{-0.5}$$one that is the sum a domestic demand term and an export demand term.suppose that the economist is asked to find the price that clears themarket of, say, a quantity of 2 units. | #%pylab inline
%pylab notebook
# pylab Populating the interactive namespace from numpy and matplotlib
# numpy for numerical computation
# matplotlib for ploting
#http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
p = np.linspace(0.01,0.5, 100)
q = .5 * p **-.2 + .5 * p ** -.5 - 2
plot(q,p)
x1,x2,y1,y2 = 2... | The market clean price is 0.15
| MIT | Chapter01.ipynb | lnsongxf/Applied_Computational_Economics_and_Finance |
Consider now the rational expectations commodity market model with governmentintervention. The source of difficulty in solving this problem is the need toevaluate the truncated expectation of a continuous distribution.The economist would replace the original normal yield distributionwith a discrete distribution that ha... | # https://github.com/QuantEcon/QuantEcon.py/blob/master/quantecon/quad.py
def qnwnorm(n, mu=None, sig2=None, usesqrtm=False):
"""
Computes nodes and weights for multivariate normal distribution
Parameters
----------
n : int or array_like(float)
A length-d iterable of the number of nodes in e... | The rational expectations equilibrium acreage is 1.10
The expected market price is 0.81
The expected effective producer price is 1.19
| MIT | Chapter01.ipynb | lnsongxf/Applied_Computational_Economics_and_Finance |
Linear AlgebraThose exercises will involve vector and matrix math, the NumPy Python package.This exercise will be divided into two parts: 1. Math checkupWhere you will do some of the math by hand. 2. NumPy and Spark linear algebraYou will do some exercise using the NumPy package.In the following exercises you will ne... | #from pyspark import SparkContext, StorageLevel \
#from pyspark.sql import SQLContext \
#sc = SparkContext(master="local[*]") \
#sqlContext = SQLContext(sc) \ | _____no_output_____ | Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
But since we are using the notebooks, those lines are not needed here. 1. Math checkup 1.1 Euclidian norm$$\mathbf{v} = \begin{bmatrix} 666 \\ 1337 \\ 1789 \\ 1066 \\ 1945 \\ \end{bmatrix} \qquad \|\mathbf{v}\| = ? $$Calculate the euclidian norm for the $\mathbf{v}$ using the following definition:$$\|\mathbf{v}\|... | #Replace the <INSERT>
import math
import numpy as np
v = [666, 1337, 1789, 1066, 1945]
rdd = sc.parallelize(v)
#sumOfSquares = rdd.map(<INSERT>).reduce(<INSERT>)
sumOfSquares = rdd.map(lambda x: x*x ).reduce(lambda x,y : x+y)
norm = math.sqrt(sumOfSquares)
# <INSERT round to 8 decimals >
norm = format(norm, '.8f')
... | b20f04e15c77f3ba100346dc128daa01
Try again!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
1.2 Transpose$$\mathbf{A} = \begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9\\ \end{bmatrix} \qquad \mathbf{A}^T = ?$$Tranpose is an operation on matrices that swaps the row for the columns.$$\begin{bmatrix} 2 & 7 \\ 3 & 11\\ 5 & 13\\ \end{bmatrix}^T \Rightarrow \begin{bmatrix} 2 & 3 & 5 \\ 7 & 11 & 13\\ \end... | #Replace the <INSERT>
#Input aT like this: AT = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
#At = <INSERT>
A= np.matrix([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(A)
print("\n")
At = np.matrix.transpose(A)
print (At)
At =[[1,4, 7],[2, 5, 8],[3, 6, 9]]
print("\n")
print (At)
#Check if the transpose is correct
hashCheck(At, '1c8dc4c23... | 1c8dc4c2349277cbe5b7c7118989d8a5
Yay, you succeeded!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
1.3 Scalar matrix multiplication$$\mathbf{A} = 3\times\begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9\\ \end{bmatrix}=?\qquad\mathbf{B} = 5\times\begin{bmatrix} 1\\ -4\\ 7\\ \end{bmatrix}=?$$The operation is done element-wise, e.g. $k\times\mathbf{A}=\mathbf{C}$ then $k\times a_{i,j}={k}c_{i,j}$.$$ 2 \times \b... | #Replace the <INSERT>
#Input A like this: A = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
#And B like this: B = [1, -4, 7]
#A = <INSERT>
#B = <INSERT>
A = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(3*A)
print ("\n")
B = np.array([1, -4, 7])
print (5*B)
print ("\n")
A = [[ 3, 6, 9], [12, 15,18], [21, 24, 27]]
B = [5, -20,... | 91b9508ec9099ee4d2c0a6309b0d69de
Yay, you succeeded!
88bddc0ee0eab409cee011770363d007
Yay, you succeeded!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
1.4 Dot product$$c_1=\begin{bmatrix} 11 \\ 2 \\ \end{bmatrix} \cdot \begin{bmatrix} 3 \\ 5 \\ \end{bmatrix} =?\qquadc_2=\begin{bmatrix} 1 \\ 2 \\ 3 \\ \end{bmatrix} \cdot \begin{bmatrix} 4 \\ 5 \\ 6 \\ \end{bmatrix} =?$$The operations are done element-wise, e.g. $\mathbf{v}\cdot\mathbf{w}=k$ then $\su... | #Replace the <INSERT>
#Input c1 and c2 like this: c = 1337
#c1 = <INSERT>
#c2 = <INSERT>
c1_1 = np.array([11,2])
c1_2 = np.array([3,5])
c1 = c1_1.dot(c1_2)
print (c1)
c1 = 43
c2_1 = np.array([1,2,3])
c2_2 = np.array([4,5,6])
c2 = c2_1.dot(c2_2)
print (c2)
c2 = 32
#Check if the dot product is correct
hashCheck(c1, '17... | 17e62166fc8586dfa4d1bc0e1742c08b
Yay, you succeeded!
6364d3f0f495b6ab9dcf8d3b5c6e0b01
Yay, you succeeded!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
1.5 Matrix multiplication $$ \mathbf{A}= \begin{bmatrix} 682 & 848 & 794 & 954 \\ 700 & 1223 & 1185 & 816 \\ 942 & 428 & 324 & 526 \\ 321 & 543 & 532 & 614 \\ \end{bmatrix} \qquad \mathbf{B}= \begin{bmatrix} 869 & 1269 & 1306 & 358 \\ 1008 & 836 & 690 & 366 \\ 973 & 619 & 407 & 1149 \\ 323 & 42 & 405 & 11... | # The convention is to import NumPy as the alias np
import numpy as np
A = [[ 682, 848, 794, 954],
[ 700, 1223, 1185, 816],
[ 942, 428, 324, 526],
[ 321, 543, 532, 614]]
B = [[ 869, 1269, 1306, 358],
[1008, 836, 690, 366],
[ 973, 619, 407, 1149],
[ 323, 42, 405, 117]]
... | f6b7b0500a6355e8e283f732ec28fa76
Yay, you succeeded!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
2. NumPy and Spark linear algebraA python library to utilize arrays is NumPy. The library is optimized to be fast and memory efficient, and provide abstractions corresponding to vectors, matrices and the operations done on these objects.Numpy's array class is called ndarray, it is also known by the alias array. This ... | #Replace the <INSERT>. You will use np.array()
A = np.array([[1, 2, 3],[4,5,6],[7,8,9]])
B = np.array([1,-4, 7])
C = A *5
D = 3 * B
print(A)
print(B)
print(C)
print(D)
#Check if the scalar matrix multiplication is correct
checkArray(C,[[5, 10, 15],[20, 25, 30],[35, 40, 45]], "the scalar multiplication")
checkArray(D,[3... | Yay, the scalar multiplication is correct!
Yay, the scalar multiplication is correct!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
2.2 Dot product and element-wise multiplicationBoth dot product and element-wise multiplication is supported by ndarrays.Element-wise multiplication is the standard between two arrays, of the same dimension, using the operator *. The dot product you can use either np.dot() or np.array.dot(). The dot product is a commu... | #Replace the <INSERT>
u = np.arange(0, 5)
v = np.arange(5, 10)
elementWise = np.multiply(u,v)
dotProduct = np.dot(u,v)
print(elementWise)
print(dotProduct)
#Check if the dot product and element wise is correct
checkArray(elementWise,[0,6,14,24,36], "the element wise multiplication")
check(dotProduct, 80, "the dot produ... | Yay, the element wise multiplication is correct!
Yay, the dot product is correct!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
2.3 Cosine similarityThe cosine similarity between two vectors is defined as the following equation:$$cosine\_similarity(u,v)=\cos\theta=\frac{\mathbf{u}\cdot\mathbf{v}}{\|u\|\|v\|}$$The norm of a vector $\|v\|$ can be calculated by using np.linalg.norm().Implement the following function that calculates the cosine sim... | def cosine_similarity(u,v):
dotProduct = np.dot(u,v)
normProduct = np.linalg.norm(u)*np.linalg.norm(v)
return dotProduct/normProduct
u = np.array([2503,2992,1042])
v = np.array([2217,2761,990])
w = np.array([0,1,1])
x = np.array([1,0,1])
uv = cosine_similarity(u,v)
wx = cosine_similarity(w,x)
print(uv)
... | Yay, cosine similarity between u and v is correct!
Yay, cosine similarity between w and x is correct!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
2.4 Matrix mathTo represent matrices, you can use the following class: np.matrix(). To create a matrix object either pass it a two-dimensional ndarray, or a list of lists to the function, or a string e.g. '1 2; 3 4'. Instead of element-wise multiplication, the operator *, does matrix multiplication.To transpose a matr... | #Replace the <INSERT>
#We generate a Vandermonde matrix
A = np.mat(np.vander([2,3], 5))
print(A)
#Calculate the transpose of A
At = np.transpose(A)
print(At)
#Calculate the multiplication of A and A^T
AAt = np.dot(A,At)
print(AAt)
#Calculate the inverse of AA^T
AAtInv = np.linalg.inv(AAt)
print(AAtInv)
#Calculate ... | Yay, the matrix math is correct!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
2.5 SlicesIt is possible to select subsets of one-dimensional arrays using slices. The basic syntax for slices is $\mathbf{v}$[i:j:k] where i is the starting index, j is the stopping index, and k is the step ($k\neq0$), the default value for k, if it is not specified, is 1. If no i is specified, the default value is 0... | #Replace the <INSERT>
v = np.arange(1, 9)
print(v)
#The first two elements of v
v1 = v[-2:]
#The last two elements of v
v3 = v[:-2]
#The middle four elements of v
v2 = v[3:7]
print(v1)
print(v2)
print(v3)
#Concatenating the three vectors to get the original array
u = np.concatenate((v1, v2, v3)) | [1 2 3 4 5 6 7 8]
[7 8]
[4 5 6 7]
[1 2 3 4 5 6]
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
2.6 StackingThere exist many functions provided by the NumPy library to manipulate existing arrays. We will try out two of these methods np.hstack() which takes two or more arrays and stack them horizontally to make a single array (column wise, equvivalent to np.concatenate), and np.vstack() which takes two or more ar... | #Replace the <INSERT>
u = np.arange(1, 11)
v = np.arange(11, 21)
#A 1x20 array
oneRow = np.hstack((u,v))
print(oneRow)
#A 2x10 array
twoRows = np.vstack((u,v))
print(twoRows)
#Check if the stacks are correct
checkArray(oneRow,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], "the hstack")
checkArray(twoRows,[[1,2... | Yay, the hstack is correct!
Yay, the vstack is correct!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
2.7 PySpark's DenseVectorIn PySpark there exists a DenseVector class within the module pyspark.mllib.linalg. The DenseVector stores the values as a NumPy array and delegates the calculations to this object. You can create a new DenseVector by using DenseVector() and passing it an NumPy array or a Python list.The Dense... | #To use the DenseVector first import it
from pyspark.mllib.linalg import DenseVector
#Replace the <INSERT>
#[0.1,0.2,...,1.0]
u = DenseVector((0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1))
print(u)
#[1.0,2.0,...,10.0]
v = DenseVector((1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0))
print(v)
#The dot product be... | Yay, the dense vectors is correct!
| Apache-2.0 | lab_exercises/solutions/lab3_1_NumpyAlgebra_Solution.ipynb | EPCCed/prace-spark-for-data-scientists |
Metadata Organization Imports | import pandas as pd
import numpy as np
import os.path
import glob
import pathlib
import functools
import time
import re
import gc
from nilearn.input_data import NiftiMasker
import nibabel as nib
from nilearn import image
from joblib import Parallel, delayed
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Load configs (all patterns/files/folderpaths) | import configurations
configs = configurations.Config('sub-xxx-resamp-intersected')
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Function to find all the regressor file paths | def timer(func):
"""Print the runtime of the decorated function"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f'Calling {func.__name__!r}')
startTime = time.perf_counter()
value = func(*args, **kwargs)
endTime = time.perf_counter()
runTime = endTime - ... | _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Function to find all the BOLD NII file paths | @timer
def find_paths(relDataFolder, subj, sess, func, patt):
paths = list(pathlib.Path(relDataFolder).glob(
os.path.join(subj, sess, func, patt)
)
)
return paths
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Find all the regressor file paths | regressor_paths = find_paths(relDataFolder=configs.dataDir,
subj='sub-*',
sess='ses-*',
func='func',
patt=configs.confoundsFilePattern)
regressor_paths
| Calling 'find_paths'
Finished 'find_paths' in 0.0247 secs
| Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Find all the BOLD NII file paths | nii_paths = find_paths(relDataFolder=configs.dataDir,
subj='sub-*',
sess='ses-*',
func='func',
patt=configs.maskedImagePattern)
nii_paths
| Calling 'find_paths'
Finished 'find_paths' in 0.0224 secs
| Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Read the participants.tsv file to find summaries of the subjects | participant_info_df = pd.read_csv(
configs.participantsSummaryFile,
sep='\t'
)
participant_info_df
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Get a mapping Dataframe of subject and which session is the sleep deprived one | @timer
def map_sleepdep(participant_info):
df = pd.DataFrame(participant_info.loc[:,['participant_id', 'Sl_cond']])
df.replace('sub-', '', inplace=True, regex=True)
return df.rename(columns={'participant_id':'subject', 'Sl_cond':'sleepdep_session'})
sleepdep_map = map_sleepdep(participant_info_df)
sleepdep... | Calling 'map_sleepdep'
Finished 'map_sleepdep' in 0.0026 secs
| Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Get Dataframe of subject, session, task, path | @timer
def get_bids_components(paths):
components_list = []
for i, path in enumerate(paths):
filename = path.stem
dirpath = path.parents[0]
matches = re.search(
'[a-z0-9]+\-([a-z0-9]+)_[a-z0-9]+\-([a-z0-9]+)_[a-z0-9]+\-([a-z0-9]+)',
filename
)
sub... | Calling 'get_bids_components'
Finished 'get_bids_components' in 0.0019 secs
| Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Combine logically sleepdep_map and components_df into 1 dataframe | sleep_bids_comb_df = bids_comp_df.merge(sleepdep_map, how='left')
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Response column 'sleepdep' imputed from 'session' 'sleepdep_session' | for i in range(len(sleep_bids_comb_df)):
if (int(sleep_bids_comb_df['session'].iloc[i]) ==
int(sleep_bids_comb_df['sleepdep_session'].iloc[i])):
sleep_bids_comb_df['sleepdep'].iloc[i] = 1
sleep_bids_comb_df
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Get confounds that can be used further clean up the signal or for prediction | def get_important_confounds(regressor_paths, important_reg_list, start, end):
regressors_df_list = []
for paths in regressor_paths:
regressors_all = pd.DataFrame(pd.read_csv(paths, sep="\t"))
regressors_selected = pd.DataFrame(regressors_all[important_reg_list].loc[start:end-1])
regresso... | _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Load the masker data file to prepare to apply to images | masker = NiftiMasker(mask_img=configs.maskDataFile, standardize=False)
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Helper to generate raw voxel df from a given path + masker and print shape for sanity | @timer
def gen_one_voxel_df(filepath, masker, start, end):
masked_array = masker.fit_transform(image.index_img(filepath, slice(start,end)))
reshaped_array = pd.DataFrame(np.reshape(
masked_array.ravel(), newshape=[1,-1]), dtype='float32')
print('> Shape of raw voxels for file ' +
'\"' + p... | _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Function to generate from masked image the raw voxel df from all images in folder | @timer
def get_voxels_df(metadata_df, masker, start, end):
rawvoxels_list = []
print() # Print to add a spacer for aesthetics
#below has been parallelized
for i in range(len(metadata_df)):
rawvoxels_list.append(gen_one_voxel_df(metadata_df['path'].iloc[i], masker, start, end))
print() #... | _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Garbage collect | gc.collect()
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Get/Generate raw voxels dataframe from all images with Y column label included | voxels_df = get_voxels_df(sleep_bids_comb_df, masker, configs.startSlice, configs.endSlice)
X = pd.concat([voxels_df, important_confounds_df], axis=1)
| Calling 'get_voxels_df'
Calling 'gen_one_voxel_df'
> Shape of raw voxels for file "sub-9001_ses-1_task-arrows_space-MNI152NLin2009cAsym_desc-preproc_bold_masked_(sub-9001-9072_resamp_intersected)_bold.nii" is:
1-D (UnMasked+Sliced): (1, 3634160)
2-D (UnMasked+Sliced): (40, 90854)
4-D (Raw header) : (87, 103... | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Separately get the Y label | Y = sleep_bids_comb_df['sleepdep']
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Save raw dataframe with Y column included to a file | X.to_pickle(configs.rawVoxelFile)
| _____no_output_____ | Apache-2.0 | 06-feature_extraction/Raw_Voxels_Extraction_with_Confounds.ipynb | DataKnightsAI/Sleep-Deprivation-Classification-using-MRI-Scans |
Useful modules in standard library--- **Programming Language**- Core Feature + builtin with language, + e.g input(), all(), for, if - Standard Library + comes preinstalled with language installer + e.g datetime, csv, Fraction- Thirdparty Library + created by community to solve specific problem + e.g ... | %ls
import hello
import hello2
%cat hello.py
hello.hello()
%ls hello_package/
%cat hello_package/__init__.py
%cat hello_package/diff.py
import hello_package
hello_package.diff.diff
hello_package.diff.diff()
hello_package.diff
import hello_package.diff
diff.diff()
hello_package.diff.diff()
import hello_package.diff as h... | Patch
| CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
Relative import | import sys
sys.path
from .hello import hello
__name__
sys.__name__ | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
Date and Time | import datetime
datetime
datetime.datetime
datetime.datetime.now()
datetime.datetime.today()
datetime.date.today()
now = datetime.datetime.now()
now
now.year
now.microsecond
now.second
help(now)
yesterday = datetime.datetime(2016, 8, 1, 8, 32, 29)
yesterday
now == yesterday
now > yesterday
now < yesterday
now - yesterd... | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
*timedelta is difference between two datetime* | delta = datetime.timedelta(days=3)
delta
yesterday + delta
now - delta
yesterday / now
yesterday // now
yesterday % now
yesterday * delta
help(datetime.timedelta)
help(datetime.datetime)
datetime.tzinfo('+530')
datetime.datetime(2016, 10, 20, tzinfo=datetime.tzinfo('+530'))
now.tzinfo
datetime.datetime.now()
datetime.d... | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
Files and Directories | f = open('hello.py')
open('non existing file')
f.read()
f.read()
f.seek(0)
f.read()
f.seek(0)
f.readlines()
f.seek(0)
f.readline()
f.readline()
f.readline()
f.close()
with open('hello.py') as _file:
for line in _file.readlines():
print(line) |
def hello():
print("hello")
| CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
**os** | import os
os.path.abspath('hello.py')
os.path.dirname(os.path.abspath('hello.py'))
os.path.join(os.path.dirname(os.path.abspath('hello.py')),
'another.py')
import glob
glob.glob('*.py')
glob.glob('*') | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
idwaker@gmail.com CSV files | import csv
with open('../../data/countries.csv') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
print(line)
with open('../../data/countries.csv') as csvfile:
reader = csv.DictReader(csvfile, fieldnames=['name', 'code'])
for line in reader:
print(line)
data = [
{'continent':... | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
Fractions | import fractions
fractions.Fraction(3, 5)
from fractions import Fraction
Fraction(2, 3)
Fraction(1, 3) + Fraction(1, 3)
(1/3) + (1/3)
10/21 | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
Named Tuples | from collections import namedtuple
Color = namedtuple('Color', ['red', 'green', 'blue'])
button_color = Color(231, 211, 201)
button_color.red
button_color[0]
'This picture has Red:{0.red} Green:{0.green} and Blue:{0.blue}'.format(button_color) | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
Builtin Methods - all()- any()- chr()- dict()- dir()- help()- id()- input()- list()- len()- map()- open()- print()- range()- reversed()- set()- sorted()- tuple()- zip() | all([1, 0, 4])
all([1, 3, 4])
any([1, 0])
any([0, 0])
chr(64)
chr(121)
ord('6')
ord('*')
dict(name='kathmandu', country='nepal')
dir('')
help(''.title)
id('')
id(1)
input("Enter your number")
list((1, 3, 5))
list('hello')
len('hello')
len([1, 4, 5])
# open()
# see: above
print("test")
range(0, 9)
range(0, 99, 3)
list(r... | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
**Lambda operations** | map(lambda x: x * 2, [1, 2, 3, 4])
list(map(lambda x: x * 2, [1, 2, 3, 4]))
lambda x: x + 4
def power2(x):
return x * 2
list(map(power2, [1, 2, 3, 4])) | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
*reduce is available in python2 only* | list(reduce(lambda x: x, [1, 4, 5, 6, 9])) | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
*for python 3* | from functools import reduce
reduce(lambda x, y: x + y, [1, 4, 5, 7, 8]) | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
*filter* | list(filter(lambda x: x < 3, [1, 3, 5, 2, 8])) | _____no_output_____ | CC-BY-4.0 | References/A.Standard Library.ipynb | pywaker/pybasics |
Preface雖然我年紀已經不小, 但是追朔 [FP (Functional programming) 的歷史](https://en.wikipedia.org/wiki/Functional_programmingHistory), 我也只能算年輕:> The lambda calculus, developed in the 1930s by Alonzo Church, is a formal system of computation built from function application. 既然歷史攸久, 因此一言難盡, 在這邊只會 吹吹皮毛, 希望至少可以 cover 下面的內容:* Basic FP ter... | #!pip install fpu
from fpu.flist import *
from functools import partial
from typing import Sequence
from collections.abc import Iterable | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
Basic FP terminology* FP Terminology - Imperative vs Declarative* FP Terminology - Closure* FP Terminology - CurryingFunctional programming has a [long history](https://en.wikipedia.org/wiki/Functional_programmingHistory). In a nutshell, **its a style of programming where you focus on transforming data through the use... | salaries = [
(True, 9000), # (Is female, salary)
(False, 12000),
(False, 6000),
(True, 14000),
]
def imperative_way(salaries):
'''Gets the sum of salaries of female and male.
Args:
salaries: List of salary. Each element is of tuple(is_female: bool, salary: int)
Returns:
... | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
Declarative底下是 [Declarative 語言的 wiki 說明](https://en.wikipedia.org/wiki/Declarative_programming):> A style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow. | def add(a, b):
return a + b
def salary_sum(is_female: bool):
'''Return calculator to sum up the salary based on female/male
Args:
is_female: True to return calculator to sum up salaries of female
False to return calculator to sum up salaries of male.
Returns:
... | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
FP Terminology - Closure ([back](sect1))A [**Closure**](https://en.wikipedia.org/wiki/Closure_(computer_programming)) is a function which **simply creates a scope that allows the function to access and manipulate the variables in enclosing scopes**. Normally, you will follow below steps to create a Closure in Python:*... | def contain_N(n):
def _inner(sequence: Sequence):
return n in sequence
return _inner
contain_5 = contain_N(5)
contain_10 = contain_N(10)
my_datas = [1, 2, 3, 4, 5]
print(f'my_data={my_datas} contains 5? {contain_5(my_datas)}')
print(f'my_data={my_datas} contains 10? {contain_10(my_datas)}') | my_data=[1, 2, 3, 4, 5] contains 5? True
my_data=[1, 2, 3, 4, 5] contains 10? False
| MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
上面的函數 `contain_N` 返回一個 closure. 該 closure 綁訂了變數 `n`. (contain_5 綁定的 `n` 為 5; contain_10 綁定的 `n` 為 10) FP Terminology - Currying ([back](sect1))底下是 wiki 上對 [**currying**](https://en.wikipedia.org/wiki/Curry_(programming_language)) 的說明:> Currying is like a kind of incremental binding of function arguments. It is the tec... | def sum_salary_by_sex(*args):
def _sum_salary_by_sex(is_female: bool, salaries: Sequence) -> int:
return sum(map(lambda t: t[1], filter(lambda t: t[0]==is_female, salaries)))
if len(args) == 1:
return partial(_sum_salary_by_sex, args[0])
return _sum_salary_by_sex(*args)
# Get femal... | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
我們透過 currying 的特性便可以得到新的函數 sum_salary_by_female 與 sum_salary_by_male. 是不是很方便? Lambda 用法 & 範例 ([back](sect0))[**Lambda**](https://docs.python.org/3/reference/expressions.htmllambda) 在 Python 是一個關鍵字用來定義 匿名函數. 底下是使用 lambda 匿名函數的注意事項:* It can only contain expressions and can’t include statements ([No Statesments](sect2_1)... | class Beef:
def __init__(self):
self.is_veg = False
def cook(self): return 'Hamburger'
class Potato:
def __init__(self):
self.is_veg = True
def cook(self): return 'French Fries'
class Chicken:
def __init__(self):
self.is_veg = False
... | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
map 範例[map](https://docs.python.org/3/library/functions.htmlmap) 需要你提供一個 function 與一個 iterable 物件 (延伸閱讀: [`The Iterator Protocol`](https://www.pythonmorsels.com/iterator-protocol/)), 接著 map 會將 iterable 的每個 element 丟掉你提供的 function 並收集 return 結果並回傳另一個 iterable 物件給你. 底下我們的範例:* **function**: `lambda food_ingredient: food_... | # map(function, iterable, ...):
# Return an iterator that applies function to every item of iterable, yielding the results.
map_iter = map(lambda food_ingredient: food_ingredient.cook(), food_ingredients)
isinstance(map_iter, Iterable) # map_iter is an iterable object.
list(map_iter) | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
filter 範例[filter](https://docs.python.org/3/library/functions.htmlfilter) 函數透過你提供的 function 來選擇傳入 iterable 物件中的 element (element 傳進 function 得到 True 的會被選擇). | # filter(function, iterable):
# Construct an iterator from those elements of iterable for which function returns true.
veg_iter = filter(lambda food_ingredient: food_ingredient.is_veg, food_ingredients)
isinstance(veg_iter, Iterable) # veg_iter is an iterable object.
# 只有 Proato 與 Corn 被選擇, 因為他們 `is_veg` == True
li... | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
reduce 範例reduce 函數的用法用講的不好說, 直接看範例: | from functools import reduce
# If initializer is not given, the first item of iterable object is returned.
f = lambda a, b: a+b
reduce(
f,
[1, 2, 3, 4, 5]
) | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
上面的執行過程可以看成:事實上你可以提供初始值, 例如: | reduce(
lambda a, b: a+b,
[1, 2, 3, 4, 5],
10,
) | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
更多有關這個函數的用法, 可以參考 [**Python's reduce(): From Functional to Pythonic Style**](https://realpython.com/python-reduce-function/) key functions 淺談Key functions in Python are higher-order functions that take a parameter `key` as a named argument.在 Python 許多的函數有提供參數 `key` 便是 lambda 使用的場合之一, 例如:* [sort()](https://docs.python.... | ids = ['id1', 'id2', 'id100', 'id30', 'id3', 'id22'] | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
你希望透過 `id` 的 `` 來進行排序 (ascending), 這時 [sorted](https://docs.python.org/3/library/functions.htmlsorted) 便可以派上用場:* **sorted(iterable, /, *, key=None, reverse=False)**: Return a new sorted list from the items in iterable. | sorted(
ids,
key=lambda id_str: int(id_str[2:]), # 比對時使用的值
) | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
懂一個 Key function 的用法, 其他就是依此類推了, 例如取出最大 `` 的 id 就會是: | max(
ids,
key=lambda id_str: int(id_str[2:])) | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
可以接受的 Lambda 使用時機 ([back](sect0))底下是 readability 文件對 Lambda 使用的建議:* [**2.10 Lambda Functions**](https://engdoc.corp.google.com/eng/doc/devguide/py/style/index.md?cl=headlambdas)> Okay to use them for one-liners. If the code inside the lambda function is longer than 60-80 chars, it's probably better to define it as a r... | # Map example
list(map(lambda x: x.capitalize(), ['cat', 'dog', 'cow']))
# Proposed way in using list comprehension
[w.capitalize() for w in ['cat', 'dog', 'cow']] | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
FilterThe built-in function [filter()](https://docs.python.org/3/library/functions.htmlfilter), another classic functional construct, can be converted into a list comprehension. It takes a [predicate](https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)) as a first argument and an iterable as a second argument... | # Filter example
even = lambda x: x%2 == 0
list(filter(even, range(11)))
# Proposed way in using list comprehension
[x for x in range(11) if x%2 == 0] | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
ReduceSince Python 3, [reduce()](https://docs.python.org/3/library/functools.htmlfunctools.reduce) has gone from a built-in function to a [**functools**](https://docs.python.org/3/library/functools.htmlfunctools.reduce) module function. As [map()](https://docs.python.org/3/library/functions.htmlmap) and [filter()](htt... | pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
sum(x[0] for x in pairs)
generator = (x[0] for x in pairs)
generator
iterator = pairs.__iter__()
iterator | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
有關 generator 與 iterator 的介紹與說明, 可以參考 "[**How to Use Generators and yield in Python**](https://realpython.com/introduction-to-python-generators/)" 與 "[**The Python `for` loop**](https://realpython.com/python-for-loop/the-python-for-loop)" Review 時會被打槍的用法 ([back](sect0))* g-long-lambda* unnecessary-lambda**The next sect... | data_set = [{'values':[1, 2, 3]}, {'values':[4, 5]}]
# Imperative
def min_max_imp(data_set):
"""Picks up the maximum of each element and calculate the minimum of them."""
max_list = []
for d in data_set:
max_list.append(max(d['values']))
return min(max_list)
# Max of [1, 2, 3] -> [3], ... | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
事實上這是兩個函數 min/max 串接的結果. 透過 FPU, 你可以改寫成: | # FP
from fpu.fp import *
from functools import reduce, partial
# compose2(f, g) = f(g())
min_max = compose2(
partial(reduce, min), # [3, 5] -> [3]
partial(map, lambda d: max(d['values']))) # [{'values':[1, 2, 3]}, {'values':[4, 5]}] -> [3, 5]
min_max(data_set) | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
Built-in filter/map/reduce in collection objectFPU 中的 collection 物件自帶 filter/map/reduce 函數. 考慮下面問題: | # 請找出在每個 element 都有出現過的元素 (character).
arr = ['abcdde', 'baccd', 'eeabg']
def gemstones_imp(arr):
# 1) Collect unique character of each element
set_list = []
for s in arr:
set_list.append(set(list(s)))
# 2) Keep searching overlapping characters among all set
uset = set_list[0]
f... | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
使用 FPU 改寫變成: | from fpu.flist import *
def gemstones_dec(arr):
rlist = fl(arr)
return ''.join(
rlist.map(
# 將每個 element 轉成 set
lambda e: set(list(e))
).reduce(
# 依序找出每個 set 共用的 character
lambda a, b: a & b
)
)
gemstones_dec(arr) | _____no_output_____ | MIT | lambda_function_101/fp_and_lambda_101.ipynb | johnklee/python_101_crash_courses |
Inheritance with the Gaussian ClassTo give another example of inheritance, take a look at the code in this Jupyter notebook. The Gaussian distribution code is refactored into a generic Distribution class and a Gaussian distribution class. Read through the code in this Jupyter notebook to see how the code works.The Dis... | class Distribution:
def __init__(self, mu=0, sigma=1):
""" Generic distribution class for calculating and
visualizing a probability distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the st... | _____no_output_____ | MIT | Assignment 7/inheritance_probability_distribution.ipynb | Sameer411/AWS-ML-Course-Assignments |
SWI - single layer Test case - strange behaviour output control packageWhen requesting both budget and head data via the OC package, the solution differs from when only the head is requested.This is set via the 'words' parameter in the OC package. | %matplotlib inline
import os
import sys
import numpy as np
import flopy.modflow as mf
import flopy.utils as fu
import matplotlib.pyplot as plt
os.chdir('C:\\Users\\Bas\\Google Drive\\USGS\\FloPy\\slope1D')
sys.path.append('C:\\Users\\Bas\\Google Drive\\USGS\\FloPy\\basScript') # location of gridObj
modelname = 'run1s... | _____no_output_____ | MIT | SWI1D/4cell1_woOcBgt.ipynb | bdestombe/SWItest |
Bank customers clustering project This dataset contains data on 5000 customers. The data include customer demographic information (age, income, etc.), the customer's relationship with the bank (mortgage, securities account, etc.), and the customer response to the last personal loan campaign (Personal Loan). Among thes... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from matplotlib import cm
df=pd.read_csv("Bank_Personal_Loan_Modelling.csv")
df.head() | _____no_output_____ | MIT | clustering_k_means_bank_loans.ipynb | Filipos27/KMeans_clustering |
Column informations: - ID - Customer id- Age - Customers age- Experience - Number of years of professional experience- Income - Annual income of the customer (x1000 USD)- ZIP Code - Home Address ZIP code- Family - Family size of the customer- CCAVG - Avg. spending on credit cards per month (x1000 USD)- Education - Educ... | #renaming columns
df.columns=['id', 'age', 'experience', 'income', 'zip_code', 'family', 'cc_avg',
'education', 'mortgage', 'personal_loan', 'securities_account',
'cd_account', 'online', 'credit_card']
df2=df.copy()
#Converting values
df2["income"]=df["income"]*1000
df2["cc_avg"]=df["cc_avg"]*1000
df2["m... | _____no_output_____ | MIT | clustering_k_means_bank_loans.ipynb | Filipos27/KMeans_clustering |
Dataset exploring | df2.shape
df2.info()
df2["income"].describe()
#visualize outliers with boxplot
plt.boxplot(df['income'])
# Upper outlier threshold Q3 + 1.5(IQR)
max_threshold=98000 + 1.5*(98000 - 39000)
max_threshold
# Removing outliers
df3=df2[df2.income<max_threshold]
# recalculate summary statistics
df3['income'].describe()
df3["c... | _____no_output_____ | MIT | clustering_k_means_bank_loans.ipynb | Filipos27/KMeans_clustering |
Data visualization | #Ploting scatterplot
title = 'Income by year experience '
plt.figure(figsize=(12,9))
sns.scatterplot(df4.experience,df4.income,hue=df4.experience).set_title(title)
plt.ioff()
#Bar plot of average income by education
df4.groupby('education')["income"].mean().plot.bar(color=[ 'red', 'cyan',"magenta"])
plt.show()
# Count... | _____no_output_____ | MIT | clustering_k_means_bank_loans.ipynb | Filipos27/KMeans_clustering |
Almost 700 hundres customers with mortgage between 0$ and 50 000$. Preparing features | features=df4[["age","experience","income","cc_avg"]] | _____no_output_____ | MIT | clustering_k_means_bank_loans.ipynb | Filipos27/KMeans_clustering |
Scaling features | # min-max scaling
from sklearn.preprocessing import MinMaxScaler, RobustScaler
scaler=MinMaxScaler()
data_scaled_array=scaler.fit_transform(features)
scaled=pd.DataFrame(data_scaled_array, columns=features.columns)
scaled.head() | _____no_output_____ | MIT | clustering_k_means_bank_loans.ipynb | Filipos27/KMeans_clustering |
KMeans cluster | from sklearn.cluster import KMeans, AffinityPropagation
import warnings
warnings.filterwarnings("ignore")
#finding sum of the squared distance between centroid and each member of the cluster
k_range = range(1,10)
sse =[]
for k in k_range:
km = KMeans(n_clusters=k)
km.fit(scaled)
sse.append(km.inertia_)
sse... | _____no_output_____ | MIT | clustering_k_means_bank_loans.ipynb | Filipos27/KMeans_clustering |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.