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 |
|---|---|---|---|---|---|
At this point the generator object is **created**, but we have not actually started running it. To do so, we call `next()`, which then starts running the function body until the first `yield` is encountered: | next(g) | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
Now the generator is **suspended**, waiting for us to call next again: | next(g) | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
Every time we call `next`, the generator function runs, or is in a **running** state until the next yield is encountered, or no more results are yielded and the function actually returns: | next(g)
next(g) | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
Once we exhaust the generator, we get a `StopIteration` exception, and we can think of the generator as being **closed**. As we can see, a generator can be in one of four states:* created* running* suspended* closed We can actually request the state of a generator programmatically by using the `inspect` module's `getge... | from inspect import getgeneratorstate
g = gen('abc')
getgeneratorstate(g) | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
We can start running the generator by calling `next`: | next(g) | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
And the state is now: | getgeneratorstate(g) | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
Once we exhaust the generator: | next(g), next(g), next(g) | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
The generator is now in a closed state: | getgeneratorstate(g) | _____no_output_____ | Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
Now we haven't seen the running state - to do that we just need to print the state from inside the generator - but to do that we need to have a reference to the generator object itself. This is not that easy to do, so I'm going to cheat and assume that the generator object will be referenced by a global variable `globa... | def gen(s):
for c in s:
print(getgeneratorstate(global_gen))
yield c
global_gen = gen('abc')
next(global_gen) | GEN_RUNNING
| Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
So a generator can be in these four very distinct states.When the generator is created, it is not in a running or suspended state - it is simply in a **created** state.We have to kick-off, or prime, the generator by calling `next` on it.After the generator has yielded a value, it it is in **suspended** state.Finally, o... | def square(i):
print(f'squaring {i}')
return i ** 2
def squares(n):
for i in range(n):
yield square(i)
print ('right after yield')
sq = squares(5)
next(sq) | squaring 0
| Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
As you can see `square(i)` was evaluated, **then** the value was yielded, and the genrator was suspended exactly at the point the `yield` statement was encountered: | next(sq) | right after yield
squaring 1
| Apache-2.0 | python-tuts/1-intermediate/06 - Generator Based Co-routines/02 - Generator States.ipynb | timgates42/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials |
Notebook 2: Setup Domain Now that we have sshed into our virtual machine (as described in the 👈🏿 notebook [01-data-owners-login.ipynb](01-data-owners-login.ipynb)), let's move on to provision our Domain node.**Note:** These steps are designed to work on a Ubuntu 20.04 VM however the steps for other linux versions o... | # autodetect the host_ip
from utils import auto_detect_domain_host_ip
DOMAIN_HOST_IP = auto_detect_domain_host_ip() | _____no_output_____ | Apache-2.0 | notebooks/medical-federated-learning-program/data-owners-full/02-data-owners-setup-domain.ipynb | Noob-can-Compile/PySyft |
print("Your Domain's Web Portal should now be ready:\n")
print("👇🏽 Click here to see PyGridUI")
print(f"http://{DOMAIN_HOST_IP}") | _____no_output_____ | Apache-2.0 | notebooks/medical-federated-learning-program/data-owners-full/02-data-owners-setup-domain.ipynb | Noob-can-Compile/PySyft | |
Importing libraries | import pandas as pd
import random
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras import regularizers
import matplotlib.pyplot as plt
from itertools impo... | _____no_output_____ | MIT | news_analyze.ipynb | Eg-nce/NLP-with-Reddit-r-news-page |
Data loading and cleaning | Reddit_df = pd.read_csv("/home/ege/selenium/r_news.csv" )
contractions = pd.read_csv("/home/ege/Desktop/kaggle/NLP/archive/contractions.csv")
Reddit_df.dropna( inplace = True)
Reddit_df = Reddit_df[['r/news']]
Reddit_df.drop_duplicates(inplace = True)
Reddit_df.head()
with open('/home/ege/Desktop/kaggle/NLP/word_index... | _____no_output_____ | MIT | news_analyze.ipynb | Eg-nce/NLP-with-Reddit-r-news-page |
Defining preprocessing functions | def df_to_dict(data):
dictionary = dict()
col_names = data.columns
for _ in range(data.shape[0]):
dictionary[data[col_names[0]].iloc[_]] = data[col_names[1]].iloc[_]
return dictionary
def lower(data):
columns = data.columns
for col in columns:
data[col] = data[col].apply(str)
... | _____no_output_____ | MIT | news_analyze.ipynb | Eg-nce/NLP-with-Reddit-r-news-page |
Data preprocessing | Reddit_df = lower(Reddit_df)
contractions_dict = df_to_dict(contractions)
Reddit_df['r/news'] = Reddit_df['r/news'].apply(preprocess_data)
split_list = split_func(Reddit_df)
tokenized_list = tokenizer_based_on_json(split_list , tokens)
news_padded = pad_sequences(tokenized_list , maxlen= max([len(x) for x in tokeniz... | _____no_output_____ | MIT | news_analyze.ipynb | Eg-nce/NLP-with-Reddit-r-news-page |
Importing saved tensorflow model | model = tf.keras.models.load_model("/home/ege/saved_model/my_model") | _____no_output_____ | MIT | news_analyze.ipynb | Eg-nce/NLP-with-Reddit-r-news-page |
Predictions | predictions = model.predict(news_padded)
predictions_list = []
for pred in predictions:
if pred > 0.7:
predictions_list.append(1)
else:
predictions_list.append(0)
| _____no_output_____ | MIT | news_analyze.ipynb | Eg-nce/NLP-with-Reddit-r-news-page |
Exploring predictions | print("negative news : " , predictions_list.count(0) , "positive news " , predictions_list.count(1))
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
labels = ['negative news', 'positive news']
numbers = [ predictions_list.count(0) , predictions_list.count(1)]
ax.bar(labels,numbers ,color = 'rg')
plt.show()
Poz_index = ... | -- Some positive news labeled by model --
1 l a coronavirus update county surpasses 7 00 covid 19 hospitalizations for first time .
2 beverly hills eatery reportedly planning indoor speakeasy nye party draws police interest .
3 azerbaijani energy ministry acwa power company sign agreement on wind farm project ... | MIT | news_analyze.ipynb | Eg-nce/NLP-with-Reddit-r-news-page |
Intermediate Lesson on Geospatial Data Data, Information, Knowledge and WisdomLesson Developers: Jayakrishnan Ajayakumar, Shana Crosson, Mohsen Ahmadkhani Part 1 of 5 | # This code cell starts the necessary setup for Hour of CI lesson notebooks.
# First, it enables users to hide and unhide code by producing a 'Toggle raw code' button below.
# Second, it imports the hourofci package, which is necessary for lessons and interactive Jupyter Widgets.
# Third, it helps hide/control other as... | _____no_output_____ | BSD-3-Clause | intermediate-lessons/geospatial-data/gd-1.ipynb | mohsenumn/lessons |
ReminderContinue with the lessonBy continuing with this lesson you are granting your permission to take part in this research study for the Hour of Cyberinfrastructure: Developing Cyber Literacy for GIScience project. In this study, you will be learning about cyberinfrastructure and related concepts using a web-based ... | from ipywidgets import Button, HBox, VBox,widgets,Layout
from IPython.display import display
import pandas as pd
table1 = pd.read_csv('databases/antartica_mass.csv').sample(frac = 1)
table1['0'] = pd.to_datetime(table1['0'])
table2 = pd.read_csv('databases/global_temperature.csv').sample(frac = 1)
table2['0'] = pd.to_d... | _____no_output_____ | BSD-3-Clause | intermediate-lessons/geospatial-data/gd-1.ipynb | mohsenumn/lessons |
These are just symbols and numbers (of course we can identify the date as we have seen that pattern before) and doesn't convey anything.This is what we essentially call **Data (or raw Data)**. What is Data? >**Data is a collection of facts** in a **raw or unorganized form** such as **numbers or characters**.Without **... | table1.columns = ["Time", "Antartic_Mass(Gt)"]
table2.columns = ["Time", "Temperature_Anomaly(C)"]
table3.columns = ["Time", "Carbon_Dioxide(PPM)"]
table1_disp = widgets.Output()
table2_disp = widgets.Output()
table3_disp = widgets.Output()
with table1_disp:
display(table1)
with table2_disp:
display(table2)
wit... | _____no_output_____ | BSD-3-Clause | intermediate-lessons/geospatial-data/gd-1.ipynb | mohsenumn/lessons |
We can do more **processing** on the data and can convert it into structured forms. For example we can **sort** these datasets to look for temporal changes | table1_disp = widgets.Output()
table2_disp = widgets.Output()
table3_disp = widgets.Output()
with table1_disp:
display(table1.sort_values(by='Time'))
with table2_disp:
display(table2.sort_values(by='Time'))
with table3_disp:
display(table3.sort_values(by='Time'))
out=HBox([VBox([table1_disp],layout = Layout... | _____no_output_____ | BSD-3-Clause | intermediate-lessons/geospatial-data/gd-1.ipynb | mohsenumn/lessons |
After sorting we can see that, with Time, there is a depletion in Antratic mass and increase in temperature anomaly as well as carbon dioxide content in the atmosphere.We can also **visualize** these datasets (as a picture is worth 1000 words!!) to bolster our arguments | import matplotlib.pyplot as plt
fig, axes = plt.subplots(1,3)
fig.set_figheight(8)
fig.set_figwidth(20)
table1.sort_values(by='Time').plot(x='Time',y='Antartic_Mass(Gt)',ax=axes[0]);
table2.sort_values(by='Time').plot(x='Time',y='Temperature_Anomaly(C)',ax=axes[1]);
table3.sort_values(by='Time').plot(x='Time',y='Carbon... | _____no_output_____ | BSD-3-Clause | intermediate-lessons/geospatial-data/gd-1.ipynb | mohsenumn/lessons |
%pip install -q tensorflow_addons
!git clone https://github.com/tfrizza/DALL-E-tf.git
%cd DALL-E-tf
import tensorflow as tf
from tensorflow.keras import Model, mixed_precision
from tensorflow.keras.losses import Loss, MeanSquaredError, MeanAbsoluteError, MSE, MAE
from tensorflow.keras.optimizers import Adam
from tensor... | _____no_output_____ | MIT | tfFlowers_demo.ipynb | tfrizza/DALL-E-tf | |
Accessing and Reading the Dataset | # If pandas is not installed, please uncomment the following line:
!pip install pandas
%matplotlib inline
import numpy as np
import pandas as pd
import tensorflow as tf
from d2l import tensorflow as d2l
# download and cache the Kaggle housing dataset
DATA_HUB['kaggle_house_train'] = (
DATA_URL + 'kaggle_house_pr... | _____no_output_____ | Unlicense | Week 9/4.10. Predicting House Prices on Kaggle.ipynb | Hanif-2610/Machine-Learning-Homework-Project |
Data Preprocessing | # If test data were inaccessible, mean and standard deviation could be
# calculated from training data
numeric_features = all_features.dtypes[all_features.dtypes != 'object'].index
all_features[numeric_features] = all_features[numeric_features].apply(
lambda x: (x - x.mean()) / (x.std()))
# After standardizing the ... | _____no_output_____ | Unlicense | Week 9/4.10. Predicting House Prices on Kaggle.ipynb | Hanif-2610/Machine-Learning-Homework-Project |
Training | loss = tf.keras.losses.MeanSquaredError()
def get_net():
net = tf.keras.models.Sequential()
net.add(tf.keras.layers.Dense(
1, kernel_regularizer=tf.keras.regularizers.l2(weight_decay)))
return net
def log_rmse(y_true, y_pred):
# To further stabilize the value when the logarithm is taken, set th... | _____no_output_____ | Unlicense | Week 9/4.10. Predicting House Prices on Kaggle.ipynb | Hanif-2610/Machine-Learning-Homework-Project |
K -Fold Cross-Validation | # function that returns the ith fold of the data in a K -fold cross-validation procedure
def get_k_fold_data(k, i, X, y):
assert k > 1
fold_size = X.shape[0] // k
X_train, y_train = None, None
for j in range(k):
idx = slice(j * fold_size, (j + 1) * fold_size)
X_part, y_part = X[idx, :... | _____no_output_____ | Unlicense | Week 9/4.10. Predicting House Prices on Kaggle.ipynb | Hanif-2610/Machine-Learning-Homework-Project |
Model Selection | !pip uninstall matplotlib
!pip install --upgrade matplotlib
k, num_epochs, lr, weight_decay, batch_size = 5, 100, 5, 0, 64
train_l, valid_l = k_fold(k, train_features, train_labels, num_epochs, lr,
weight_decay, batch_size)
print(f'{k}-fold validation: avg train log rmse: {float(train_l):f}, '... | fold 1, train log rmse 0.170148, valid log rmse 0.156585
fold 2, train log rmse 0.162369, valid log rmse 0.191238
fold 3, train log rmse 0.163789, valid log rmse 0.168228
fold 4, train log rmse 0.167955, valid log rmse 0.154542
fold 5, train log rmse 0.163108, valid log rmse 0.182900
5-fold validation: avg train log rm... | Unlicense | Week 9/4.10. Predicting House Prices on Kaggle.ipynb | Hanif-2610/Machine-Learning-Homework-Project |
1. 배열 생성 | np.array([1, 2, 3, 4])
np.array([[1, 2, 3], [4, 5, 6]]) | _____no_output_____ | MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
1.1. 자료형 지정 | np.array([1.2, 2.1, -1.6, 4.45], dtype='f') | _____no_output_____ | MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
1.2. 영벡터 생성 | np.zeros(3, dtype='i')
np.zeros((2, 3)) | _____no_output_____ | MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
1.3. 원소가 1인 벡터 생성 | np.ones((2, 6)) | _____no_output_____ | MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
1.4. 다른 배열을 이용한 벡터 생성 | a = np.array([[1, 2,], [3, 4], [5, 6]])
print(a)
print(a.shape)
b = np.zeros_like(a, dtype='f')
# b = np.ones_like(a, dtype='f')
print()
print(b)
print(b.shape) | [[1 2]
[3 4]
[5 6]]
(3, 2)
[[1. 1.]
[1. 1.]
[1. 1.]]
(3, 2)
| MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
1.5. 초기화 없이 배열 생성 @메모리에 있는 값을 바탕으로 배열 요소값이 지정됨 | a = np.empty((10, 3))
print(a) | [[1.41158355e-311 9.58487353e-322 0.00000000e+000]
[0.00000000e+000 6.95293141e-310 5.02034658e+175]
[1.27010965e-075 2.57751692e-056 4.16150492e-061]
[6.12673096e-062 1.47763641e+248 1.16096346e-028]
[7.69165785e+218 1.35617292e+248 1.10208290e-046]
[5.64373615e-038 1.40415688e+165 2.89818752e-057]
[4.26050046e-... | MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
1.6. Arange 사용 | np.arange(10)
# np.arange(시작, 끝, 공차)
np.arange(3, 20, 4) | _____no_output_____ | MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
2. 차원 확인 | a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
print(np.ndim(a))
a = np.array([[[1, 2, 3], [4, 5, 6]], [[2, 4, 6], [-1, 0, 0]]])
print(a)
print(a.shape)
a = np.array([[[1, 2, 3]], [[-1, 0, 0]]])
print(a)
print(a.shape)
print(np.ndim(a)) | [[[ 1 2 3]]
[[-1 0 0]]]
(2, 1, 3)
3
| MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
3. 차원 변경 | a = np.array([1, 2, 3, 4, 5, 6])
print(a)
print(a.reshape([2, 3]))
print(a.reshape([2, -1]))
print(a.reshape([-1, 2]))
print(a.reshape([2, 3, 1])) | [[[1]
[2]
[3]]
[[4]
[5]
[6]]]
| MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
3.1. 전치 | a = np.array([[1, 2, 3,], [4, 5, 6]])
print(a)
print(a.shape)
print()
b = a.T
print(b)
print(b.shape) | [[1 2 3]
[4 5 6]]
(2, 3)
[[1 4]
[2 5]
[3 6]]
(3, 2)
| MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
3.2. 차원축 추가 | a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
print()
a = np.expand_dims(a, axis=0)
print(a.shape) | (2, 3)
(1, 2, 3)
| MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
4. 자료형 변경 | a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)
print(a.astype('float32')) | [[1 2 3]
[4 5 6]]
[[1. 2. 3.]
[4. 5. 6.]]
| MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
5. 배열 계산 5.1. Elementwise 계산 | a = np.array([[1, 2, 3], [4, 5, 6]]).astype('float32')
print(a)
print(a/2)
a = np.array([1, 2, 3, 4, 5, 6])
print(a)
b = a >= 4
print(b)
print(b.astype(np.int)) | [1 2 3 4 5 6]
[False False False True True True]
[0 0 0 1 1 1]
| MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
5.2. 행렬 곱 | a = np.array([[1, 0], [2, 2]])
print(a.shape)
b = np.array([[2, 2], [3, 0]])
print(b.shape)
print(np.dot(a, b))
a = np.array(
[[1, 1, 2],
[0, 2, 0]])
print(a.shape)
b = np.array(
[[1, 2],
[0, 3],
[1, 1]])
print(b.shape)
print(np.dot(a, b)) | (2, 3)
(3, 2)
[[3 7]
[0 6]]
| MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
6. hstack | a = np.array([1, 1, [2, 2, -1], [3, 0], 6])
print(a)
b = np.hstack(a)
print(b)
a = np.array([[1, 1, [2, 2, -1], [3, 0], 6], [12, 12, [21, 21, -11], [30, 0], 16]])
print(a)
b = np.hstack(a)
print(b)
tmp = list()
for i in a:
tmp.append(np.hstack(i))
tmp1 = np.vstack(tmp)
print(tmp1) | [[ 1 1 2 2 -1 3 0 6]
[ 12 12 21 21 -11 30 0 16]]
| MIT | jupyter_notebooks/Numpy_Memo0.ipynb | 0pt3ryx/0pt3ryx.github.io |
Modeling | trainingset.columns[model.get_support()]
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(trainingset, ytrain, test_size=0.05, random_state=42)
print('Start training...')
# train
gbm = lgb.LGBMRegressor(objective='regression',
num_leaves=60... | _____no_output_____ | BSD-3-Clause | argedis.ipynb | AurelienGalicher/DStoolkit |
Final Output | %matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
from statistics import mean, median, variance
plt.rcParams['figure.figsize'] = [10, 5]
import pprint
import math
import tabulate
def get_overheads(file_name):
data = []
with open(file_name, 'r') as results:
for line in result... | _____no_output_____ | MIT | final.ipynb | ia2067/TRAPP |
Machine learning sur le titanic | import pandas as pd
import numpy as np | _____no_output_____ | MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
On importe les données | titanic = pd.read_csv("./data/titanic_train.csv")
titanic.head() | _____no_output_____ | MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
On sélectionne les colonnes de x | x = titanic.drop(["PassengerId","Survived","Name","Ticket"],axis=1)
y = titanic["Survived"] | _____no_output_____ | MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
On simplifie la colonne `Cabin` | x["Cabin"]=x["Cabin"].str[0].fillna("No").replace({"T":"No","G":"No"})#.replace("G","No")
# on transforme toutes colonnes quali en binaires
x = pd.get_dummies(x,columns=["Sex","Cabin","Embarked"])
def transfo(x):
""" Cette fonction permet de transformer en binaires toutes les colonnes
objet d'un DataFrame en ut... | _____no_output_____ | MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
Séparation apprentissage / test | from sklearn.model_selection import train_test_split | _____no_output_____ | MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
On veut découper nos données en train / test | x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.3)
print(x_train.shape, x_test.shape) | (623, 17) (268, 17)
| MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
On va construire et estimer des modèles de ML | from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import confusion_matrix, roc_auc_score, accuracy_score
dico_modeles... | _____no_output_____ | MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
On va rechercher les hyper-paramètres du modèle en utilisant une grille | from sklearn.model_selection import GridSearchCV
# on construit la grille de paramètres
param = dict(n_estimators=[10,100,1000], max_depth=[3,5,7,9])
# on crée un objet de la classe GridSearchCV
modele_grid= GridSearchCV(RandomForestClassifier(),param,scoring="roc_auc",cv=4)
modele_grid.fit(x_train,y_train)
modele_gri... | _____no_output_____ | MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
Si on veut exporter un modèle, on peut utiliser : | from sklearn.externals import joblib
joblib.dump(modele_grid,"modele_grid.pkl") | _____no_output_____ | MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
Construction d'un pipeline | from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.decomposition import PCA
# création d'un objet de la classe Pipeline
mon_pipe = Pipeline(steps=[("acp",PCA(n_components=4)),("svm",SVC())])
mon_pipe.fit(x_train,y_train)
confusion_matrix(y_test,mon_pipe.predict(x_test)) | _____no_output_____ | MIT | 07c_ML_titanic.ipynb | stat4decision/python-data-lbp-fev20 |
Imporing Libraries and Dataset | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
data_train= pd.read_csv(r"C:\Users\shruti\Desktop\Decodr Session Recording\Project\Decodr Project\Power Plant Data Analysis\train.csv", delimiter=",... | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Structure of Dataset | data_train.describe()
y_train.shape | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Checking for Null values | data_train.isnull().sum()
data_train.isna().sum()
y_train.isnull().sum()
y_train.isna().sum() | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Exploratory Data Analysis | # Statistics
min_EP= y_train.min()
max_EP= y_train.max()
mean_EP= y_train.mean()
median_EP= y_train.median()
std_EP= y_train.std()
# Quartile calculator
first_quar= np.percentile(y_train, 25)
third_quar= np.percentile(y_train, 75)
inter_quar= third_quar - first_quar
# Print Statistics
print("Statistics for combined ... | Statistics for combined cycle Power Plant:
Minimum EP: 420.26
Maximum EP: 495.76
Mean EP: 454.43129319955347
Median EP: 451.74
Standard Deviation of EP: 17.134571175425727
First Quartile of EP: 439.7375
Third Quartile of EP: 468.6675
InterQuartile of EP: 28.930000000000007
| Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Plotting | sns.set(rc={"figure.figsize":(5,5)})
sns.distplot(data_train, bins=30, color= "orange")
plt.show() | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Correlation | corr_df=data_train.copy()
corr_df["EP"]=y_train
corr_df.head()
sns.set(style="ticks", color_codes=True)
plt.figure(figsize=(12,12))
sns.heatmap(corr_df.astype("float32").corr(), linewidths=0.1, square=True, annot=True)
plt.show() | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Features Plot | # Print all Features
data_train.columns
plt.plot(corr_df["# T"], corr_df["EP"], "+", color= "green")
plt.plot(np.unique(corr_df["# T"]), np.poly1d(np.polyfit(corr_df["# T"], corr_df["EP"], 1))
(np.unique(corr_df["# T"])), color="yellow")
plt.xlabel("Temperature", fontsize=12)
plt.ylabel("EP", fontsize=12)
plt.... | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Feature Scaling | from sklearn.preprocessing import StandardScaler
scaler= StandardScaler()
scaler.fit_transform(data_train) | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Gradient Descent Model | x_train= data_train
x_train.shape, y_train.shape
from sklearn.ensemble import GradientBoostingRegressor
gbr=GradientBoostingRegressor(learning_rate=1.9, n_estimators=2000)
gbr
gbr.fit(x_train, y_train)
x_test= np.genfromtxt(r"C:\Users\shruti\Desktop\Decodr Session Recording\Project\Decodr Project\Power Plant Data Anal... | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Model Evaluation | gbr.score(x_train, y_train) | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
Saving the Prediction | np.savetxt("Predict_csv", y_pred, fmt="%.5f") | _____no_output_____ | Unlicense | Project3- Power Plant Data Analysis.ipynb | Shruti0630/Shruti_PythonProject3 |
NumPy - 科学计算 一、简介 NumPy是Python语言的一个扩充程序库。支持高级大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。Numpy内部解除了[CPython的GIL](https://www.cnblogs.com/wj-1314/p/9056555.html)(全局解释器锁),运行效率极好,是大量机器学习框架的基础库!NumPy的全名为Numeric Python,是一个开源的Python科学计算库,它包括:- 一个强大的N维数组对象ndrray;- 比较成熟的(广播)函数库;- 用于整合C/C++和Fortran代码的工具包;- 实用的线性代数、傅里叶变换和随机数生成函数 NumPy的... | # 调用
import numpy as np
# 将列表转换为矩阵
a = [[1,2,3],[2,3,4]]
print('list:\n',a)
array = np.array(a)
print('array:\n',array)
# 获取矩阵基本属性
print('num of dim:',array.ndim) # 秩,矩阵维度
print('shape:',array.shape) # 矩阵形状
print('size:',array.size) # 矩阵元素数量 | num of dim: 2
shape: (2, 3)
size: 6
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
2.2 矩阵生成(1)指定元素格式。 NumPy 支持比 Python 更多种类的数值类型,为了区别于 Python 原生的数据类型,bool、int、float、complex、str 等类型名称末尾都加了_,详细的数据类型列表可在以下网址查看:https://www.cnblogs.com/gl1573/p/10549547.html。 | # 将列表转化为指定格式的矩阵
a = np.array([2,3,4],dtype=np.float32)
print(a.dtype) | float32
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(2)全零矩阵 | zero = np.zeros((3,4))
print(zero) | [[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(3) 全1矩阵 | one = np.ones((3,4),dtype=np.int32)
print(one) | [[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(4) 全空矩阵 | empty = np.empty((3,4))
print(empty) | [[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(5) 有序数列 | range = np.arange(10,20,2) # [10,20)
print(range) | [10 12 14 16 18]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(6) 指定shape的矩阵 | shape = np.arange(12).reshape((3,4))
print(shape) | [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(7) 线段 | line = np.linspace(10,20,5)
print(line) | [10. 12.5 15. 17.5 20. ]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
2.3 按位运算 (1) 加减乘除 直接加减乘除是对矩阵各元素同位运算: | a1 = np.array([5,8,11,15,20])
a2 = np.arange(1,6)
b1 = a1 + a2
print(b1)
b2 = a1 - a2
print(b2)
b3 = a1 * a2
print(b3)
b4 = a1 / a2
print(b4) | [ 6 10 14 19 25]
[ 4 6 8 11 15]
[ 5 16 33 60 100]
[5. 4. 3.66666667 3.75 4. ]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(2) 幂次方 (双星号) | b5 = a2**3
print(b5) | [ 1 8 27 64 125]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(4) sin/cos | b6 = 10*np.sin(a2)
print(b6) | [ 8.41470985 9.09297427 1.41120008 -7.56802495 -9.58924275]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(5) 判断 | print(a2<5) | [ True True True True False]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
2.4 矩阵运算 | c1 = np.array([[1,2],[1,2]])
c2 = np.arange(4).reshape((2,2))
print(c1)
print(c2) | [[1 2]
[1 2]]
[[0 1]
[2 3]]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(1) 乘 | c_dot = np.dot(c1,c2)
c_dot2 = c1.dot(c2)
print(c_dot)
print(c_dot2) | [[4 7]
[4 7]]
[[4 7]
[4 7]]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(2) 矩阵求和/最大值/最小值/平均值 | c3 = np.random.random((2,4))
print(c3)
print(np.sum(c3))
print(np.sum(c3,axis=1)) # 行内
print(np.min(c3))
print(np.sum(c3,axis=0)) # 列内
print(np.max(c3))
print(np.mean(c3))
print(c3.mean()) | 0.47663474858414656
0.47663474858414656
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(3) 元素索引 | print(np.argmin(c3))
print(np.argmax(c3)) | 2
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(4) 元素累加 | print(np.cumsum(c3)) | [0.33013443 0.68702991 1.66559172 2.07143305 2.54675138 2.7749667
3.14546112 3.81307799]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(5) 矩阵转置 | print(c3.T) | [[0.33013443 0.47531833]
[0.35689548 0.22821532]
[0.97856181 0.37049442]
[0.40584133 0.66761687]]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(6) 截止(限制矩阵的最大值和最小值) | print(c3.clip(0.25,0.75)) | [[0.33013443 0.35689548 0.75 0.40584133]
[0.47531833 0.25 0.37049442 0.66761687]]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
三 进阶技巧 3.1 索引 索引都是从0开始 | d1 = np.arange(3,15).reshape((3,4))
print(d1)
print(d1[1]) # 整行索引
print(d1[1,:]) # 整行索引
print(d1[1][3]) #
print(d1[1,3]) # 使用这种方法吧
print(d1[:,2]) # 整列索引
print(d1[0:2,2]) #
# 按行打印
for row in d1:
print(row)
# 按列打印
for colum in d1.T:
print(colum)
# 按索引打印
for items in d1.flat: #flat将矩阵展开为行矩阵
print(items) | 3
4
5
6
7
8
9
10
11
12
13
14
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
3.2 合并 | e1 = np.array([1,1,1])
e2 = np.array([2,2,2])
# 上下合并
f1 = np.vstack((e1,e2))
print(f1)
# 左右合并
f2 = np.hstack((e1,e2))
print(f2)
# 行向量转列向量
print(e1[:,np.newaxis])
print(e1.T) # .T适用于矩阵,不适用于向量
# concatenate行列合并0=列,1=行
f3 = np.concatenate((e1,e2),axis=0)
print(f3) | [1 1 1 2 2 2]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
3.3 分割 (1) 等量分割 | g1 = np.arange(12).reshape((3,4))
print(g1)
print(np.split(g1,2,axis=1))
print(np.split(g1,3,axis=0))
print(np.hsplit(g1,2))
print(np.vsplit(g1,3)) | [array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2, 3],
[ 6, 7],
[10, 11]])]
[array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(2) 不等量分割 | print(np.array_split(g1,2,axis=0)) | [array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
3.4 复制 (1) 浅复制 | a = np.arange(4)
b = a
c = a
d = b
a[0] = 15
d[3] = 20
print(a)
print(b)
print(c)
print(d)
print(b is a) | [15 1 2 20]
[15 1 2 20]
[15 1 2 20]
[15 1 2 20]
True
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
(2) 深复制(deep copy) | a = np.arange(6)
b = np.copy(a)
a[0]=666
print(a)
print(b) | [666 1 2 3 4 5]
[0 1 2 3 4 5]
| MIT | 99 Cache/lesson1-1 NumPy.ipynb | Leon-Hou/PythonLearningNotebook |
Filling in Missing Values in Tabular RecordsYou can select Run->Run All Cells from the menu to run all cells in Studio (or Cell->Run All in a SageMaker Notebook Instance). IntroductionMissing data values are common due to omissions during manual entry or optional input. Simple data imputation such as using the median... | # Replace these with your train/test CSV data and target columns.
# If left empty, the sample data set will be used.
data_location = '' # Ex. s3://your_bucket/your_file.csv
target = '' # Specify target column name
if data_location == '':
# Use sample dataset.
dataset_file = 'data/dataset.csv'
... | _____no_output_____ | Apache-2.0 | sagemaker/1_fill_missing_values.ipynb | awslabs/filling-in-missing-values-in-tabular-records |
Inspect the Data | import pandas as pd
data = pd.read_csv(dataset_file)
data | _____no_output_____ | Apache-2.0 | sagemaker/1_fill_missing_values.ipynb | awslabs/filling-in-missing-values-in-tabular-records |
Preprocess DataSome of the entries in the target column are null. We will remove those entries for training/testing. | import numpy as np
def remove_null_rows(data, target):
idx = data[target].notna()
return data.loc[idx]
def split_train_test(data, p=.9):
idx = np.random.choice([True, False], replace = True, size = len(data), p=[.8, .2])
train_df = data.iloc[idx]
test_df = data.iloc[[not i for i in idx]]
retur... | _____no_output_____ | Apache-2.0 | sagemaker/1_fill_missing_values.ipynb | awslabs/filling-in-missing-values-in-tabular-records |
Store Processed Data on S3Now that we have our data in files, we store this data to S3 so we can use SageMaker AutoPilot. | import sagemaker
from sagemaker.s3 import S3Uploader
import json
with open('stack_outputs.json') as f:
sagemaker_configs = json.load(f)
s3_bucket = sagemaker_configs['S3Bucket']
train_data_s3_path = S3Uploader.upload(train_file, 's3://{}/data'.format(s3_bucket))
print('Train data uploaded to: ' + train_data_... | _____no_output_____ | Apache-2.0 | sagemaker/1_fill_missing_values.ipynb | awslabs/filling-in-missing-values-in-tabular-records |
Configure AutoPilotFor the purposes of a demo, we will use only 2 candidates. Remove this parameter to run AutoPilot with its defaults (note: for this data set a full run will take ~ 4 several hours.) | input_data_config = [{
'DataSource': {
'S3DataSource': {
'S3DataType': 'S3Prefix',
'S3Uri': 's3://{}/data/train'.format(s3_bucket)
}
},
'TargetAttributeName': target
}]
output_data_config = {
'S3OutputPath': 's3://{}/data/output'.format(s3_bucket)
}
automl_jo... | _____no_output_____ | Apache-2.0 | sagemaker/1_fill_missing_values.ipynb | awslabs/filling-in-missing-values-in-tabular-records |
Deploy and Endpoint | print("Building endpoint with model {}".format(model))
endpoint_config_name = sagemaker_configs['SageMakerEndpointName'] + '-config'
create_endpoint_config_response = sm.create_endpoint_config(
EndpointConfigName = endpoint_config_name,
ProductionVariants=[{
'InstanceType':'ml.m5.xlarge',
'Initi... | _____no_output_____ | Apache-2.0 | sagemaker/1_fill_missing_values.ipynb | awslabs/filling-in-missing-values-in-tabular-records |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.