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
Forward propagation for the basic Recurrent Neural Network RNN cell
# GRADED FUNCTION: rnn_cell_forward def rnn_cell_forward(xt, a_prev, parameters): # Retrieve parameters from "parameters" Wax = parameters["Wax"] Waa = parameters["Waa"] Wya = parameters["Wya"] ba = parameters["ba"] by = parameters["by"] # compute next activation state using the formu...
a_next[4] = [ 0.59584544 0.18141802 0.61311866 0.99808218 0.85016201 0.99980978 -0.18887155 0.99815551 0.6531151 0.82872037] a_next.shape = (5, 10) yt_pred[1] = [ 0.9888161 0.01682021 0.21140899 0.36817467 0.98988387 0.88945212 0.36920224 0.9966312 0.9982559 0.17746526] yt_pred.shape = (2,...
MIT
.ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb
aadimangla/Custom-Trained-Recurrent-Neural-Network
1.2 - RNN forward pass
# GRADED FUNCTION: rnn_forward def rnn_forward(x, a0, parameters): # Initialize "caches" which will contain the list of all caches caches = [] # Retrieve dimensions from shapes of x and parameters["Wya"] n_x, m, T_x = x.shape n_y, n_a = parameters["Wya"].shape # initialize "a"...
a[4][1] = [-0.99999375 0.77911235 -0.99861469 -0.99833267] a.shape = (5, 10, 4) y_pred[1][3] = [ 0.79560373 0.86224861 0.11118257 0.81515947] y_pred.shape = (2, 10, 4) caches[1][1][3] = [-1.1425182 -0.34934272 -0.20889423 0.58662319] len(caches) = 2
MIT
.ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb
aadimangla/Custom-Trained-Recurrent-Neural-Network
Long Short-Term Memory (LSTM) network Overview of gates and states - Forget gate $\mathbf{\Gamma}_{f}$* Let's assume we are reading words in a piece of text, and plan to use an LSTM to keep track of grammatical structures, such as whether the subject is singular ("puppy") or plural ("puppies"). * If the subject chang...
# GRADED FUNCTION: lstm_cell_forward def lstm_cell_forward(xt, a_prev, c_prev, parameters): # Retrieve parameters from "parameters" Wf = parameters["Wf"] # forget gate weight bf = parameters["bf"] Wi = parameters["Wi"] # update gate weight (notice the variable name) bi = parameters["bi"] # (notice ...
a_next[4] = [-0.66408471 0.0036921 0.02088357 0.22834167 -0.85575339 0.00138482 0.76566531 0.34631421 -0.00215674 0.43827275] a_next.shape = (5, 10) c_next[2] = [ 0.63267805 1.00570849 0.35504474 0.20690913 -1.64566718 0.11832942 0.76449811 -0.0981561 -0.74348425 -0.26810932] c_next.shape = (5, 10...
MIT
.ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb
aadimangla/Custom-Trained-Recurrent-Neural-Network
Forward pass for LSTM
# GRADED FUNCTION: lstm_forward def lstm_forward(x, a0, parameters): # Initialize "caches", which will track the list of all the caches caches = [] # Retrieve dimensions from shapes of x and Wy (≈2 lines) n_x, m, T_x = x.shape n_y, n_a = parameters["Wy"].shape # initialize "a", "...
a[4][3][6] = 0.172117767533 a.shape = (5, 10, 7) y[1][4][3] = 0.95087346185 y.shape = (2, 10, 7) caches[1][1][1] = [ 0.82797464 0.23009474 0.76201118 -0.22232814 -0.20075807 0.18656139 0.41005165] c[1][2][1] -0.855544916718 len(caches) = 2
MIT
.ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb
aadimangla/Custom-Trained-Recurrent-Neural-Network
**Expected Output**:```Pythona[4][3][6] = 0.172117767533a.shape = (5, 10, 7)y[1][4][3] = 0.95087346185y.shape = (2, 10, 7)caches[1][1][1] = [ 0.82797464 0.23009474 0.76201118 -0.22232814 -0.20075807 0.18656139 0.41005165]c[1][2][1] -0.855544916718len(caches) = 2``` Backpropagation in recurrent neural networks ...
def rnn_cell_backward(da_next, cache): # Retrieve values from cache (a_next, a_prev, xt, parameters) = cache # Retrieve values from parameters Wax = parameters["Wax"] Waa = parameters["Waa"] Wya = parameters["Wya"] ba = parameters["ba"] by = parameters["by"] # compute the gr...
gradients["dxt"][1][2] = -1.3872130506 gradients["dxt"].shape = (3, 10) gradients["da_prev"][2][3] = -0.152399493774 gradients["da_prev"].shape = (5, 10) gradients["dWax"][3][1] = 0.410772824935 gradients["dWax"].shape = (5, 3) gradients["dWaa"][1][2] = 1.15034506685 gradients["dWaa"].shape = (5, 5) gradients["dba"][4]...
MIT
.ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb
aadimangla/Custom-Trained-Recurrent-Neural-Network
**Expected Output**: **gradients["dxt"][1][2]** = -1.3872130506 **gradients["dxt"].shape** = (3, 10) **gradients["da_prev"][2][3]** = -0.1523...
def rnn_backward(da, caches): # Retrieve values from the first cache (t=1) of caches (≈2 lines) (caches, x) = caches (a1, a0, x1, parameters) = caches[0] # Retrieve dimensions from da's and x1's shapes (≈2 lines) n_a, m, T_x = da.shape n_x, m = x1.shape # initialize ...
gradients["dx"][1][2] = [-2.07101689 -0.59255627 0.02466855 0.01483317] gradients["dx"].shape = (3, 10, 4) gradients["da0"][2][3] = -0.314942375127 gradients["da0"].shape = (5, 10) gradients["dWax"][3][1] = 11.2641044965 gradients["dWax"].shape = (5, 3) gradients["dWaa"][1][2] = 2.30333312658 gradients["dWaa"].shape ...
MIT
.ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb
aadimangla/Custom-Trained-Recurrent-Neural-Network
**Expected Output**: **gradients["dx"][1][2]** = [-2.07101689 -0.59255627 0.02466855 0.01483317] **gradients["dx"].shape** = (3, 10, 4) **gradients["da0"][2][3]** = ...
def lstm_cell_backward(da_next, dc_next, cache): # Retrieve information from "cache" (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters) = cache # Retrieve dimensions from xt's and a_next's shape (≈2 lines) n_x, m = xt.shape n_a, m = a_next.shape # Compute gates related d...
gradients["dxt"][1][2] = 3.23055911511 gradients["dxt"].shape = (3, 10) gradients["da_prev"][2][3] = -0.0639621419711 gradients["da_prev"].shape = (5, 10) gradients["dc_prev"][2][3] = 0.797522038797 gradients["dc_prev"].shape = (5, 10) gradients["dWf"][3][1] = -0.147954838164 gradients["dWf"].shape = (5, 8) gradients["...
MIT
.ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb
aadimangla/Custom-Trained-Recurrent-Neural-Network
**Expected Output**: **gradients["dxt"][1][2]** = 3.23055911511 **gradients["dxt"].shape** = (3, 10) **gradients["da_prev"][2][3]** = -0.0639...
def lstm_backward(da, caches): # Retrieve values from the first cache (t=1) of caches. (caches, x) = caches (a1, c1, a0, c0, f1, i1, cc1, o1, x1, parameters) = caches[0] # Retrieve dimensions from da's and x1's shapes (≈2 lines) n_a, m, T_x = da.shape n_x, m = x1.shape # initial...
gradients["dx"][1][2] = [ 0.00433841 0.01182645 -0.01648453 0.20649992] gradients["dx"].shape = (3, 10, 4) gradients["da0"][2][3] = 0.176564564406 gradients["da0"].shape = (5, 10) gradients["dWf"][3][1] = -0.0698198561274 gradients["dWf"].shape = (5, 8) gradients["dWi"][1][2] = 0.102371820249 gradients["dWi"].shape =...
MIT
.ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb
aadimangla/Custom-Trained-Recurrent-Neural-Network
Based on http://scikit-learn.org/stable/auto_examples/text/document_clustering.html
from sklearn.datasets import fetch_20newsgroups from sklearn import metrics from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.sv...
Linear Support Vector classifier precision recall f1-score support comp.graphics 0.91 0.97 0.94 389 sci.med 0.95 0.90 0.92 396 soc.religion.christian 0.96 0.97 0.96 398 talk.politics.misc 0...
MIT
Document classify - KMeans.ipynb
heolin123/text_analysis
pandasはpdという名前でインポートされることがほとんどです
import pandas as pd
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
本書第1章で使うデータを読み込みましょう read_csv関数を使うことでcsvをpandasのDataFrameという形式で読み込むことができます
df = pd.read_csv('../data/ch1_sport_test.csv') df
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
抽出 今回はDataFrameが10行と比較的小規模ですが、数百行・数千行のDataFrameを扱うことも珍しくありません そのようなDataFrameの概観を知るためにDataFrameのheadメソッドがよく使われます headメソッドはDataFrameの先頭の数行を抽出するメソッドです ここでは3行抽出してみましょう
df.head(3)
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
何も指定しないと5行抽出されます
df.head()
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
同様にtailメソッドはDataFrameの末尾を抽出します
df.tail()
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
スライスで抽出することもできます
df[2:5]
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
列は列名によって抽出できます
df['握力']
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
複数列を同時に指定することもできます
df[['学年', '点数']]
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
行と列を同時に指定して抽出したいときはlocメソッドが便利です たとえば1行目の学年は次のように抽出できます
df.loc[1, '学年']
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
スライスによる指定も可能です
df.loc[1:3, '握力']
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
条件に合致する行を抽出したい場合は次のように書きます ここでは握力が30より下の行を抽出しています
df[df['握力'] < 30]
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
データの概要 データの大きさはshapeでわかります
df.shape
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
列名はcolumnsです
df.columns df.index df.describe()
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
データの追加 dfにデータを追加してみましょう まずは列の追加です
df['腕立て伏せ'] = [15, 12, 10, 4, 20, 24, 9, 11, 11, 17] df
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
次は行を追加してみます
new_row = pd.Series([11, 3, 42.4, 30, 15, 11, 12], index=df.columns, name=10) new_row df.append(new_row)
_____no_output_____
BSD-3-Clause
tutorial/pandas.ipynb
tsahara/python_stat
Data description: I'm going to solve the International Airline Passengers prediction problem. This is a problem where given a year and a month, the task is to predict the number of international airline passengers in units of 1,000. The data ranges from January 1949 to December 1960 or 12 years, with 144 observations....
import keras import sklearn import tensorflow as tf import numpy as np from scipy import stats import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn import metrics from sklearn import preprocessing import random as rn import math %matplotlib inline from keras import backend as K sessio...
_____no_output_____
MIT
Deep Learning with Keras_TensorFlow/Airlline Passengers prediction (with LSTM RNN in Keras-TensorFlow).ipynb
RooHashemi/Data-Science-Projects-with-Python-Spark-Keras_TensorFlow-AWS
Chemistry for Technology Students at GGC Measurement Uncertainty, Accuracy, and Precision [Textbook: Chapter 1, section 5](https://openstax.org/books/chemistry-2e/pages/1-5-measurement-uncertainty-accuracy-and-precision) Measurement Uncertainty Most measurements are very much _not_ like that. You can easily ima...
d = 1.00 # inches pi = 3.1415926 c = pi*d print ("The circumference of the circle is {:.2f} inches.".format(c))
The circumference of the circle is 3.14 inches.
MIT
chapters/ch01/sections/chem4tech01_05.ipynb
pscoppock/chem4tech
Inject activity patterns without plasticity
np.random.seed(7) input_patterns=S[np.nonzero(U[:,13])[0],:] input_patterns=zscore(input_patterns,axis=1) v_lst=[] w=np.random.normal(loc=0,size=(656,)) v_lst=[np.dot(w,input_patterns[:,0])] for j in range(1,30560): v_lst.append(np.dot(w,input_patterns[:,j])) plt.plot(zscore(v_lst[:100])) plt.show() plt.plot(i...
_____no_output_____
MIT
EnsemblePursuitSynapseExploration.ipynb
mariakesa/DayanAbbottExplorations
Inject patterns with plasticity
#Using Euler's method to calculate the weight increments h=0.001 input_patterns=S[np.nonzero(U[:,13])[0],:] input_patterns=zscore(input_patterns,axis=1) print(input_patterns.shape) v_lst=[] w_lst=[] w=np.random.normal(loc=0,size=(656,)) v_lst=[np.dot(w,input_patterns[:,1])] for j in range(0,1000): v_lst.append(np.d...
_____no_output_____
MIT
EnsemblePursuitSynapseExploration.ipynb
mariakesa/DayanAbbottExplorations
Comparing soundings from NCEP Reanalysis and various models We are going to plot the global, annual mean sounding (vertical temperature profile) from observations.Read in the necessary NCEP reanalysis data from the online server.The catalog is here:
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import xarray as xr ncep_url = "https://psl.noaa.gov/thredds/dodsC/Datasets/ncep.reanalysis.derived/" ncep_air = xr.open_dataset( ncep_url + "pressure/air.mon.1981-2010.ltm.nc", decode_times=False) level = ncep_air.level lat = ncep_air.lat
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Take global averages and time averages.
Tzon = ncep_air.air.mean(dim=('lon','time')) weight = np.cos(np.deg2rad(lat)) / np.cos(np.deg2rad(lat)).mean(dim='lat') Tglobal = (Tzon * weight).mean(dim='lat')
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Here is code to make a nicely labeled sounding plot.
fig = plt.figure( figsize=(10,8) ) ax = fig.add_subplot(111) ax.plot( Tglobal + 273.15, np.log(level/1000)) ax.invert_yaxis() ax.set_xlabel('Temperature (K)', fontsize=16) ax.set_ylabel('Pressure (hPa)', fontsize=16 ) ax.set_yticks( np.log(level/1000) ) ax.set_yticklabels( level.values ) ax.set_title('Global, annual me...
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Now compute the Radiative Equilibrium solution for the grey-gas column model
import climlab from climlab import constants as const col = climlab.GreyRadiationModel() print(col) col.subprocess['LW'].diagnostics col.integrate_years(1) print("Surface temperature is " + str(col.Ts) + " K.") print("Net energy in to the column is " + str(col.ASR - col.OLR) + " W / m2.")
Integrating for 365 steps, 365.2422 days, or 1 years. Total elapsed time is 0.9993368783782377 years. Surface temperature is [287.84577808] K. Net energy in to the column is [0.00165505] W / m2.
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Plot the radiative equilibrium temperature on the same plot with NCEP reanalysis
pcol = col.lev fig = plt.figure( figsize=(10,8) ) ax = fig.add_subplot(111) ax.plot( Tglobal + 273.15, np.log(level/1000), 'b-', col.Tatm, np.log( pcol/const.ps ), 'r-' ) ax.plot( col.Ts, 0, 'ro', markersize=20 ) ax.invert_yaxis() ax.set_xlabel('Temperature (K)', fontsize=16) ax.set_ylabel('Pressure (hPa)', fontsize=1...
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Now use convective adjustment to compute a Radiative-Convective Equilibrium temperature profile
dalr_col = climlab.RadiativeConvectiveModel(adj_lapse_rate='DALR') print(dalr_col) dalr_col.integrate_years(2.) print("After " + str(dalr_col.time['days_elapsed']) + " days of integration:") print("Surface temperature is " + str(dalr_col.Ts) + " K.") print("Net energy in to the column is " + str(dalr_col.ASR - dalr_co...
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Now plot this "Radiative-Convective Equilibrium" on the same graph:
fig = plt.figure( figsize=(10,8) ) ax = fig.add_subplot(111) ax.plot( Tglobal + 273.15, np.log(level/1000), 'b-', col.Tatm, np.log( pcol/const.ps ), 'r-' ) ax.plot( col.Ts, 0, 'ro', markersize=16 ) ax.plot( dalr_col.Tatm, np.log( pcol / const.ps ), 'k-' ) ax.plot( dalr_col.Ts, 0, 'ko', markersize=16 ) ax.invert_yaxis()...
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
The convective adjustment gets rid of the unphysical temperature difference between the surface and the overlying air.But now the surface is colder! Convection acts to move heat upward, away from the surface.Also, we note that the observed lapse rate (blue) is always shallower than $\Gamma_d$ (temperatures decrease mor...
rce_col = climlab.RadiativeConvectiveModel(adj_lapse_rate=6, abs_coeff=1.7E-4) print(rce_col) rce_col.integrate_years(2.) print("After " + str(rce_col.time['days_elapsed']) + " days of integration:") print("Surface temperature is " + str(rce_col.Ts) + " K.") print("Net energy in to the column is " + str(rce_col.ASR - ...
Integrating for 730 steps, 730.4844 days, or 2.0 years. Total elapsed time is 1.9986737567564754 years. After 730.0 days of integration: Surface temperature is [287.9049635] K. Net energy in to the column is [2.14745046e-06] W / m2.
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Now add this new temperature profile to the graph:
fig = plt.figure( figsize=(10,8) ) ax = fig.add_subplot(111) ax.plot( Tglobal + 273.15, np.log(level/1000), 'b-', col.Tatm, np.log( pcol/const.ps ), 'r-' ) ax.plot( col.Ts, 0, 'ro', markersize=16 ) ax.plot( dalr_col.Tatm, np.log( pcol / const.ps ), 'k-' ) ax.plot( dalr_col.Ts, 0, 'ko', markersize=16 ) ax.plot( rce_col....
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Adding stratospheric ozone Our model has no equivalent of the stratosphere, where temperature increases with height. That's because our model has been completely transparent to shortwave radiation up until now.We can load some climatogical ozone data:
# Put in some ozone import xarray as xr ozonepath = "http://thredds.atmos.albany.edu:8080/thredds/dodsC/CLIMLAB/ozone/apeozone_cam3_5_54.nc" ozone = xr.open_dataset(ozonepath) ozone
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Take the global average of the ozone climatology, and plot it as a function of pressure (or height)
# Taking annual, zonal, and global averages of the ozone data O3_zon = ozone.OZONE.mean(dim=("time","lon")) weight_ozone = np.cos(np.deg2rad(ozone.lat)) / np.cos(np.deg2rad(ozone.lat)).mean(dim='lat') O3_global = (O3_zon * weight_ozone).mean(dim='lat') O3_global.shape ax = plt.figure(figsize=(10,8)).add_subplot(111) a...
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
This shows that most of the ozone is indeed in the stratosphere, and peaks near the top of the stratosphere.Now create a new column model object **on the same pressure levels as the ozone data**. We are also going set an adjusted lapse rate of 6 K / km, and tune the longwave absorption
oz_col = climlab.RadiativeConvectiveModel(lev = ozone.lev, abs_coeff=1.82E-4, adj_lapse_rate=6, albedo=0.315)
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Now we will do something new: let the column absorb some shortwave radiation. We will assume that the shortwave absorptivity is proportional to the ozone concentration we plotted above. We need to weight the absorptivity by the pressure (mass) of each layer.
ozonefactor = 75 dp = oz_col.Tatm.domain.axes['lev'].delta sw_abs = O3_global * dp * ozonefactor oz_col.subprocess.SW.absorptivity = sw_abs oz_col.compute() oz_col.compute() print(oz_col.SW_absorbed_atm)
[0.01521244 0.00239547 0.00294491 0.00359022 0.00437158 0.0053308 0.006518 0.00801322 0.00983974 0.0122112 0.01517438 0.01896033 0.02378877 0.03006126 0.03813404 0.04839947 0.06121356 0.07689825 0.0956929 0.11774895 0.14311224 0.17200325 0.20535155 0.24420577 0.28873387 0.33942617 0.39635885 0.45785715 0.515456...
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
Now run it out to Radiative-Convective Equilibrium, and plot
oz_col.integrate_years(2.) print("After " + str(oz_col.time['days_elapsed']) + " days of integration:") print("Surface temperature is " + str(oz_col.Ts) + " K.") print("Net energy in to the column is " + str(oz_col.ASR - oz_col.OLR) + " W / m2.") pozcol = oz_col.lev fig = plt.figure( figsize=(10,8) ) ax = fig.add_sub...
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
And we finally have something that looks looks like the tropopause, with temperature increasing above at about the correct rate. Though the tropopause temperature is off by 15 degrees or so. Greenhouse warming in the RCE model with ozone
oz_col2 = climlab.process_like( oz_col ) oz_col2.subprocess['LW'].absorptivity *= 1.2 oz_col2.integrate_years(2.) fig = plt.figure( figsize=(10,8) ) ax = fig.add_subplot(111) ax.plot( Tglobal + const.tempCtoK, np.log(level/const.ps), 'b-' ) ax.plot( oz_col.Tatm, np.log( pozcol / const.ps ), 'c-' ) ax.plot( oz_col.Ts, ...
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
And we find that the troposphere warms, while the stratosphere cools! Vertical structure of greenhouse warming in CESM model
datapath = "http://thredds.atmos.albany.edu:8080/thredds/dodsC/CESMA/" atmstr = ".cam.h0.clim.nc" cesm_ctrl = xr.open_dataset(datapath + 'som_1850_f19/clim/som_1850_f19' + atmstr) cesm_2xCO2 = xr.open_dataset(datapath + 'som_1850_2xCO2/clim/som_1850_2xCO2' + atmstr) cesm_ctrl.T T_cesm_ctrl_zon = cesm_ctrl.T.mean(dim=(...
_____no_output_____
BSD-3-Clause
docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb
cjcardinale/climlab
1.multiples of 3 and 5
sum1=0 x=int(input()) for i in range(1,x): if(i%3==0 or i%5==0): sum1=sum1+i print(sum1)
1000 233168
MIT
euler's.ipynb
boopathiviky/Eulers-Project
2.even fib numbers
a=0 b=1 c=0 sum2=0 for i in range(0,10): c=a+b a=b b=c print(c) if(c%2==0): sum2=sum2+c print('sum',sum2)
1 2 3 5 8 13 21 34 55 89 sum 44
MIT
euler's.ipynb
boopathiviky/Eulers-Project
3.prime fact of
def isprime(n): pr=1 for i in range(2,int(n/2)): if(n%i==0): pr=0 break if(pr==1): print(n) x=int(input()) for i in range(2,x): if(x%i==0): isprime(i)
15 3 5
MIT
euler's.ipynb
boopathiviky/Eulers-Project
4.Largest palindrome product
li=[] def ispalindrome(c): if(str(c) == str(c)[::-1]): li.append(c) #print(list) li.sort() for i in range(100,1000): for k in range(i,1000): a=i*k ispalindrome(a) print("Largest palindrome is:", li[-1])
Largest palindrome is: 906609
MIT
euler's.ipynb
boopathiviky/Eulers-Project
5.Smallest multiple
n=1 while (n>=1): n=n+1 c=1 for i in range(1,11): if (n%i==0): c=c+1 if (c>10): print(n) break
2520
MIT
euler's.ipynb
boopathiviky/Eulers-Project
6.Sum square difference
sq1=0 sq=0 # i insiate start,stop 10 1,9 1,11 for i in range(1,100+1): sq=i**2 sq1=sq1+sq sqr=0 for j in range(1,100+1): sqr=sqr+j s1=sqr**2 final=s1-sq1 print(sq1) print(s1) print(final) # sq1=0 # for i in range(1,10+1): # sq=i**2 # sq1=sq1+sq # print(sq) # print('\t',sq1)
_____no_output_____
MIT
euler's.ipynb
boopathiviky/Eulers-Project
7.10001st prime
def isprime(n): pr=1 for i in range(2,int(n/2)): if(n%i==0): pr=0 break if(pr==1): return 1 c=0 for i in range(3,1000000): if (isprime(i)==1): c=c+1 if (c>=10001): print (i) break
104743
MIT
euler's.ipynb
boopathiviky/Eulers-Project
8.Largest product in a series
n='731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511\ 125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749\ 3035890729629...
23514624000
MIT
euler's.ipynb
boopathiviky/Eulers-Project
9.Special Pythagorean triplet
for i in range(500): for j in range(500): for k in range(500): if i+j+k == 1000: if i<j<k: if i**2+j**2==k**2: print (i,j,k)
200 375 425
MIT
euler's.ipynb
boopathiviky/Eulers-Project
10.Summation of primes
num1=[] pr=0 for num in range(0,11): if num>=1: for i in range(2,num): if(num%i==0): pr=0 break else: pr=1 if(pr==1): num1.append(num) print(sum(num1))
_____no_output_____
MIT
euler's.ipynb
boopathiviky/Eulers-Project
11.Largest product in a grid
import numpy as np lst1=[] lst2=[] lst3=[] lst4=[] dt=np.genfromtxt('data.txt', delimiter=' ') rows, cols=dt.shape print(dt[0]) su=1 for i in range(0,rows): for j in range(0,cols): # forward if(j+4<=cols): su=dt[i,j]*dt[i,j+1]*dt[i,j+2]*dt[i,j+3] lst1.append(su) su=1 ...
_____no_output_____
MIT
euler's.ipynb
boopathiviky/Eulers-Project
`numpy`မင်္ဂလာပါ၊ welcome to the week 07 of Data Science Using Python. We will go into details of `numpy` this week (as well as do some linear algebra stuffs). `numpy` အကြောင်း သိပြီးသမျှ* `numpy` ဟာ array library ဖြစ်တယ်၊ * efficient ဖြစ်တယ်၊ * vector နဲ့ matrix တွေကို လွယ်လွယ်ကူကူ ကိုင်တွယ်နိုင်တယ်၊ * tens...
# tensor ဆိုတာ 2 ထက်များတဲ့ dimension ရှိတဲ့ array ကြီးတွေကို သင်္ချာဆန်ဆန် ခေါ်တာပါပဲ။ import numpy as np tensor_3d = np.array( [ [ [1, 2], [3, 4] ], [ [10, 20], [30, 40] ], ] ) print (tensor_3d.ndim, tensor_3d.shape, tensor_3...
_____no_output_____
Apache-2.0
week07/01_numpy.ipynb
neolaw84/data_science_using_python_labs
* **array indexing** `numpy` array တွေကို index လုပ်ဖို့ square bracket '[]' ထဲမှာ comma ',' ခံပြီး ရေးရတယ်။ dimension အရေအတွက် ရှိတဲ့အတိုင်း အကုန်ရေးရတယ်။ ချန်ထားရင် ကျန်တဲ့ dimensional တွေအတွက် အကုန်လို့ ယူဆတယ်။ * **slicing/dicing** `numpy` array တွေရဲ့ view တခုကို dimension အတွက် index ဂဏန်း နေရာမှာ start:end:step s...
from utils import my_data, np_data print (my_data) print ('---') print (np_data) # so, how to get the id, length, width view and height view ?
_____no_output_____
Apache-2.0
week07/01_numpy.ipynb
neolaw84/data_science_using_python_labs
`numpy` array creation`numpy` မှာ array ဖန်တီးဖို့ short-cut function တွေရှိတယ်။
import numpy as np a = np.zeros((2,2)) # Create an array of all zeros print(a) # Prints "[[ 0. 0.] # [ 0. 0.]]" b = np.ones((1,2)) # Create an array of all ones print(b) # Prints "[[ 1. 1.]]" c = np.full((2,2), 7) # Create a constant array print(c) ...
[[0. 0.] [0. 0.]] [[1. 1.]] [[7 7] [7 7]] [[1. 0.] [0. 1.]] [[0.12793776 0.2217626 ] [0.03490039 0.66624149]] [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34]
Apache-2.0
week07/01_numpy.ipynb
neolaw84/data_science_using_python_labs
အသုံးများတာကတော့ ... * `arange`* `zeros`* `ones`* `full`* `eye` နဲ့* `random.random` တို့ ဖြစ်တယ်။အပြည့်အစုံကို [Numpy official documentation](https://numpy.org/doc/stable/reference/routines.array-creation.html) မှာ ကြည့်နိုင်တယ်။ `numpy` array manipulationအသုံးအများဆုံး array manipulation ကတော့ ... * `copy`* `reshape...
v1 = np_data[::2] v2 = np_data[1::2,0] print (v1.shape, v2.shape) print (v1) print (v2) v2 =v2.reshape(-1,1) # here, -1 means "ကိုယ့်ဟာကိုယ် ကြည့်ဖြည့်လိုက်" print (v2.shape) np.hstack((v1, v2)) A = np.zeros((3,3)) # သတိထားစရာက tuple တွေကို parameter pass တာပဲ print (A) print ("---") B = np.eye(2, 2) print (B) print ("...
_____no_output_____
Apache-2.0
week07/01_numpy.ipynb
neolaw84/data_science_using_python_labs
နောက်ထပ် အသုံးများတဲ့ property တခုကတော့ `T` ပဲ။ transpose လုပ်တာ။
print (D.T) print (E.T)
_____no_output_____
Apache-2.0
week07/01_numpy.ipynb
neolaw84/data_science_using_python_labs
vector/matrix calculations`dot` function ဟာ matrix/vector တွေကို လွယ်ကူစွာ မြှောက်နိုင်စေတယ်။
x = np.array( [ [1,2], [3,4] ]) y = np.array( [ [5,6], [7,8] ]) v = np.array([9,10]) w = np.array([11, 12]) # Inner product of vectors; both produce 219 print(v.dot(w)) print(np.dot(v, w)) # Matrix / vector product; both produce the rank 1 array [29 67] print(x.dot(v))...
219 219 [29 67] [29 67] [[19 22] [43 50]] [[19 22] [43 50]]
Apache-2.0
week07/01_numpy.ipynb
neolaw84/data_science_using_python_labs
Special Array indexing`numpy` မှာ array တခုရဲ့ dimension တခုစီအတွက် list တခုနှုန်းနဲ့ (အဲဒီ list ထဲမှာ ကိုယ်လိုချင်တဲ့ element အရေအတွက်အတိုင်း ပါရ) index လုပ်တဲ့ special indexing method လဲ ရှိတယ်။
r = np.arange(35).reshape(5, 7) print (r) index_x0 = [3, 4, 4] index_x1 = [6, 2, 3] print (r[index_x0, index_x1])
[[ 0 1 2 3 4 5 6] [ 7 8 9 10 11 12 13] [14 15 16 17 18 19 20] [21 22 23 24 25 26 27] [28 29 30 31 32 33 34]] [27 30 31]
Apache-2.0
week07/01_numpy.ipynb
neolaw84/data_science_using_python_labs
`numpy` special boolean ability and boolean indexing
r_index = r % 2 == 0 print (r_index)
[[ True False True False True False True] [False True False True False True False] [ True False True False True False True] [False True False True False True False] [ True False True False True False True]]
Apache-2.0
week07/01_numpy.ipynb
neolaw84/data_science_using_python_labs
အဲဒီလို boolean array (size တူရမယ်) ကို အသုံးပြုပြီး မူလ array ကနေ data retrieval လုပ်နိုင်တယ်။
r_selected = r[r_index] print (r_selected)
[ 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34]
Apache-2.0
week07/01_numpy.ipynb
neolaw84/data_science_using_python_labs
Building your Deep Neural Network: Step by StepWelcome to your week 4 assignment (part 1 of 2)! Previously you trained a 2-layer Neural Network with a single hidden layer. This week, you will build a deep neural network with as many layers as you want!- In this notebook, you'll implement all the functions required to ...
import numpy as np import h5py import matplotlib.pyplot as plt from testCases import * from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward from public_tests import * %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'neares...
_____no_output_____
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
2 - OutlineTo build your neural network, you'll be implementing several "helper functions." These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function will have detailed instructions to walk you through the necessary steps. H...
# GRADED FUNCTION: initialize_parameters def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: parameters -- python dictionary containing your parameters: W1 --...
W1 = [[ 0.01624345 -0.00611756 -0.00528172] [-0.01072969 0.00865408 -0.02301539]] b1 = [[0.] [0.]] W2 = [[ 0.01744812 -0.00761207]] b2 = [[0.]]  All tests passed.
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
***Expected output***```W1 = [[ 0.01624345 -0.00611756 -0.00528172] [-0.01072969 0.00865408 -0.02301539]]b1 = [[0.] [0.]]W2 = [[ 0.01744812 -0.00761207]]b2 = [[0.]]``` 3.2 - L-layer Neural NetworkThe initialization for a deeper L-layer neural network is more complicated because there are many more weight matrices and...
# GRADED FUNCTION: initialize_parameters_deep def initialize_parameters_deep(layer_dims): """ Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": ...
W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388] [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218] [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034] [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]] b1 = [[0.] [0.] [0.] [0.]] W2 = [[-0.01185047 -0.0020565 ...
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
***Expected output***```W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388] [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218] [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034] [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]b1 = [[0.] [0.] [0.] [0.]]W2 = [[-0.011850...
# GRADED FUNCTION: linear_forward def linear_forward(A, W, b): """ Implement the linear part of a layer's forward propagation. Arguments: A -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current la...
Z = [[ 3.26295337 -1.23429987]]  All tests passed.
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
***Expected output***```Z = [[ 3.26295337 -1.23429987]]``` 4.2 - Linear-Activation ForwardIn this notebook, you will use two activation functions:- **Sigmoid**: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. You've been provided with the `sigmoid` function which returns **two** items: the activation va...
# GRADED FUNCTION: linear_activation_forward def linear_activation_forward(A_prev, W, b, activation): """ Implement the forward propagation for the LINEAR->ACTIVATION layer Arguments: A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weigh...
With sigmoid: A = [[0.96890023 0.11013289]] With ReLU: A = [[3.43896131 0. ]]  All tests passed.
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
***Expected output***```With sigmoid: A = [[0.96890023 0.11013289]]With ReLU: A = [[3.43896131 0. ]]``` **Note**: In deep learning, the "[LINEAR->ACTIVATION]" computation is counted as a single layer in the neural network, not two layers. 4.3 - L-Layer Model For even *more* convenience when implementing the $L...
# GRADED FUNCTION: L_model_forward def L_model_forward(X, parameters): """ Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() ...
AL = [[0.03921668 0.70498921 0.19734387 0.04728177]]  All tests passed.
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
***Expected output***```AL = [[0.03921668 0.70498921 0.19734387 0.04728177]]``` **Awesome!** You've implemented a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in "caches". Using $A^{[L]}$, you can compute the cost...
# GRADED FUNCTION: compute_cost def compute_cost(AL, Y): """ Implement the cost function defined by equation (7). Arguments: AL -- probability vector corresponding to your label predictions, shape (1, number of examples) Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), sh...
Cost: 0.2797765635793422  All tests passed.
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
**Expected Output**: cost 0.2797765635793422 6 - Backward Propagation ModuleJust as you did for the forward propagation, you'll implement helper functions for backpropagation. Remember that backpropagation is used to calculate the gradient of the loss function with respect to the parameters. **Rem...
A = np.array([[1, 2], [3, 4]]) print('axis=1 and keepdims=True') print(np.sum(A, axis=1, keepdims=True)) print('axis=1 and keepdims=False') print(np.sum(A, axis=1, keepdims=False)) print('axis=0 and keepdims=True') print(np.sum(A, axis=0, keepdims=True)) print('axis=0 and keepdims=False') print(np.sum(A, axis=0, keepd...
axis=1 and keepdims=True [[3] [7]] axis=1 and keepdims=False [3 7] axis=0 and keepdims=True [[4 6]] axis=0 and keepdims=False [4 6]
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
6.1 - Linear BackwardFor layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation).Suppose you have already calculated the derivative $dZ^{[l]} = \frac{\partial \mathcal{L} }{\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$.Figure 4The three outputs $(dW^{...
# GRADED FUNCTION: linear_backward def linear_backward(dZ, cache): """ Implement the linear portion of backward propagation for a single layer (layer l) Arguments: dZ -- Gradient of the cost with respect to the linear output (of current layer l) cache -- tuple of values (A_prev, W, b) coming from ...
dA_prev: [[-1.15171336 0.06718465 -0.3204696 2.09812712] [ 0.60345879 -3.72508701 5.81700741 -3.84326836] [-0.4319552 -1.30987417 1.72354705 0.05070578] [-0.38981415 0.60811244 -1.25938424 1.47191593] [-2.52214926 2.67882552 -0.67947465 1.48119548]] dW: [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 ...
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
**Expected Output**:```dA_prev: [[-1.15171336 0.06718465 -0.3204696 2.09812712] [ 0.60345879 -3.72508701 5.81700741 -3.84326836] [-0.4319552 -1.30987417 1.72354705 0.05070578] [-0.38981415 0.60811244 -1.25938424 1.47191593] [-2.52214926 2.67882552 -0.67947465 1.48119548]]dW: [[ 0.07313866 -0.0976715 -0.8758...
# GRADED FUNCTION: linear_activation_backward def linear_activation_backward(dA, cache, activation): """ Implement the backward propagation for the LINEAR->ACTIVATION layer. Arguments: dA -- post-activation gradient for current layer l cache -- tuple of values (linear_cache, activation_cache)...
With sigmoid: dA_prev = [[ 0.11017994 0.01105339] [ 0.09466817 0.00949723] [-0.05743092 -0.00576154]] With sigmoid: dW = [[ 0.10266786 0.09778551 -0.01968084]] With sigmoid: db = [[-0.05729622]] With relu: dA_prev = [[ 0.44090989 0. ] [ 0.37883606 0. ] [-0.2298228 0. ]] With relu: dW = [...
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
**Expected output:**```With sigmoid: dA_prev = [[ 0.11017994 0.01105339] [ 0.09466817 0.00949723] [-0.05743092 -0.00576154]]With sigmoid: dW = [[ 0.10266786 0.09778551 -0.01968084]]With sigmoid: db = [[-0.05729622]]With relu: dA_prev = [[ 0.44090989 0. ] [ 0.37883606 0. ] [-0.2298228 0. ]]Wi...
# GRADED FUNCTION: L_model_backward def L_model_backward(AL, Y, caches): """ Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group Arguments: AL -- probability vector, output of the forward propagation (L_model_forward()) Y -- true "label" vector (contain...
dA0 = [[ 0. 0.52257901] [ 0. -0.3269206 ] [ 0. -0.32070404] [ 0. -0.74079187]] dA1 = [[ 0.12913162 -0.44014127] [-0.14175655 0.48317296] [ 0.01663708 -0.05670698]] dW1 = [[0.41010002 0.07807203 0.13798444 0.10502167] [0. 0. 0. 0. ] [0.05283652 0.01...
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
**Expected output:**```dA0 = [[ 0. 0.52257901] [ 0. -0.3269206 ] [ 0. -0.32070404] [ 0. -0.74079187]]dA1 = [[ 0.12913162 -0.44014127] [-0.14175655 0.48317296] [ 0.01663708 -0.05670698]]dW1 = [[0.41010002 0.07807203 0.13798444 0.10502167] [0. 0. 0. 0. ] [0...
# GRADED FUNCTION: update_parameters def update_parameters(params, grads, learning_rate): """ Update parameters using gradient descent Arguments: params -- python dictionary containing your parameters grads -- python dictionary containing your gradients, output of L_model_backward Re...
W1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008] [-1.76569676 -0.80627147 0.51115557 -1.18258802] [-1.0535704 -0.86128581 0.68284052 2.20374577]] b1 = [[-0.04659241] [-1.28888275] [ 0.53405496]] W2 = [[-0.55569196 0.0354055 1.32964895]] b2 = [[-0.84610769]]  All tests passed.
MIT
Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb
alivara/deep_learning
**Load training data**
train_df = pd.read_csv("/kaggle/input/house-prices-advanced-regression-techniques/train.csv")
_____no_output_____
MIT
notebook04cb9a8032.ipynb
brendanmanning/Kaggle-Housing-Price-Activity
**Remove categorical features, handle missing data, cast improper types**
train_df['MSSubClass'] = train_df['MSSubClass'].apply(str) train_df['MoSold'] = train_df['MoSold'].astype(str) train_df['YrSold'] = train_df['YrSold'].astype(str) cat_features = train_df.select_dtypes(include = 'object').columns train_df.drop(cat_features, axis=1, inplace=True) for c in train_df.columns: train_df...
_____no_output_____
MIT
notebook04cb9a8032.ipynb
brendanmanning/Kaggle-Housing-Price-Activity
**Split the data into X(test/train) and Y(test/train) datasets**
y = train_df['SalePrice'] x = train_df.loc[:, train_df.columns != 'SalePrice'] X_dict = x.to_dict(orient='records') dv_X = DictVectorizer(sparse=False) X_encoded = dv_X.fit_transform(X_dict) X_Train, X_Test, Y_Train, Y_Test = train_test_split(X_encoded, y.to_numpy(), test_size=0.33, random_state=42)
_____no_output_____
MIT
notebook04cb9a8032.ipynb
brendanmanning/Kaggle-Housing-Price-Activity
**Train a Linear Regression Model**
# Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(X_Train, Y_Train)
_____no_output_____
MIT
notebook04cb9a8032.ipynb
brendanmanning/Kaggle-Housing-Price-Activity
**Predict from the testing set**
# Make predictions using the testing set preds = regr.predict(X_Test)
_____no_output_____
MIT
notebook04cb9a8032.ipynb
brendanmanning/Kaggle-Housing-Price-Activity
**Score the model**
regr.score(X_Test, Y_Test)
_____no_output_____
MIT
notebook04cb9a8032.ipynb
brendanmanning/Kaggle-Housing-Price-Activity
Isolation Forest (IF) outlier detector deployment Wrap a scikit-learn Isolation Forest python model for use as a prediction microservice in seldon-core and deploy on seldon-core running on minikube or a Kubernetes cluster using GCP. Dependencies - [helm](https://github.com/helm/helm)- [minikube](https://github.com/ku...
# define columns to keep cols=['duration','protocol_type','flag','src_bytes','dst_bytes','land', 'wrong_fragment','urgent','hot','num_failed_logins','logged_in', 'num_compromised','root_shell','su_attempted','num_root','num_file_creations', 'num_shells','num_access_files','num_outbound_cmds','is_host_...
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Test using Kubernetes cluster on GCP or Minikube Run the outlier detector as a model or a transformer. If you want to run the anomaly detector as a transformer, change the SERVICE_TYPE variable from MODEL to TRANSFORMER [here](./.s2i/environment), set MODEL = False and change ```OutlierIsolationForest.py``` to:```pyth...
MODEL = True
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Pick Kubernetes cluster on GCP or Minikube.
MINIKUBE = True if MINIKUBE: !minikube start --memory 4096 else: !gcloud container clusters get-credentials standard-cluster-1 --zone europe-west1-b --project seldon-demos
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Create a cluster-wide cluster-admin role assigned to a service account named “default” in the namespace “kube-system”.
!kubectl create clusterrolebinding kube-system-cluster-admin --clusterrole=cluster-admin \ --serviceaccount=kube-system:default !kubectl create namespace seldon
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Add current context details to the configuration file in the seldon namespace.
!kubectl config set-context $(kubectl config current-context) --namespace=seldon
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Create tiller service account and give it a cluster-wide cluster-admin role.
!kubectl -n kube-system create sa tiller !kubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller !helm init --service-account tiller
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Check deployment rollout status and deploy seldon/spartakus helm charts.
!kubectl rollout status deploy/tiller-deploy -n kube-system !helm install ../../../helm-charts/seldon-core-operator --name seldon-core --set usage_metrics.enabled=true --namespace seldon-system
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Check deployment rollout status for seldon core.
!kubectl rollout status deploy/seldon-controller-manager -n seldon-system
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Install Ambassador API gateway
!helm install stable/ambassador --name ambassador --set crds.keep=false !kubectl rollout status deployment.apps/ambassador
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
If Minikube used: create docker image for outlier detector inside Minikube using s2i. Besides the transformer image and the demo specific model image, the general model image for the Isolation Forest outlier detector is also available from Docker Hub as ***seldonio/outlier-if-model:0.1***.
if MINIKUBE & MODEL: !eval $(minikube docker-env) && \ s2i build . seldonio/seldon-core-s2i-python3:0.4 seldonio/outlier-if-model-demo:0.1 elif MINIKUBE: !eval $(minikube docker-env) && \ s2i build . seldonio/seldon-core-s2i-python3:0.4 seldonio/outlier-if-transformer:0.1
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Install outlier detector helm charts either as a model or transformer and set *threshold* hyperparameter value.
if MODEL: !helm install ../../../helm-charts/seldon-od-model \ --name outlier-detector \ --namespace=seldon \ --set model.type=isolationforest \ --set model.isolationforest.image.name=seldonio/outlier-if-model-demo:0.1 \ --set model.isolationforest.threshold=0 \ --set...
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Port forward AmbassadorRun command in terminal: ```kubectl port-forward $(kubectl get pods -n seldon -l app.kubernetes.io/name=ambassador -o jsonpath='{.items[0].metadata.name}') -n seldon 8003:8080``` Import rest requests, load data and test requests
from utils import get_payload, rest_request_ambassador, send_feedback_rest, get_kdd_data, generate_batch data = get_kdd_data(keep_cols=cols,percent10=True) # load dataset print(data.shape)
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Generate a random batch from the data
import numpy as np samples = 1 fraction_outlier = 0. X, labels = generate_batch(data,samples,fraction_outlier) print(X.shape) print(labels.shape)
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Test the rest requests with the generated data. It is important that the order of requests is respected. First we make predictions, then we get the "true" labels back using the feedback request. If we do not respect the order and eg keep making predictions without getting the feedback for each prediction, there will be...
request = get_payload(X) response = rest_request_ambassador("outlier-detector","seldon",request,endpoint="localhost:8003")
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
If the outlier detector is used as a transformer, the output of the anomaly detection is added as part of the metadata. If it is used as a model, we send model feedback to retrieve custom performance metrics.
if MODEL: send_feedback_rest("outlier-detector","seldon",request,response,0,labels,endpoint="localhost:8003")
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Analytics Install the helm charts for prometheus and the grafana dashboard
!helm install ../../../helm-charts/seldon-core-analytics --name seldon-core-analytics \ --set grafana_prom_admin_password=password \ --set persistence.enabled=false \ --namespace seldon
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Port forward Grafana dashboard Run command in terminal: ```kubectl port-forward $(kubectl get pods -n seldon -l app=grafana-prom-server -o jsonpath='{.items[0].metadata.name}') -n seldon 3000:3000``` You can then view an analytics dashboard inside the cluster at http://localhost:3000/dashboard/db/prediction-analytics?...
import time n_requests = 100 samples = 1 for i in range(n_requests): fraction_outlier = .1 X, labels = generate_batch(data,samples,fraction_outlier) request = get_payload(X) response = rest_request_ambassador("outlier-detector","seldon",request,endpoint="localhost:8003") if MODEL: send_feedb...
_____no_output_____
Apache-2.0
components/outlier-detection/isolation-forest/isolation_forest.ipynb
OrthoDex/seldon-core
Implementing logistic regression from scratchThe goal of this notebook is to implement your own logistic regression classifier. We will: * Extract features from Amazon product reviews. * Convert an SFrame into a NumPy array. * Implement the link function for logistic regression. * Write a function to compute the deriv...
import turicreate ## utils for this notebooks moved into its own package import sys sys.path.append("../common") from utils import time_it, assert_all, get_numpy_data, load_important_words
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec