markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
<h2> Supply and demand </h2> Market clearing equilibrium price, $p^*$, satisfies... $$ D(p_t) = S(p_t^e). $$ Really this is also an equilibrium in beliefs because we also require that $p_t = p_t^e$!
interactive_supply_demand_plot = ipywidgets.interact(cobweb.supply_demand_plot, D=ipywidgets.fixed(quantity_demand), S=ipywidgets.fixed(quantity_supply), a=cobwe...
notebooks/cobweb-models.ipynb
davidrpugh/sfi-complexity-mooc
mit
<h2> Analyzing dynamics of the model via simulation... </h2> Model has no closed form solution (i.e., we can not solve for a function that describes $p_t^e$ as a function of time and model parameters). BUT, we can simulate equation 7 above to better understand the dynamics of the model... We can simulate our model an...
model = functools.partial(adaptive_expectations, inverse_demand, quantity_supply) interactive_time_series_plot = ipywidgets.interact(cobweb.time_series_plot, F=ipywidgets.fixed(model), X0=cobweb.initial_expected_price_...
notebooks/cobweb-models.ipynb
davidrpugh/sfi-complexity-mooc
mit
<h2> Forecast errors </h2> How do we measure forecast error? What does the distribution of forecast errors look like for different parameters? Could an agent learn to avoid chaos? Specifically, suppose an agent learned to tune the value of $w$ in order to minimize its mean forecast error. Would this eliminate chaotic...
interactive_forecast_error_plot = ipywidgets.interact(cobweb.forecast_error_plot, D_inverse=ipywidgets.fixed(inverse_demand), S=ipywidgets.fixed(quantity_supply), ...
notebooks/cobweb-models.ipynb
davidrpugh/sfi-complexity-mooc
mit
LU 分解 将一个矩阵分解为一个上三角和下三角矩阵的乘积
import numpy as np def LU(A): U = np.copy(A) m, n = A.shape L = np.eye(n) for k in range(n-1): for j in range(k+1,n): L[j,k] = U[j,k]/U[k,k] U[j,k:n] -= L[j,k] * U[k,k:n] return L, U A = np.array([[2,1,1,0],[4,3,3,1],[8,7,9,3],[6,7,9,8]]).astype(np.float) L, U = LU...
fastai_notes/LinearAlgebra/speech03.ipynb
AutuanLiu/Python
mit
The LU factorization is useful! Solving Ax = b becomes LUx = b: 1. find A = LU 2. solve Ly = b 3. solve Ux = y
v=np.array([1,2,3]) v v.shape v1=np.expand_dims(v, -1) v1 v1.shape v2 = v[np.newaxis] v2 v2.shape v3 = v[:, np.newaxis] v3 v3.shape
fastai_notes/LinearAlgebra/speech03.ipynb
AutuanLiu/Python
mit
广播运算 When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when they are equal, or one of them is 1 稀疏矩阵 There are the most common sparse storage formats: coordinate-wise (scipy calls COO) compressed sp...
import sklearn
fastai_notes/LinearAlgebra/speech03.ipynb
AutuanLiu/Python
mit
Load Data For this section, I'll load the data into a Pandas dataframe using urlopen from the urllib.request module. Instead of downloading a csv, I started implementing this method (inspired by this Python Tutorials) where I grab the data straight from the UCI Machine Learning Database using an http request.
# Loading data and cleaning dataset UCI_data_URL = 'https://archive.ics.uci.edu/ml/machine-learning-databases\ /breast-cancer-wisconsin/wdbc.data'
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
I do recommend on keeping a static file for your dataset as well. Next, I created a list with the appropriate names and set them as the data frame's column names, then I load them unto a pandas data frame
names = ['id_number', 'diagnosis', 'radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean', 'compactness_mean', 'concavity_mean','concave_points_mean', 'symmetry_mean', 'fractal_dimension_mean', 'radius_se', 'texture_se', 'perimeter_se', ...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Cleaning We do some minor cleanage like setting the id_number to be the data frame index, along with converting the diagnosis to the standard binary 1, 0 representation using the map() function.
# Setting 'id_number' as our index breast_cancer.set_index(['id_number'], inplace = True) # Converted to binary to help later on with models and plots breast_cancer['diagnosis'] = breast_cancer['diagnosis'].map({'M':1, 'B':0})
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Missing Values Given context of the data set, I know that there is no missing data, but I ran a for-loop that checks to see if there was any missing values through each column. Printing the column name and total missing values for that column, iteratively.
breast_cancer.isnull().sum()
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
This will be used for the random forest model, where the id_number won't be relevant.
# For later use in CART models names_index = names[2:]
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Let's preview the data set utilizing the head() function which will give the first 5 values of our data frame.
breast_cancer.head()
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Next, we'll give the dimensions of the data set; where the first value is the number of patients and the second value is the number of features. We print the data types of our data set this is important because this will often be an indicator of missing data, as well as giving us context to anymore data cleanage.
print("Here's the dimensions of our data frame:\n", breast_cancer.shape) print("Here's the data types of our columns:\n", breast_cancer.dtypes)
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Class Imbalance The distribution for diagnosis is important because it brings up the discussion of Class Imbalance within Machine learning and data mining applications. Class Imbalance refers to when a target class within a data set is outnumbered by the other target class (or classes). This can lead to misleading accu...
def print_target_perc(data_frame, col): """Function used to print class distribution for our data set""" try: # If the number of unique instances in column exceeds 20 print warning if data_frame[col].nunique() > 20: return print('Warning: there are {0} values in `{1}` column which ex...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Fortunately, this data set does not suffer from class imbalance. Next we will use a useful function that gives us standard descriptive statistics for each feature including mean, standard deviation, minimum value, maximum value, and range intervals.
breast_cancer.describe()
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
We can see through the maximum row that our data varies in distribution, this will be important when considering classification models. Standardization is an important requirement for many classification models that should be considered when implementing pre-processing. Some models (like neural networks) can perform p...
feature_space = breast_cancer.iloc[:, breast_cancer.columns != 'diagnosis'] feature_class = breast_cancer.iloc[:, breast_cancer.columns == 'diagnosis'] training_set, test_set, class_set, test_class_set = train_test_split(feature_space, feature_class,...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
NOTE: What I mean when I say pseudo-random is that we would want everyone who replicates this project to get the same results. So we use a random seed generator and set it equal to a number of our choosing, this will then make the results the same for anyone who uses this generator, awesome for reproducibility.
# Cleaning test sets to avoid future warning messages class_set = class_set.values.ravel() test_class_set = test_class_set.values.ravel()
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Fitting Random Forest Now we will create the model no parameter tuning aside from the random seed generator. What I mean when I say parameter tuning is different machine learning models utilize various parameters which have to be tuned by the person implementing the algorithm. Here I'll give a brief overview of the pa...
# Set the random state for reproducibility fit_rf = RandomForestClassifier(random_state=42)
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Hyperparameters Optimization Utilizing the GridSearchCV functionality, I create a dictionary with parameters I am looking to optimize to create the best model for our data. Setting the n_jobs to 3 tells the grid search to run 3 jobs in parallel reducing the time the function will take to compute the best parameters. I ...
np.random.seed(42) start = time.time() param_dist = {'max_depth': [2, 3, 4], 'bootstrap': [True, False], 'max_features': ['auto', 'sqrt', 'log2', None], 'criterion': ['gini', 'entropy']} cv_rf = GridSearchCV(fit_rf, cv = 10, param_grid=param_dist, ...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Once we are given the best parameter combination, we set the parameters to our model. Notice how we didn't utilize the bootstrap: True parameter, this will make sense in the following section.
# Set best parameters given by grid search fit_rf.set_params(criterion = 'gini', max_features = 'log2', max_depth = 3)
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Out of Bag Error Rate Another useful feature of Random Forest is the concept of Out of Bag Error Rate or OOB error rate. When creating the forest, typically only 2/3 of the data is used to train each tree, this gives us 1/3 of unseen data that we can then utilize in a way that is advantageos to our accuracy metrics wit...
fit_rf.set_params(warm_start=True, oob_score=True) min_estimators = 15 max_estimators = 1000 error_rate = {} for i in range(min_estimators, max_estimators + 1, 5): fit_rf.set_params(n_estimators=i) fit_rf.fit(training_set, class_set) oob_error = 1 - fit_rf.oob_score_ error_rate[i]...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
The OOB error rate starts to oscilate at around 400 trees, so I will go ahead and use my judgement to use 400 trees in my forest. Using the pandas series object I can easily find the OOB error rate for the estimator as follows:
print('OOB Error rate for 400 trees is: {0:.5f}'.format(oob_series[400]))
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Utilizing the OOB error rate that was created with the model gives us an unbiased error rate. This can be helpful when cross validating and/or hyperparameter optimization prove to be too computationally expensive, since oob can be calculated with the model estimation. For the sake of this tutorial I will go over the o...
fit_rf.set_params(n_estimators=400, bootstrap = True, warm_start=False, oob_score=False)
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Training Algorithm Next we train the algorithm utilizing the training and target class set we had made earlier.
fit_rf.fit(training_set, class_set)
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Variable Importance Once we have trained the model, we are able to assess this concept of variable importance. A downside to creating ensemble methods with Decision Trees is we lose the interpretability that a single tree gives. A single tree can outline for us important node splits along with variables that were impor...
def variable_importance(fit): """ Purpose ---------- Checks if model is fitted CART model then produces variable importance and respective indices in dictionary. Parameters ---------- * fit: Fitted model containing the attribute feature_importances_ Returns ---------- Dict...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
We can see here that our top 5 variables were area_worst, perimeter_worst, concave_points_worst, concave_points_mean, radius_worst. This can give us great insight for further analysis like feature engineering, although we won't go into this during this tutorial. This step can help give insight to the practitioner and ...
def variable_importance_plot(importance, indices, name_index): """ Purpose ---------- Prints bar chart detailing variable importance for CART model NOTE: feature_space list was created because the bar chart was transposed and index would be in incorrect order. Parameters ---------- *...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
The visual helps drive the point of variable importance, since you can clearly see the difference in importance of variables for the ensemble method. Certain cutoff points can be made to reduce the inclusion of features and can help in the accuracy of the model, since we'll be removing what is considered noise within o...
def cross_val_metrics(fit, training_set, class_set, estimator, print_results = True): """ Purpose ---------- Function helps automate cross validation processes while including option to print metrics or store in variable Parameters ---------- fit: Fitted model training_set: Data_fr...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Test Set Metrics Now we will be utilizing the test set that was created earlier to receive another metric for evaluation of our model. Recall the importance of data leakage and that we didn't touch the test set until now, after we had done hyperparamter optimization. We create a confusion matrix showcasing the followi...
predictions_rf = fit_rf.predict(test_set)
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Confusion Matrix Here we create a confusion matrix visual with seaborn and transposing the matrix when creating the heatmap.
def create_conf_mat(test_class_set, predictions): """Function returns confusion matrix comparing two arrays""" if (len(test_class_set.shape) != len(predictions.shape) == 1): return print('Arrays entered are not 1-D.\nPlease enter the correctly sized sets.') elif (test_class_set.shape != predictions....
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
As you can see we got a very similar error rate for our test set that we did for our OOB, which is a good sign for our model. ROC Curve Metrics Receiver Operating Characteristc Curve, calculates the False Positive Rates and True Positive Rates across different thresholds . We will now graph these calculations, and be...
# We grab the second array from the output which corresponds to # to the predicted probabilites of positive classes # Ordered wrt fit.classes_ in our case [0, 1] where 1 is our positive class predictions_prob = fit_rf.predict_proba(test_set)[:, 1] fpr2, tpr2, _ = roc_curve(test_class_set, pr...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Our model did exceptional with an AUC over .90, now we do a zoomed in view to showcase the closeness our ROC Curve is relative to the ideal ROC Curve.
plot_roc_curve(fpr2, tpr2, auc_rf, 'rf', xlim=(-0.01, 0.2), ylim=(0.85, 1.01))
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
Classification Report The classification report is available through sklearn.metrics, this report gives many important classification metrics including: + Precision: also the positive predictive value, is the number of correct predictions divided by the number of correct predictions plus false positives, so $tp / (tp +...
def print_class_report(predictions, alg_name): """ Purpose ---------- Function helps automate the report generated by the sklearn package. Useful for multiple model comparison Parameters: ---------- predictions: The predictions made by the algorithm used alg_name: String containing ...
notebooks/02_random_forest.ipynb
raviolli77/machineLearning_breastCancer_Python
mit
You can check the version of the library. Because pandas is fast-evolving library, you want to make sure that you have the up-to-date version of the library.
pd.__version__
m02-history/lab02.ipynb
yy/dviz-course
mit
You also need matplotlib, which is used by pandas to plot figures. The following is the most common convention to import matplotlib library.
import matplotlib.pyplot as plt
m02-history/lab02.ipynb
yy/dviz-course
mit
Let's check its version too.
import matplotlib matplotlib.__version__
m02-history/lab02.ipynb
yy/dviz-course
mit
Loading a CSV data file Using pandas, you can read tabular data files in many formats and through many protocols. Pandas supports not only flat files such as .csv, but also various other formats including clipboard, Excel, JSON, HTML, Feather, Parquet, SQL, Google BigQuery, and so on. Moreover, you can pass a local fil...
pump_df = pd.read_csv('https://raw.githubusercontent.com/yy/dviz-course/master/data/pumps.csv')
m02-history/lab02.ipynb
yy/dviz-course
mit
df stands for "Data Frame", which is a fundamental data object in Pandas. You can take a look at the dataset by looking at the first few lines.
pump_df.head()
m02-history/lab02.ipynb
yy/dviz-course
mit
Q1: can you print only the first three lines? Refer: http://pandas.pydata.org/pandas-docs/stable/index.html
# TODO: write your code here
m02-history/lab02.ipynb
yy/dviz-course
mit
You can also sample several rows randomly. If the data is sorted in some ways, sampling may give you a rather unbiased view of the dataset.
# Your code here
m02-history/lab02.ipynb
yy/dviz-course
mit
You can also figure out the number of rows in the dataset by running
len(pump_df)
m02-history/lab02.ipynb
yy/dviz-course
mit
Note that df.size does not give you the number of rows. It tells you the number of elements.
pump_df.size
m02-history/lab02.ipynb
yy/dviz-course
mit
You can also look into the shape of the dataset as well as what are the columns in the dataset.
pump_df.shape # 13 rows and 2 columns pump_df.columns
m02-history/lab02.ipynb
yy/dviz-course
mit
You can also check out basic descriptive statistics of the whole dataset by using describe() method.
pump_df.describe()
m02-history/lab02.ipynb
yy/dviz-course
mit
You can slice the data like a list
pump_df[:2] pump_df[-2:] pump_df[1:5]
m02-history/lab02.ipynb
yy/dviz-course
mit
or filter rows using some conditions.
pump_df[pump_df.X > 13]
m02-history/lab02.ipynb
yy/dviz-course
mit
Now let's load another CSV file that documents the cholera deaths. The URL is https://raw.githubusercontent.com/yy/dviz-course/master/data/deaths.csv Q2: load the death dataset and inspect it load this dataset as death_df. show the first 2 rows. show the total number of rows.
# TODO: Remove below dummy dataframe and write your code here. You probably want to create multiple cells. death_df = pd.DataFrame({"X": [2., 3.], "Y": [1., 2.]})
m02-history/lab02.ipynb
yy/dviz-course
mit
Some visualizations? Let's visualize them! Pandas actually provides a nice visualization interface that uses matplotlib under the hood. You can do many basic plots without learning matplotlib. So let's try.
death_df.plot()
m02-history/lab02.ipynb
yy/dviz-course
mit
This is not what we want! When asked to plot the data, it tries to figure out what we want based on the type of the data. However, that doesn't mean that it will successfully do so! Oh by the way, depending on your environment, you may not see any plot. If you don't see anything run the following command.
%matplotlib inline
m02-history/lab02.ipynb
yy/dviz-course
mit
The commands that start with % is called the magic commands, which are available in IPython and Jupyter. The purpose of this command is telling the IPython / Jupyter to show the plot right here instead of trying to use other external viewers. Anyway, this doesn't seem like the plot we want. Instead of putting each row...
death_df.plot(x='X', y='Y', kind='scatter', label='Deaths')
m02-history/lab02.ipynb
yy/dviz-course
mit
I think I want to reduce the size of the dots and change the color to black. But it is difficult to find how to do that! It is sometimes quite annoying to figure out how to change how the visualization looks, especially when we use matplotlib. Unlike some other advanced tools, matplotlib does not provide a very coheren...
death_df.plot(x='X', y='Y', kind='scatter', label='Deaths', s=2, c='black')
m02-history/lab02.ipynb
yy/dviz-course
mit
Can we visualize both deaths and pumps?
death_df.plot(x='X', y='Y', s=2, c='black', kind='scatter', label='Deaths') pump_df.plot(x='X', y='Y', kind='scatter', c='red', s=8, label='Pumps')
m02-history/lab02.ipynb
yy/dviz-course
mit
Oh well, this is not what we want! We want to overlay them to see them together, right? How can we do that? Before going into that, we probably want to understand some key components of matplotlib figures. Figure and Axes Why do we have two separate plots? The reason is that, by default, the plot method creates a new ...
ax = death_df.plot(x='X', y='Y', s=2, c='black', kind='scatter', label='Deaths') ax
m02-history/lab02.ipynb
yy/dviz-course
mit
This object contains all the information and objects in the plot we see. Whatever we want to do with this axes (e.g., changing x or y scale, overlaying other data, changing the color or size of symbols, etc.) can be done by accessing this object. Then you can pass this axes object to another plot to put both plots in ...
ax = death_df.plot(x='X', y='Y', s=2, c='black', alpha=0.5, kind='scatter', label='Deaths') pump_df.plot(x='X', y='Y', kind='scatter', c='red', s=8, label='Pumps', ax=ax)
m02-history/lab02.ipynb
yy/dviz-course
mit
Although simply invoking the plot() command is quick and easy when doing an exploratory data analysis, it is usually better to be formal about figure and axes objects. Here is the recommended way to create a plot. Call the subplots() method (see https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.subplots.html)...
import matplotlib.pyplot as plt fig, ax = plt.subplots() # your code here
m02-history/lab02.ipynb
yy/dviz-course
mit
Voronoi diagram Let's try the Voronoi diagram. You can use the scipy.spatial.Voronoi and scipy.spatial.voronoi_plot_2d from scipy, the scientific python library.
from scipy.spatial import Voronoi, voronoi_plot_2d
m02-history/lab02.ipynb
yy/dviz-course
mit
Take a look at the documentation of Voronoi and voronoi_plot_2d and Q3: produce a Voronoi diagram that shows the deaths, pumps, and voronoi cells
# you'll need this points = pump_df.values points # TODO: your code here
m02-history/lab02.ipynb
yy/dviz-course
mit
Saving the figure You can also save your figure into PDF, PNG, etc. If you run the following, the plot will not only be displayed here, but also be saved as foo.png.
import matplotlib.pyplot as plt plt.plot([1,2,3], [4,2,3]) plt.savefig('foo.png')
m02-history/lab02.ipynb
yy/dviz-course
mit
Q4: Save your Voronoi diagram. Make sure that your plot contains the scatterplot of deaths & pumps as well as the Voronoi cells
# TODO: your code here
m02-history/lab02.ipynb
yy/dviz-course
mit
Ok, that was a brief introduction to pandas and some simple visualizations. Now let's talk about web a little bit. HTML & CSS Basics HTML review Webpages are written in a standard markup language called HTML (HyperText Markup Language). The basic syntax of HTML consists of elements enclosed within &lt; and &gt; symbol...
%%html <!DOCTYPE html> <html> <head> <style> .para { font: 20px times-new-roman; color: green; padding: 10px; border: 1px solid black; } </style> </head> <body> <p class='para'>Hello World!</p> ...
m02-history/lab02.ipynb
yy/dviz-course
mit
练习:数据探索 首先我们对数据集进行一个粗略的探索,我们将看看每一个类别里会有多少被调查者?并且告诉我们这些里面多大比例是年收入大于50,000美元的。在下面的代码单元中,你将需要计算以下量: 总的记录数量,'n_records' 年收入大于50,000美元的人数,'n_greater_50k'. 年收入最多为50,000美元的人数 'n_at_most_50k'. 年收入大于50,000美元的人所占的比例, 'greater_percent'. 提示: 您可能需要查看上面的生成的表,以了解'income'条目的格式是什么样的。
# TODO:总的记录数 n_records = len(data['income']) # TODO:被调查者的收入大于$50,000的人数 n_greater_50k = len(data[data['income'] == '>50K']) # TODO:被调查者的收入最多为$50,000的人数 n_at_most_50k = len(data[data['income'] == '<=50K']) # TODO:被调查者收入大于$50,000所占的比例 greater_percent = (n_at_most_50k + 0.0) / n_records * 100 # 打印结果 print "Total numbe...
Udacity-ML/finding_donors-master/finding_donors.ipynb
quoniammm/happy-machine-learning
mit
练习:数据预处理 从上面的数据探索中的表中,我们可以看到有几个属性的每一条记录都是非数字的。通常情况下,学习算法期望输入是数字的,这要求非数字的特征(称为类别变量)被转换。转换类别变量的一种流行的方法是使用独热编码方案。独热编码为每一个非数字特征的每一个可能的类别创建一个_“虚拟”_变量。例如,假设someFeature有三个可能的取值A,B或者C,。我们将把这个特征编码成someFeature_A, someFeature_B和someFeature_C. | | 一些特征 | | 特征_A | 特征_B | 特征_C | | :-: | :-: | ...
# TODO:使用pandas.get_dummies()对'features_raw'数据进行独热编码 features = pd.get_dummies(features_raw) income_mapping = { '<=50K': 0, '>50K': 1 } # TODO:将'income_raw'编码成数字值 income = income_raw.map(income_mapping) # 打印经过独热编码之后的特征数量 encoded = list(features.columns) print "{} total features after one-hot encoding.".format...
Udacity-ML/finding_donors-master/finding_donors.ipynb
quoniammm/happy-machine-learning
mit
评价模型性能 在这一部分中,我们将尝试四种不同的算法,并确定哪一个能够最好地建模数据。这里面的三个将是你选择的监督学习器,而第四种算法被称为一个朴素的预测器。 评价方法和朴素的预测器 CharityML通过他们的研究人员知道被调查者的年收入大于\$50,000最有可能向他们捐款。因为这个原因CharityML对于准确预测谁能够获得\$50,000以上收入尤其有兴趣。这样看起来使用准确率作为评价模型的标准是合适的。另外,把没有收入大于\$50,000的人识别成年收入大于\$50,000对于CharityML来说是有害的,因为他想要找到的是有意愿捐款的用户。这样,我们期望的模型具有准确预测那些能够年收入大于\$50,000的能力比模型去...
# TODO: 计算准确率 accuracy = n_greater_50k / float(n_records) precision = accuracy recall = 1.0 # TODO: 使用上面的公式,并设置beta=0.5计算F-score fscore = (1 + 0.5**2) * precision * recall / ( 0.5 ** 2 * precision + recall) # 打印结果 print "Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]".format(accuracy, fscore)
Udacity-ML/finding_donors-master/finding_donors.ipynb
quoniammm/happy-machine-learning
mit
监督学习模型 下面的监督学习模型是现在在 scikit-learn 中你能够选择的模型 - 高斯朴素贝叶斯 (GaussianNB) - 决策树 - 集成方法 (Bagging, AdaBoost, Random Forest, Gradient Boosting) - K近邻 (KNeighbors) - 随机梯度下降分类器 (SGDC) - 支撑向量机 (SVM) - Logistic回归 问题 2 - 模型应用 列出从上面的监督学习模型中选择的三个适合我们这个问题的模型,你将在人口普查数据上测试这每个算法。对于你选择的每一个算法: 描述一个该模型在真实世界的一个应用场景。(你需要为此做点研究,并给出你的引用出处) 这个模型...
# TODO:从sklearn中导入两个评价指标 - fbeta_score和accuracy_score from sklearn.metrics import fbeta_score, accuracy_score def train_predict(learner, sample_size, X_train, y_train, X_test, y_test): ''' inputs: - learner: the learning algorithm to be trained and predicted on - sample_size: the size of samples...
Udacity-ML/finding_donors-master/finding_donors.ipynb
quoniammm/happy-machine-learning
mit
练习:初始模型的评估 在下面的代码单元中,您将需要实现以下功能: - 导入你在前面讨论的三个监督学习模型。 - 初始化三个模型并存储在'clf_A','clf_B'和'clf_C'中。 - 如果可能对每一个模型都设置一个random_state。 - 注意:这里先使用每一个模型的默认参数,在接下来的部分中你将需要对某一个模型的参数进行调整。 - 计算记录的数目等于1%,10%,和100%的训练数据,并将这些值存储在'samples'中 注意:取决于你选择的算法,下面实现的代码可能需要一些时间来运行!
# TODO:从sklearn中导入三个监督学习模型 from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier # TODO:初始化三个模型 clf_A = LogisticRegression(random_state=0) clf_B = SVC(kernel='linear', C=1.0, random_state=0) clf_C = DecisionTreeClassifier(criterion='entropy', ma...
Udacity-ML/finding_donors-master/finding_donors.ipynb
quoniammm/happy-machine-learning
mit
提高效果 在这最后一节中,您将从三个有监督的学习模型中选择最好的模型来使用学生数据。你将在整个训练集(X_train和y_train)上通过使用网格搜索优化至少调节一个参数以获得一个比没有调节之前更好的F-score。 问题 3 - 选择最佳的模型 基于你前面做的评价,用一到两段向CharityML解释这三个模型中哪一个对于判断被调查者的年收入大于\$50,000是最合适的。 提示:你的答案应该包括关于评价指标,预测/训练时间,以及该算法是否适合这里的数据的讨论。 回答: 问题 4 - 用通俗的话解释模型 用一到两段话,向CharityML用外行也听得懂的话来解释最终模型是如何工作的。你需要解释所选模型的主要特...
# TODO:导入'GridSearchCV', 'make_scorer'和其他一些需要的库 from sklearn.grid_search import GridSearchCV from sklearn.metrics import fbeta_score, make_scorer from sklearn.svm import SVC # TODO:初始化分类器 clf = SVC(random_state=1) # TODO:创建你希望调节的参数列表 parameters = [{ 'C': [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0], 'k...
Udacity-ML/finding_donors-master/finding_donors.ipynb
quoniammm/happy-machine-learning
mit
问题 5 - 最终模型评估 你的最优模型在训练数据上的准确率和F-score是多少?这些分数比没有优化的模型好还是差?你优化的结果相比于你在问题 1中得到的朴素预测器怎么样? 注意:请在下面的表格中填写你的结果,然后在答案框中提供讨论。 结果: | 评价指标 | 基准预测器 | 未优化的模型 | 优化的模型 | | :------------: | :-----------------: | :---------------: | :-------------: | | 准确率 | | | | | F-sco...
# TODO:导入一个有'feature_importances_'的监督学习模型 from sklearn.ensemble import RandomForestClassifier # TODO:在训练集上训练一个监督学习模型 model = RandomForestClassifier(n_estimators=10000, random_state=0) model.fit(X_train, y_train) # TODO: 提取特征重要性 importances = model.feature_importances_ # 绘图 vs.feature_plot(importances, X_train, y_train...
Udacity-ML/finding_donors-master/finding_donors.ipynb
quoniammm/happy-machine-learning
mit
问题 7 - 提取特征重要性 观察上面创建的展示五个用于预测被调查者年收入是否大于\$50,000最相关的特征的可视化图像。 这五个特征和你在问题 6中讨论的特征比较怎么样?如果说你的答案和这里的相近,那么这个可视化怎样佐证了你的想法?如果你的选择不相近,那么为什么你觉得这些特征更加相关? 回答: 特征选择 如果我们只是用可用特征的一个子集的话模型表现会怎么样?通过使用更少的特征来训练,在评价指标的角度来看我们的期望是训练和预测的时间会更少。从上面的可视化来看,我们可以看到前五个最重要的特征贡献了数据中所有特征中超过一半的重要性。这提示我们可以尝试去减小特征空间,并简化模型需要学习的信息。下面代码单元将使用你前面发现的优化模型,并只...
# 导入克隆模型的功能 from sklearn.base import clone # 减小特征空间 X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]] X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]] # 在前面的网格搜索的基础上训练一个“最好的”模型 clf = (clone(best_clf)).fit(X_train_reduced, y_train) # 做一个新的预测 redu...
Udacity-ML/finding_donors-master/finding_donors.ipynb
quoniammm/happy-machine-learning
mit
Handling Data over time There's a widespread trend in solar physics at the moment for correlation over actual science, so being able to handle data over time spans is a skill we all need to have. Python has ample support for this so lets have a look at what we can use. <section class="objectives panel panel-warning"> <...
from __future__ import print_function, division import numpy as np import sunpy from sunpy import lightcurve as lc import matplotlib.pyplot as plt %matplotlib inline import warnings warnings.filterwarnings('ignore')
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Now lets create some lightcurves
goes_lightcurve = lc.GOESLightCurve.create('2011-06-07 06:00','2011-06-07 08:00') hsi_lightcurve = lc.RHESSISummaryLightCurve.create('2011-06-07 06:00','2011-06-07 08:00')
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
In terms of LYRA, the server only allows you to download an entire day of data at a time. We can match this to the rest of the data by using the truncate function.
lyra_lightcurve_fullday = lc.LYRALightCurve.create('2011-06-07') lyra_lightcurve = lyra_lightcurve_fullday.truncate('2011-06-07 06:00','2011-06-07 08:00')
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Part of the advantage of using these inbuilt functions we can get a quicklook at our data using short commands:
fig = goes_lightcurve.peek() fig = lyra_lightcurve.peek()
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Accessing and using the data More custom plots can be made easily by accessing the data in the lightcurve functionality. Both the time information and the data are contained within the lightcurve.data code, which is a pandas dataframe. We can see what data is contained in the dataframe by finding which keys it contains...
print(lyra_lightcurve.data.keys()) print(lyra_lightcurve.meta)
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Notice that the meta data information is stored in something called OrderedDict <section class="objectives panel panel-info"> <div class="panel-heading"> <h2><span class="fa fa-thumb-tack"></span> On Dictionaries </h2> </div> <br/> We can create keyword-data pairs to form a dictionary (shock horror) of values. In this ...
plt.figure(1, figsize=(10,5)) plt.plot(lyra_lightcurve.data.index, lyra_lightcurve.data['CHANNEL3'], color='blue', label='Al filter') plt.plot(lyra_lightcurve.data.index, lyra_lightcurve.data['CHANNEL4'], color='red', label='Zr filter') plt.ylabel('Flux (Wm^2)') plt.show()
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Analysing Lightcurve data We can asses the degree to which the lyra curves correlate with each other:
cross_correlation = np.correlate(lyra_lightcurve.data['CHANNEL3'], lyra_lightcurve.data['CHANNEL4']) print(cross_correlation)
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Pandas In its own words Pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. Pandas has two forms of structures, 1D series and 2D dataframe. It also has its own functions associated with it. It is also a...
# max time argument taken from long and short GOES channels max_t_goes_long = goes_lightcurve.data['xrsb'].idxmax() max_t_goes_short = goes_lightcurve.data['xrsa'].idxmax() # max_time argument taken from channel 3 & 4 LYRA channe;s max_t_lyra_al = lyra_lightcurve.data['CHANNEL3'].idxmax() max_t_lyra_zr = lyra_lightcur...
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
So lets plot them on the graph
# create figure with raw curves plt.figure(1, figsize=(10,5)) plt.plot(lyra_lightcurve.data.index, lyra_lightcurve.data['CHANNEL3'], color='blue', label='Al filter') plt.plot(lyra_lightcurve.data.index, lyra_lightcurve.data['CHANNEL4'], color='red', label='Zr filter') plt.ylabel('Flux (Wm^2)') # max lines plt.axvline(...
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Reading in Tablulated data Now we have seen a little of what Pandas can do, lets read in some of our own data. In this case we are going to use data from Bennett et al. 2015, ApJ, a truly ground breaking work. Now the data we are reading in here is a structured Array.
data = np.genfromtxt('macrospicules.csv', skip_header=1, dtype=None, delimiter=',')
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Now, the above line imports information on some solar features over a sample time period. Specifically we have, maximum length, lifetime and time at which they occured. Now if we type data[0] what will happen?
data[0]
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
This is the first row of the array, containing the first element of our three properties. This particular example is a stuctured array, so the columns and rows can have properties and assign properties to the header. We can ask what the title of these columns is by using a dtype command:
data.dtype.names
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Unhelpful, so lets give them something more recognisable. We can use the docs to look up syntax and change the names of the column lables. <br/> <section class="objectives panel panel-success"> <div class="panel-heading"> <h2><span class="fa fa-pencil"></span> Google your troubles away </h2> </div> <br/> So the docs ar...
data.dtype.names = ('max_len', 'ltime', 'sample_time') data['max_len']
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
DataFrame Now a pandas DataFrame takes two arguments as a minimum, index and data. In this case the index will be our time within the sample and the maximum length and lifetime will be our data. So lets import pandas and use the dataframe: Pandas reads a dictionary when we want to input multiple data columns. Therefore...
import pandas as pd d = {'max_len': data['max_len'], 'ltime': data['ltime']} df = pd.DataFrame(data=d, index=data['sample_time']) print(df)
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Datetime Objects Notice that the time for the sample is in a strange format. It is a string containing the date in YYYY-MM-DD and time in HH-MM-SS-mmmmmm. These datetime objects have their own set of methods associated with them. Python appreciates that theses are built this way and can use them for the indexing easily...
import datetime print(datetime.datetime.now()) print(datetime.datetime.utcnow()) lunchtime = datetime.time(12,30) the_date = datetime.date(2005, 7, 14) dinner = datetime.datetime.combine(the_date, lunchtime) print("When is dinner? {}".format(dinner))
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Looking back at when we discussed the first element of data, and the format of the time index was awkward to use so lets do something about that.
print(df.index[0])
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
This is a string and python will just treat it as such. We need to use datetime to pick this string appart and change it into an oject we can use. To the Docs! So we use the formatting commands to match up with the string we have.
dt_obj = datetime.datetime.strptime(df.index[0], '%Y-%m-%dT%H:%M:%S.%f') print(dt_obj)
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Now the next logical step would be to make a for loop and iterate over the index and reassign it. HOWEVER there is almost always a better way. And Pandas has a to_dateime() method that we can feed the index:
df.index = pd.to_datetime(df.index) df
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Much easier. Note that the format of table has now changed and are pandas specific datetime objects, and looks like this:
df.index[0]
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
This means we can bin data according to time
l_bins = pd.groupby(df['max_len'], by=[df.index.year, df.index.month]) print(len(l_bins))
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Here we have used the groupby command to take the 'max_len' column, called as a dictionary key, and create bins for our data to sit in according to year and then month. The object l_bins has mean, max, std etc. attributes in the same way as the numpy arrays we handled the other day.
l_mean = l_bins.mean() l_std = l_bins.std()
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Lets not forget that l_bins is a list of bins so when we print out l_mean we get:
print(l_mean)
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Now we have all this data we can build a lovely bargraph with error bars and wonderful things like that. Remember, these pandas objects have functions associated with them, and one of them is a plot command.
fig, ax = plt.subplots() fig.autofmt_xdate() l_mean.plot(kind='bar', ax=ax, yerr=l_std, grid=False, legend=False) plt.show()
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
Note that the date on the x-axis is a little messed up we can fix with fig.autofmt_xdate() <section class="objectives panel panel-success"> <div class="panel-heading"> <h2><span class="fa fa-pencil"></span> How do the lifetimes change? </h2> </div> <br/> Now that we have the plot for the maximum length, now make a bar ...
import numpy as np ep_data = np.loadtxt('data/XO1_wl_transit_FLUX.txt') ep_dict = {'flux':ep_data[:, 1], 'err_flux':ep_data[:, 2]} ep_df = pd.DataFrame(data=ep_dict, index=ep_data[:,0]) ep_df.index = pd.to_datetime(ep_df.index) from astropy.time import Time t = Time(ep_data[:, 0], format='jd') UTC = t.d...
09-Time-Series-Data.ipynb
OpenAstronomy/workshop_sunpy_astropy
mit
2. Project 5 data set import This cell: * Creates a feature file name list of the car/non-car supplied files * Creates a label (y) vector * Randomly split the dataset into a train and a validation dataset
import glob import numpy as np from sklearn.model_selection import train_test_split cars = glob.glob("./dataset/vehicles/*/*.png") non_cars = glob.glob("./dataset/non-vehicles/*/*.png") # feature list X = [] # Append cars and non-cars image file paths to the feature list for car in cars: X.append(car) for non_c...
CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb
mlandry1/CarND
mit
3. Print a dataset summary This cell: * Prints a summary of the dataset
import matplotlib.image as mpimg %matplotlib inline if display_output == 1: # Load the 1rst image to get its size train_img = mpimg.imread(X_train[0]) # Dataset image shape image_shape = train_img.shape # Number of unique classes/labels there are in the dataset. n_classes = np.unique(y_train)...
CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb
mlandry1/CarND
mit
4. Exploratory visualization of the dataset This cell: * Defines the show_dataset_classes_histogram function * Defines the show_sample() function * Shows an hstogram distribution of the dataset classes * Shows a random sample of the dataset
import matplotlib.pyplot as plt import random def show_dataset_classes_histogram(labels_train, labels_valid): f, ax = plt.subplots(figsize=(5, 5)) # Generate histogram and bins hist_train, bins = np.histogram(labels_train, 2) hist_valid, bins = np.histogram(labels_valid, 2) # Bar width width...
CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb
mlandry1/CarND
mit
5. Get Model As we have seen in the "intro to convolutionnal network" lesson, a nice property of a convolutional filter is that is reuses the weights gwhile slidding through the image and feature maps, the weight number is thus not dependent on the input image size. Therefore, it is possible to train a full ConvNet to ...
from model import get_model from keras.layers import Flatten # Get the "base" ConvNet Model model = get_model() # Flat out the last layer for training model.add(Flatten()) # Print out model summary if display_output == 1: model.summary()
CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb
mlandry1/CarND
mit
6. Declare generators/load dataset This cell: * Declares a Keras generator (keras_generator()) to enable training on low end hardware * Declares a loader (loader()) to load all the dataset in memory (faster training, higher end hardware required)
from sklearn.utils import shuffle def keras_generator(features, labels, batch_size=32): num_features = len(features) # Loop forever so the generator never terminates while 1: # shuffles the input sample shuffle(features, labels) for offset in range(0, num_features, batch_size): ...
CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb
mlandry1/CarND
mit
7. Train Model and save the best weights This cell: * Defines a training visualization function (plot_train_result()) * Compiles the Keras model. The Adam optimizer is chosen and Mean Squared Error is used as a loss function * A Keras checkpointer is declared and configured to save the weights if loss becomes lower tha...
from keras.callbacks import ModelCheckpoint from keras.optimizers import Adam def plot_train_results(history_object): f, ax = plt.subplots(figsize=(10, 5)) ax.plot(history_object.history['acc']) ax.plot(history_object.history['val_acc']) ax.set_ylabel('Model accuracy') ax.set_xlabel('Epoch') a...
CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb
mlandry1/CarND
mit
Testing the classifier 8. Load weights This cell: * Loads the best weight saved by the Keras checkpointer (code cell #7 above).
# Load the weight model.load_weights('./weights/best-weights.hdf5') print("Weights loaded!")
CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb
mlandry1/CarND
mit
9. Test the classifier on random images This cell: * Picks random images from the dataset * Infers the label using the trained model * Measures the inference time * Shows a figure of the images and predicted label, title color changes according to correctness of the inference (green = correct, red = incorrect).
if display_output == 1: import matplotlib.pyplot as plt %matplotlib inline import time import numpy as np sample_num = 12 col_num = 4 row_num = int(sample_num/col_num) # Create training sample + histogram plot f, axarr = plt.subplots(row_num, col_num, figsize=(col_num...
CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb
mlandry1/CarND
mit
3. Create a Radical Pilot Session
session = rp.Session() print "Session id %s"%session.uid c = rp.Context('ssh') c.user_id = "" session.add_context(c)
02_pilot/Radical_Pilot_YARN_Stampede.ipynb
radical-cybertools/supercomputing2015-tutorial
apache-2.0