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 |
|---|---|---|---|---|---|
Observando a partir da coluna eh_controle True False que criamos | sns.catplot(data=analise_comp, x='composto', y='g0', hue='eh_controle', col='dose', row='tempo', kind='box') | _____no_output_____ | MIT | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 |
Passando ordem explícita para o hue de como ordenar | sns.catplot(data=analise_comp, x='composto', y='g0', hue='tratamento', col='dose', row='tempo', kind='box', hue_order=['com_droga','com_controle']) | _____no_output_____ | MIT | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 |
Dia 5 No último dia da imersão, estamos implementando alguns modelos de machine learning para auxiliar no Drug Discovery | dados_final.head() | _____no_output_____ | MIT | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 |
No train test split, podemos passar algumas variáveis, para que tenhamos um modelo de comparação para os outros modelos que vamos testar (a benchmark), são eles: random_state, que vai travar em determinada acurácia o modelo e stratify que vai garantir que a acurácia seja igual à realidade. | from sklearn.model_selection import train_test_split #biblioteca para separar as bases de dados para treinar e testar a capacidade do modelo
x = dados_final.select_dtypes('float64')
y = dados_final['moa_ativado']
x_treino, x_teste, y_treino, y_teste = train_test_split(x,y, test_size=0.2, stratify=y, random_state=350)... | _____no_output_____ | MIT | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 |
Um método interessante para comparar a capacidade do modelo é o uso de modelo Dummy (bobo e simples) para ver se nosso modelo realmente está fazendo uma previsão melhor que "chutando".Obs: na página do Sklearn sobre o Dummy há um alerta de não usá-lo para problemas reais. | from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score
dummy_model = DummyClassifier('most_frequent')
dummy_model.fit(x_treino, y_treino)
previsao_dummy = dummy_model.predict(x_teste)
accuracy_score(y_teste, previsao_dummy) | _____no_output_____ | MIT | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 |
Com o benchmark feito, agora podemos construir nossa tentativa de um novo modelo com melhor capacidade de previsão, o proposto foi: árvore de decisão (Decision Tree) | from sklearn.tree import DecisionTreeClassifier
x = dados_final.select_dtypes('float64')
y = dados_final['moa_ativado']
x_treino, x_teste, y_treino, y_teste = train_test_split(x,y, test_size=0.2, stratify=y, random_state=350)
tree = DecisionTreeClassifier(max_depth=3)
tree.fit(x_treino, y_treino)
tree.score(x_teste, ... | _____no_output_____ | MIT | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 |
O max_depth é a profundidade dos níveis de decisão da árvore, nesse caso, ela está com 3, isso PODE SER um dos problemas da baixa acurácia.Vamos testar para uma profundidade maior e ver o que acontece. | tree = DecisionTreeClassifier(max_depth=10)
tree.fit(x_treino, y_treino)
tree.score(x_teste, y_teste)
teste=[]
treino=[]
for i in range(1,15):
modelo_arvore = DecisionTreeClassifier(max_depth = i)
modelo_arvore.fit(x_treino, y_treino)
teste.append(modelo_arvore.score(x_teste, y_teste))
treino.append(mo... | _____no_output_____ | MIT | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 |
Podemos ver que ao contrário do esperado, o algoritmo passou a performar melhor no treino e pior no teste, esse é um processo conhecido como 'overfitting', ou uma especialização do algoritmo na base de treino e que portanto, perde a capacidade de generalização. Já que aprofundar não é uma forma sempre perfeita de aplic... | from sklearn.ensemble import RandomForestClassifier
#aplicação é semelhante ao Decision Tree
x = dados_final.drop(columns=['id', 'moa_ativado', 'n_moa', 'tratamento','tempo','dose','composto']) #podemos ver que o Random Forest consegue arcar com tipos diversos de dados
y = dados_final['moa_ativado']
x_treino, x_teste... | _____no_output_____ | MIT | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 |
Testei minha Random Forest para vários parâmetros e cheguei a esses resultados: | random_forest = RandomForestClassifier(n_estimators=1000)
random_forest.fit(x_treino, y_treino)
random_forest.score(x_teste, y_teste)
random_forest = RandomForestClassifier(n_estimators=1000, max_depth=8)
random_forest.fit(x_treino, y_treino)
random_forest.score(x_teste, y_teste)
random_forest = RandomForestClassifier(... | _____no_output_____ | MIT | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 |
ENGR 1330 Computational Thinking with Data Science Copyright © 2021 Theodore G. Cleveland and Farhang ForghanparastLast GitHub Commit Date: 14: Visual display of dataThis lesson is a prelude to the `matplotlib` external module package, used to constructline charts, scatter plots, bar charts, box plot, and hi... | # import the package
from matplotlib import pyplot as plt
# Create two lists; time and speed.
time = [0,1.0,2.0,3.0,4.0,5.0,6.0]
speed = [0,3,7,12,20,30,45.6]
# Create a line chart of speed on y axis and time on x axis
mydata = plt.figure(figsize = (10,5)) # build a square drawing canvass from figure class
plt.plot(ti... | _____no_output_____ | CC0-1.0 | engr1330jb/_build/jupyter_execute/lessons/lesson14/lesson14.ipynb | dustykat/engr-1330-psuedo-course |
--- Line Charts in PandasThe next few examples use graphics in pandas. The example below uses a database table from [census_18.csv](http://54.243.252.9/engr-1330-webroot/1-Lessons/Lesson12/census_18.csv) | import pandas as pd
df = pd.read_csv('census_18.csv')
df.head()
df.plot.line(x="AGE", y="2010", label="Born in 2014", c="blue")
ax = df.plot.line(x="AGE", y="2010", label="Born in 2014", c="blue")
df.plot.line(x="AGE", y="2014", label="Born in 2015", c="red", ax=ax)
import matplotlib.pyplot as plt
age = df['AGE']
bor... | _____no_output_____ | CC0-1.0 | engr1330jb/_build/jupyter_execute/lessons/lesson14/lesson14.ipynb | dustykat/engr-1330-psuedo-course |
References1. Grus, Joel (2015-04-14). Data Science from Scratch: First Principles with Python(Kindle Locations 1190-1191). O'Reilly Media. Kindle Edition. 2. Call Expressions in "Adhikari, A. and DeNero, J. Computational and Inferential Thinking The Foundations of Data Science" https://www.inferentialthinking.com/chap... | # python script to illustrate plotting
# CODE BELOW IS ADAPTED FROM:
# Grus, Joel (2015-04-14). Data Science from Scratch: First Principles with Python
# (Kindle Locations 1190-1191). O'Reilly Media. Kindle Edition.
#
from matplotlib import pyplot as plt # import the plotting library from matplotlibplt.show()
years =... | _____no_output_____ | CC0-1.0 | engr1330jb/_build/jupyter_execute/lessons/lesson14/lesson14.ipynb | dustykat/engr-1330-psuedo-course |
Now lets put the plotting script into a function so we can make line charts of any two numeric lists | def plotAline(list1,list2,strx,stry,strtitle): # plot list1 on x, list2 on y, xlabel, ylabel, title
from matplotlib import pyplot as plt # import the plotting library from matplotlibplt.show()
plt.plot( list1, list2, color ='green', marker ='o', linestyle ='solid') # create a line chart, years on x-axis, gdp on... | <class 'int'>
<class 'float'>
| CC0-1.0 | engr1330jb/_build/jupyter_execute/lessons/lesson14/lesson14.ipynb | dustykat/engr-1330-psuedo-course |
Setting Up Python EnvironmentSetting up Python environment consists of 4 main elements1. Install Python Environment and Necessary Tools2. Execute Python Commands3. Run Sample Python Program4. Install Python PackagesWe will go with Python Anaconda distribution for our course because it has really comprehensive in terms... | import numpy as np
import matplotlib.pyplot as plt
N = 20
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
ax = plt.subplot(111, polar=True)
bars = ax.bar(theta, radii, width=width, bottom=0.0)
# Use custom colors and opacity
for r, bar in zi... | _____no_output_____ | MIT | Python_Basics/02_Setting_Up.ipynb | eneskemalergin/Data_Science_with_Python |
PMOD TC1 Sensor demonstrationThis demonstration shows how to use the PmodTC1. You will also see how to plot a graph using matplotlib.The PmodTC1 is required.The thermocouple sensor is initialized and set to log a reading every 1 second. The temperature of the sensorcan be changed by touching it with warm fingers or b... | from pynq.overlays.base import BaseOverlay
base = BaseOverlay("base.bit")
from pynq.lib import Pmod_TC1
# TC1 sensor is on PMODB
my_tc1 = Pmod_TC1(base.PMODB)
print('Raw Register Value: %08x hex' % my_tc1.read_raw())
print('Ref Junction Temp: %.4f' % my_tc1.read_junction_temperature())
print('Thermocouple Temp: %.2f... | Raw Register Value: 01981c90 hex
Ref Junction Temp: 28.5625
Thermocouple Temp: 25.50
Alarm flags: 00000000 hex
| BSD-3-Clause | boards/MicroZed7010/base/notebooks/pmod/pmod_tc1.ipynb | Picarro-SzeMengTan/MicroZed-PYNQ |
2. Starting logging temperature once every secondUsers can use `set_log_interval_ms` to set the time elapsed during 2 samples. By default it is set to 1 second. | my_tc1.start_log() | _____no_output_____ | BSD-3-Clause | boards/MicroZed7010/base/notebooks/pmod/pmod_tc1.ipynb | Picarro-SzeMengTan/MicroZed-PYNQ |
3. Modifying the temperture* Touch the thermocouple with warm fingers; or* Blow on the thermocouple with cool airStop the logging whenever you are finished trying to change the sensor's value. | my_tc1.stop_log()
log = my_tc1.get_log() | _____no_output_____ | BSD-3-Clause | boards/MicroZed7010/base/notebooks/pmod/pmod_tc1.ipynb | Picarro-SzeMengTan/MicroZed-PYNQ |
4. Plot values over time | %matplotlib inline
import matplotlib.pyplot as plt
from pynq.lib.pmod.pmod_tc1 import reg_to_tc
from pynq.lib.pmod.pmod_tc1 import reg_to_ref
tc = [reg_to_tc(v) for v in log]
ref = [reg_to_ref(v) for v in log]
plt.plot(range(len(tc)), tc, 'ro', label='Thermocouple')
plt.plot(range(len(ref)), ref, 'bo', label='Ref Jun... | _____no_output_____ | BSD-3-Clause | boards/MicroZed7010/base/notebooks/pmod/pmod_tc1.ipynb | Picarro-SzeMengTan/MicroZed-PYNQ |
**Deep Convolutional Generative Adversarial Network (DC-GAN):** DC-GAN is a foundational adversarial framework developed in 2015. It had a major contribution in streamlining the process of designing adversarial frameworks and visualizing intermediate representations, thus, making GANs more accessible to both researche... | from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
tf.__version__
# To generate GIFs for illustration
!pip install imageio
import glob
import imageio
import matplotlib.pyplot as plt
import numpy as np
import os
import PI... | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Load and prepare the datasetYou will use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the MNIST data.You can also repeat the exercise for other avaliable variations of the MNIST dataset such as: EMNIST, Fashio-MNIST or KMNIST. For more detail... | (train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]
BUFFER_SIZE = 60000
BATCH_SIZE = 256
# Batch and shuffle the data
train_datas... | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Create the modelsBoth the generator and discriminator are defined using the [Keras Sequential API](https://www.tensorflow.org/guide/kerassequential_model). The GeneratorThe generator uses `tf.keras.layers.Conv2DTranspose` (fractional-strided convolutional) layers to produce an image from an input noise vector. Start ... | def make_generator_model():
model = tf.keras.Sequential()
model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Reshape((7, 7, 256)))
assert model.output_shape == (None, 7, 7, 256) # Note: N... | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Use the (as yet untrained) generator to create an image. | generator = make_generator_model()
noise = tf.random.normal([1, 100])
generated_image = generator(noise, training=False)
plt.imshow(generated_image[0, :, :, 0], cmap='gray') | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
The DiscriminatorThe discriminator is a CNN-based image classifier. | def make_discriminator_model():
model = tf.keras.Sequential()
model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',
input_shape=[28, 28, 1]))
model.add(layers.LeakyReLU())
model.add(layers.Dropout(0.3))
model.add(layers.Conv2D(128, (5, 5), strides=... | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Use the (as yet untrained) discriminator to classify the generated images as real or fake. The model will be trained to output positive values for real images, and negative values for fake images. | discriminator = make_discriminator_model()
decision = discriminator(generated_image)
print (decision) | tf.Tensor([[0.00197769]], shape=(1, 1), dtype=float32)
| MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Define the loss and optimizersDefine loss functions and optimizers for both models. | # This method returns a helper function to compute the binary cross entropy loss
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True) | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Discriminator lossDefine the discriminator loss function. [Hint](https://www.tensorflow.org/api_docs/python/tf/keras/losses/BinaryCrossentropy): compare the discriminator's predictions on real images to an array of 1s. | def discriminator_loss(real_output, fake_output):
real_loss = cross_entropy(tf.ones_like(real_output), real_output)
fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
total_loss = real_loss + fake_loss
return total_loss | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Generator lossThe generator's loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Again, use the same principle used to define the real_loss to define the generator_loss. | def generator_loss(fake_output):
generator_loss = cross_entropy(tf.ones_like(fake_output), fake_output)
return generator_loss | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
The discriminator and the generator optimizers are different since both networks are trained separately. Hint: use Adam optimizers. Experiment with the learning rates. | generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4) | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Save checkpointsThis notebook also demonstrates how to save and restore models, which can be helpful in case a long running training task is interrupted (especially for larger datasets). | checkpoint_dir = './training_checkpoints'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
discriminator_optimizer=discriminator_optimizer,
generator=generator,
... | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Define the training loop | EPOCHS = 100
noise_dim = 100
num_examples_to_generate = 16 # For visualization
# We will reuse this noise_vector overtime (so it's easier)
# to visualize progress in the animated GIF)
noise_vector = tf.random.normal([num_examples_to_generate, noise_dim]) | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
The training loop should begin with generator receiving a random vector as input. That vector will be used to produce an image. The discriminator should then be used to classify real images (drawn from the training set) and fakes images (produced by the generator). The loss will be calculated for each of these models, ... | # Notice the use of `tf.function`
# This annotation causes the function to be "compiled".
@tf.function
def train_step(images):
noise = tf.random.normal([BATCH_SIZE, noise_dim])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
# Generator output
generated_images = generator(noise,... | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
**Generate and save images** | def generate_and_save_images(model, epoch, test_input):
# Notice `training` is set to False.
# This is so all layers run in inference mode (batchnorm).
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
plt... | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Train the modelCall the `train()` method defined above to train the generator and discriminator simultaneously. Note, training GANs can be tricky. It's important that the generator and discriminator do not overpower each other (e.g., that they train at a similar rate).At the beginning of the training, the generated im... | %%time
train(train_dataset, EPOCHS) | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Restore the latest checkpoint. | checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir)) | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Create a GIF | # Display a single image using the epoch number
def display_image(epoch_no):
return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))
display_image(EPOCHS) | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Use imageio to create an animated gif using the images saved during training. | anim_file = 'dcgan.gif'
with imageio.get_writer(anim_file, mode='I') as writer:
filenames = glob.glob('image*.png')
filenames = sorted(filenames)
last = -1
for i,filename in enumerate(filenames):
frame = 8*(i**0.25)
if round(frame) > round(last):
last = frame
else:
continue
image = ... | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
If you're working in Colab you can download the animation with the code below: | try:
from google.colab import files
except ImportError:
pass
else:
files.download(anim_file) | _____no_output_____ | MIT | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning |
Code Equivalence | import ast
import astpretty
import showast
import sys
import re
sys.path.insert(0, '../preprocess/')
sys.path.insert(0, '../../coarse2fine.git/src')
from sketch_generation import Sketch
from tree import SketchRepresentation
import table
SKP_WORD = '<sk>'
RIG_WORD = '<]>'
LFT_WORD = '<[>'
def is_code_eq(tokens1, toke... | _____no_output_____ | MIT | notebooks/code_equivalence.ipynb | code-gen/exploration |
Eval framework | ## TODO | _____no_output_____ | MIT | notebooks/code_equivalence.ipynb | code-gen/exploration |
Import Scikit Learn, Pandas and Numpy | import sklearn
import numpy as np
import pandas as pd | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
1. Read the Dataset using Pandas | data = pd.read_csv("data/amazon_baby.csv")
data | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
2. Exploratory Data Analysis | data.head()
data.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 183531 entries, 0 to 183530
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 name 183213 non-null object
1 review 182702 non-null object
2 rating 183531 non-null int64
dtypes: int64(1), object(... | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
The first observation is that we have cells with null review and they have rating. Those rows which contain those cells should be dropped from the data as they will confuse the model by acting like noise. | data.describe()
import matplotlib.pyplot as plt
import seaborn as sns
fig = sns.countplot(x='rating', data=data) | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
The second observation is that we have imbalanced classes in our Data. At this project we will just use different metrics to measure model performance besides accuracy like recall, $F_{1}$ score and ROC. 3. Data Preprocessing Drop null rows using DataFrame.dropna() | data.dropna(inplace=True)
data.reset_index(drop=True, inplace=True)
data.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 182384 entries, 0 to 182383
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 name 182384 non-null object
1 review 182384 non-null object
2 rating 182384 non-null int64
dtypes: int64(1), object(... | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
Ignore the three stars ratings.Because they are neutral, and dropp those rows with neutral reviews.This step is done before building the word count vector to save memory space and computational power by not getting the word count vector for those neutral reviews. | data = data[data['rating'] != 3]
data.reset_index(drop=True, inplace=True)
data.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 165679 entries, 0 to 165678
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 name 165679 non-null object
1 review 165679 non-null object
2 rating 165679 non-null int64
dtypes: int64(1), object(... | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
Build word count vectors | import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
def dictionarize(row):
cv = CountVectorizer(
analyzer = "word",
token_pattern = '[a-zA-Z0-9$&+:;=?@#|<>.^*()%!]+'
)
text = [row.loc['review']]
cv_fit=cv.fit_transform(text)
w... | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
4. Train-Test Split | from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(data, test_size=0.2, random_state=42) | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
5. Logistic Regression Pipeline | from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer
sentiment_pipeline = Pipeline(
[
('Count_Vectorizer', CountVectorizer()),
('TF-IDF', ... | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
6. Pipeline Training | sentiment_pipeline.fit(train_set['review'], train_set['sentiment']) | [Pipeline] .. (step 1 of 3) Processing Count_Vectorizer, total= 10.9s
[Pipeline] ............ (step 2 of 3) Processing TF-IDF, total= 1.2s
[Pipeline] (step 3 of 3) Processing Logistic_Regression, total= 19.2s
| MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
Plot Learning Curves | from sklearn.model_selection import learning_curve
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
"""
Generate a simple plot of the test and traning learning curve.
Parameters
----------
estimator : object... | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
7. Metrics | from sklearn.metrics import classification_report
y_pred = sentiment_pipeline.predict(test_set['review'])
print('Classification report:\n\n{}'.format(
classification_report(test_set['sentiment'], y_pred))
)
plot_learning_curve(sentiment_pipeline\
, 'Pipeline Learning Curves', train_set['review'... | The accuracy of the sentiment_pipeline is 0.9352064220183486
| MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
Assignment 1. Use .apply() to build a new feature with the counts for each of the selected_words. | selected_words = ['awesome', 'great', 'fantastic', 'amazing',\
'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate']
def dictionary_count(row):
count_list = []
for word in selected_words:
count_list.append(row['word_count'].get(word, 0))
dictionary = dict(zip(selected_word... | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
2. Create a new sentiment analysis model using only the selected_words as features | from sklearn.preprocessing import StandardScaler
from sklearn.feature_extraction import DictVectorizer
from sklearn.preprocessing import Normalizer
selected_words_pipeline = Pipeline(
[
('Dictionary_Vectorizer', DictVectorizer(sparse=False, sort=False)),
('Scaler', StandardScaler()),
('Logi... | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
Train-Test split | train_set, test_set = train_test_split(data, test_size=0.2, random_state=15) | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
Training the selected_words_pipeline | selected_words_pipeline.fit(train_set['selected_words'], train_set['sentiment']) | [Pipeline] (step 1 of 3) Processing Dictionary_Vectorizer, total= 1.8s
[Pipeline] ............ (step 2 of 3) Processing Scaler, total= 0.0s
[Pipeline] (step 3 of 3) Processing Logistic_Regression, total= 0.3s
| MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
selected_words_pipeline Metrics | from sklearn.metrics import classification_report
y_pred = selected_words_pipeline.predict(test_set['selected_words'])
print('Classification report:\n\n{}'.format(
classification_report(test_set['sentiment'], y_pred))
)
disp = plot_learning_curve(selected_words_pipeline, 'selected_words_pipeline Learning Curves', ... | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
3. Comparing the accuracy of different sentiment analysis models: Using .predict()In this task the accuracy of the sentiment_pipeline, selected_words_pipeline and majority_class. The first one has been calculated above. | from sklearn.metrics import accuracy_score
y_pred_selected_words = selected_words_pipeline.predict(test_set['selected_words'])
y_true_selected_words = test_set['sentiment']
accuracy_score(y_true_selected_words, y_pred_selected_words)
print('The accuracy of the selected_words_pipeline is',
accuracy_score(y_true_s... | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
4. Interpreting the difference in performance between the models | diaper_champ_reviews = data.loc[data['name']=='Baby Trend Diaper Champ',\
['review', 'selected_words', 'sentiment']]
diaper_champ_reviews
diaper_champ_reviews['predicted_sentiment'] = \
sentiment_pipeline.predict_proba(diaper_champ_reviews['review'])[:, 1].tol... | _____no_output_____ | MIT | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization |
MCPC rehearsal problem Oct 25 2017 at UCSY Problem E: Stacking Plates Input format- 1st Line: 1 integer, Number of Test Case, each Test Case has following data + 1 Line: 1 integer, **n**(Number of Stacks) + **n** Lines: first integer: **h** (Number of Plates), and **h** integers (Plate size) Output formatCase: ... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
2017 MCPC at UCSY
Problem-E: Stacking Plates
'''
import sys
class TestCase():
pass
class Plates():
# Groupt of same radius plates in merged stack
# id_list: list of stack ID
def __init__(self, radius, id_list):
self.radius = radius
... | Case 1:5
Case 2:2
Case 3:5
Case 4:8
Case 5:3
| MIT | MCPC-Rehearsal-E.ipynb | ShinjiKatoA16/mcpc2017ucsy |
- 패혈증 진단받은 환자수, 입원수 | pd.read_sql(
"""
select count(distinct hadm_id), count(distinct icustay_id) from sepsis3 where excluded=0
""", engine) | _____no_output_____ | Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
- ICU, 입원 기간의 최소, 최대 | pd.read_sql(
"""
select min(icu_los), max(icu_los), min(hosp_los), max(hosp_los) from sepsis3 where excluded=0
""", engine) | _____no_output_____ | Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
라벨- 사망: 원내 사망, 30일 이내 사망 | label = get_mortality_label()
label.head() | _____no_output_____ | Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
변수 : 인구통계, 입원, 진단 | demo = get_demo()
demo.head()
admit = get_admit()
admit.head()
com = get_comorbidity()
com.head() | _____no_output_____ | Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
변수 : 바이탈사인, 투약, 검사, 승압제 | gcs = get_gcs()
gcs.head()
vital = get_vitalsign()
vital.head()
drug = get_drug()
drug.head()
lab = get_lab()
lab.head()
vaso = get_vaso()
vaso.head()
sepsis = get_sepsis()
sepsis.head()
data_frames = [
label,
demo,
admit,
com,
gcs,
vital,
drug,
lab,
vaso,
sepsis
]
df_merged = re... | _____no_output_____ | Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
- hdf 포맷으로 저장 | filename_sepsis = "mimiciii_sepsis_mortality.h5"
df_merged.to_hdf(filename_sepsis, key='all') | _____no_output_____ | Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
탐색 | df = pd.read_hdf(filename_sepsis, key='all')
df.head() | _____no_output_____ | Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
Correlation mortality and features | labels = ['hospital_expire_flag', 'thirtyday_expire_flag']
for f in data_frames[1:]:
fig_corr_heatmap(labels, df, f) | _____no_output_____ | Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
Feature, Label | y = df[labels].groupby(level=0).agg('max').fillna(0).values
X = df.drop(columns=labels).groupby(level=0).agg(['mean','max', 'min']).fillna(0)
X.shape, y.shape
y.sum(axis=0) / y.shape[0] | _____no_output_____ | Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
In-hospital Death - Train and Validation | from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score, confusion_matrix, f1_score, accuracy_score
import numpy as np
random_state = 2
X_train, X_te... | auroc : 0.8163843583591641
accuracy: 0.9559072922555116
| Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
30day Death - Train and Validation | X_train, X_test, y_train, y_test = train_test_split(X, y[:, 1], test_size=0.3, random_state=random_state)
clf = LogisticRegression(penalty='l1',
solver='liblinear',
# tol=1e-6,
# max_iter=int(1e6),
# warm_start=True,
... | auroc : 0.7760491255033056
accuracy: 0.9355568117580554
| Apache-2.0 | notebook/sepsis-mortality.ipynb | seoulai/mdml |
[View in Colaboratory](https://colab.research.google.com/github/tjh48/DCGAN/blob/master/dcgan.ipynb) First we'll import all the tools we need and set some initial parameters | import numpy as np
from sklearn.utils import shuffle
import matplotlib.pyplot as plt
import os
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import EarlyStopping
from keras.datasets import mnist
from keras.utils import np_utils
from keras.initializers import ... | _____no_output_____ | Unlicense | dcgan.ipynb | tjh48/DCGAN |
This is an optional code block for creating an ngrok tunnel to a tensorboard instance. Useful for running on cloud services | if not os.path.isfile('./ngrok'):
!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip ngrok-stable-linux-amd64.zip
get_ipython().system_raw(
'tensorboard --logdir ' + LOG_DIR + ' --host 0.0.0.0 --port 6006 &'
)
get_ipython().system_raw('./ngrok http 6006 &')
! curl -s http://loca... | http://e37a75c1.ngrok.io
| Unlicense | dcgan.ipynb | tjh48/DCGAN |
This code block imports manual logging functionality and defines a couple of extra functions required for GANs in Keras, since we need to use train_on_batch rather than fit. train_on_batch does not log automatically to tensorboard, hence we'll perform the logging manually. | if os.path.isfile('tensorboard_logging.py'): os.remove('tensorboard_logging.py')
!wget https://gist.githubusercontent.com/tjh48/bf56684801d641544e49a5e66bf15fba/raw/9c6e04cca49288ab0920d9a3aeb3283da13d1a39/tensorboard_logging.py
import tensorboard_logging as tbl
subdir = LOG_DIR + "/" + logSub + '_' + str(int(np.rou... | --2018-08-29 20:50:54-- https://gist.githubusercontent.com/tjh48/bf56684801d641544e49a5e66bf15fba/raw/9c6e04cca49288ab0920d9a3aeb3283da13d1a39/tensorboard_logging.py
Resolving gist.githubusercontent.com (gist.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...
Connecting to gist.githubuserc... | Unlicense | dcgan.ipynb | tjh48/DCGAN |
Next we'll download the MNIST data set, in lieu of anything more interesting to work with.We'll also define a function for plotting MNIST-type images so that we can see the output of the generator. | from keras.datasets import mnist
(x_train, _), (x_test, _) = mnist.load_data()
# just for fun, you can drop in the fashion_mnist dataset here instead of standard mnist
#from keras.datasets import fashion_mnist
#(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
x_train = x_train.astype('float32') / 127... | _____no_output_____ | Unlicense | dcgan.ipynb | tjh48/DCGAN |
Here's a function to define the generator layer. We want to upsample from a random vector to an image, with a convolutional layer at each upsampling. Each upsampling with a 2x2 shape doubles the size of the image, so we can start with with a low-dimensional image with a large number of features and upsample until we ge... | def disfun(inputImage, initialFeatures= 64, numLayers = 2):
x = inputImage
for ii in range(numLayers):
x = Conv2D(initialFeatures * np.power(2, ii), kernel_size = 5, padding='same', strides=(2,2), use_bias = useBias)(x)
x = LeakyReLU(0.2)(x)
if useBN: x = BatchNormalization()(x)
x = Flatten()(x)
x =... | _____no_output_____ | Unlicense | dcgan.ipynb | tjh48/DCGAN |
Now comes the conceptually tricky bit. The best way I've found to think about this is found on ctmakro's github page:This map of the model makes it clear what we're trying to do in each training pass. We generate a ran... | optimizer = Adam(0.0002, 0.5)
def dcganModels():
inputRandom = Input(shape=(100,))
generator = Model(inputRandom, genfun(inputRandom, initialFeatures = 128, outputDim = x_train.shape[2], outputFeatures = x_train.shape[3]))
generator.compile(loss = 'binary_crossentropy', optimizer = optimizer)
inputImage = ... | _____no_output_____ | Unlicense | dcgan.ipynb | tjh48/DCGAN |
Next we'll create a function that creates the data for each training batch. One trick for improving performance of GANs is to add random noise to both the true and fake images as they go into the discriminator. This weakens the discriminator by creating more overlap between (the distribution of) true and fake images (h... | def makeBatch(x_train, batchSize = 128, noisyEpochs = 0.0):
noise_factor = 0
if noisyEpochs > 0:
noise_factor = np.clip(1 - i/noisyEpochs, 0, 1)
trueImages = x_train[np.random.randint(0, x_train.shape[0], batchSize),]
trueImages = trueImages + np.random.normal(loc=0.0, scale=noise_factor, size=trueImages.sh... | _____no_output_____ | Unlicense | dcgan.ipynb | tjh48/DCGAN |
Now we can train the models. We first generate the fake images, then train the discriminator on these and an equal sized random batch of the true images. Then we train the generator. Every fifty epochs, we'll take a look at a sample of the current output and log the various metrics of interest. | nbEpoch = 10000
dLoss = []
gLoss = []
from IPython.display import clear_output, Image
gan, discriminator, generator = dcganModels()
batchSize = 128
for epoch in range(nbEpoch):
randomInput, trueImages, generatedImages = makeBatch(x_train)
discriminatorLoss = 0.5 * (discriminator.train_on_batch(generatedImages, ... | _____no_output_____ | Unlicense | dcgan.ipynb | tjh48/DCGAN |
Preprocessing | # Import our dependencies
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import pandas as pd
import tensorflow as tf
# Import and read the charity_data.csv.
import pandas as pd
application_df = pd.read_csv("Resources/charity_data.csv")
application_df.head()
# Dr... | _____no_output_____ | ADSL | Starter_Code.ipynb | Tania612/deep-learning |
Compile, Train and Evaluate the Model | # # Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer.
# number_input_features = len( X_train_scaled[0])
# hidden_nodes_layer1=88
# hidden_nodes_layer2=44
# attempt 2
number_input_features = len( X_train_scaled[0])
hidden_nodes_layer1=10
hidden_nodes_layer2=20
# # ... | _____no_output_____ | ADSL | Starter_Code.ipynb | Tania612/deep-learning |
Puts ALL WISE Astrometry reference catalogues into GAIA reference frameThe WISE catalogues were produced by ../dmu16_allwise/make_wise_samples_for_stacking.cshIn the catalogue, we keep:- The position;- The chi^2This astrometric correction is adapted from master list code (dmu1_ml_XMM-LSS/1.8_SERVS.ipynb) written by Y... | field="XMM-LSS"
from herschelhelp_internal import git_version
print("This notebook was run with herschelhelp_internal version: \n{}".format(git_version()))
%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
plt.rc('figure', figsize=(10, 6))
from collections import OrderedD... | _____no_output_____ | MIT | dmu16/dmu16_allwise/WISE_2_GAIA-XMM-LSS.ipynb | djbsmith/dmu_products |
III - Astrometry correctionWe match the astrometry to the Gaia one. We limit the Gaia catalogue to sources with a g band flux between the 30th and the 70th percentile. Some quick tests show that this give the lower dispersion in the results. | #gaia = Table.read("./dmu17_XMM-LSS/data/GAIA_XMM-LSS.fits")
print(f"../../dmu0/dmu0_GAIA/data/GAIA_{field}.fits")
gaia = Table.read(f"../../dmu0/dmu0_GAIA/data/GAIA_{field}.fits")
gaia_coords = SkyCoord(gaia['ra'], gaia['dec'])
nb_astcor_diag_plot(wise_coords.ra, wise_coords.dec,
gaia_coords.ra, g... | /Users/sjo/anaconda3/envs/herschelhelp_internal/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | dmu16/dmu16_allwise/WISE_2_GAIA-XMM-LSS.ipynb | djbsmith/dmu_products |
V - Saving to disk | wise.write(f"../dmu16_allwise/data/Allwise_PSF_stack_GAIA_{field}.fits", overwrite=True) | _____no_output_____ | MIT | dmu16/dmu16_allwise/WISE_2_GAIA-XMM-LSS.ipynb | djbsmith/dmu_products |
This is the post about **Introduction to Data Scinece**, I am going to write about* handling tabular/dataframe* data in python3. Importing Data | import pandas as pd
df = pd.read_csv('/kaggle/input/california-housing-prices/housing.csv')
display(df.head()) | _____no_output_____ | MIT | Jupyter-Notebook/Intro to Data Science/intro-to-data-science-applying-functions-to-data.ipynb | shohan4556/machine-learning-course-notes |
During data analysis, we need to use our data to perform some calculations and generate some new data or output from it. Pandas makes it very easy to apply user-defined operations, in Python terminology, on individual data items, rows, and columns of a dataframe.Pandas has an **apply** function which applies the provid... | def convert(n):
return n * 10000
converted = df['median_income'].apply(convert)
display(converted.head())
# update value
df['median_income'] = converted
display(df.head()) | _____no_output_____ | MIT | Jupyter-Notebook/Intro to Data Science/intro-to-data-science-applying-functions-to-data.ipynb | shohan4556/machine-learning-course-notes |
Converting numerical values to categories ----During analysis, sometimes we want to classify our data into separate classes based on some criteria. For instance, we might want to separate these housing blocks into three distinct categories based on the median income of the households i.e.* High-incomes* Moderate-incom... | def category(n):
value = n / 10000
if value > 10:
return 'high-income'
elif value > 2 and value < 10:
return 'moderate-income'
else:
return 'low-income'
categories = df['median_income'].apply(category)
df['income-category'] = categories
display(df.head())
print(df['income-... | _____no_output_____ | MIT | Jupyter-Notebook/Intro to Data Science/intro-to-data-science-applying-functions-to-data.ipynb | shohan4556/machine-learning-course-notes |
04_05: special arrays | import math
import collections
import numpy as np
import pandas as pd
import matplotlib.pyplot as pp
%matplotlib inline
discography = np.load('discography.npy')
discography
discography[0]
discography[0][0]
discography[0][1]
discography[0]['title']
discography['title']
minidisco = np.zeros(len(discography), dtype=[('t... | _____no_output_____ | CC0-1.0 | chapter4/04_05_special.ipynb | yoji-toriumi/Python_Data_Analysis |
-> Associated lecture videos: in Neural Networks/Lesson 4 - Deep Learning with PyTorch: video 4, video 5, video 6, video 7 Introduction to Deep Learning with PyTorchIn this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways... | # First, import PyTorch
import torch
def activation(x):
""" Sigmoid activation function
Arguments
---------
x: torch.Tensor
"""
return 1/(1+torch.exp(-x))
### Generate some data
torch.manual_seed(7) # Set the random seed so things are predictable
# Features are 5 random norm... | _____no_output_____ | MIT | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning |
Above I generated data we can use to get the output of our simple network. This is all just random for now, going forward we'll start using normal data. Going through each relevant line:`features = torch.randn((1, 5))` creates a tensor with shape `(1, 5)`, one row and five columns, that contains values randomly distrib... | ## Calculate the output of this network using the weights and bias tensors
h = torch.sum(features * weights) + bias
output_y = activation(h)
# or using (features * weights).sum() instead of torch.sum()
### Recall
# features * weights -> this multiplies each element (5 in total) of '... | _____no_output_____ | MIT | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning |
You can do the multiplication and sum in the same operation using a matrix multiplication, instead of writing `torch.sum(features * weights)`. In general, you'll want to use matrix multiplications since they are more efficient and accelerated using modern libraries and high-performance computing on GPUs.Here, we want t... | ## Calculate the output of this network using matrix multiplication
h = torch.mm(features, weights.view(5,1)) + bias
output_y = activation(h)
output_y | _____no_output_____ | MIT | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning |
Stack them up! -> Multilayer neural networksThat's how you can calculate the output for a single neuron. The real power of this algorithm happens when you start stacking these individual units into layers and stacks of layers, into a network of neurons. The output of one layer of neurons becomes the input for the nex... | ### Generate some data
torch.manual_seed(7) # Set the random seed so things are predictable
# Features are 3 random normal variables: x1, x2 and x3
features = torch.randn((1, 3))
# Define the size of each layer in our network
n_input = features.shape[1] # Number of input units, must match number of input features... | _____no_output_____ | MIT | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning |
> **Exercise:** Calculate the output for this multi-layer network using the weights `W1` & `W2`, and the biases, `B1` & `B2`. | ## Your solution here
H = activation(torch.mm(features, W1) + B1) # 2D tensor (shape: 1,2) containing h1 and h2
output_y = activation(torch.mm(H, W2) + B2) # 1D tensor (shape: 1,1) containg the single ouput
output_y | _____no_output_____ | MIT | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning |
If you did this correctly, you should see the output `tensor([[ 0.3171]])`.The number of hidden units is a parameter of the network, often called a **hyperparameter** to differentiate it from the weights and biases parameters. As you'll see later when we discuss training a neural network, the more hidden units a networ... | import numpy as np
a = np.random.rand(4,3)
a # a nd numpy array
b = torch.from_numpy(a)
b # a 2D tensor
b.numpy() | _____no_output_____ | MIT | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning |
The memory is shared between the Numpy array and Torch tensor, so if you change the values in-place of one object, the other will change as well. | # Multiply PyTorch Tensor by 2, in place (symbol: _)
b.mul_(2) # in place multiplication by 2
# Numpy array matches new values from Tensor b
a | _____no_output_____ | MIT | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning |
import pandas as pd
import matplotlib.pyplot as plt
import scipy.optimize as so
import numpy as np
Data = pd.read_csv(r'data7_1.csv')
X = Data.x
Y = Data.y
'''
a_sol, a_cov = so.curve_fit(f, X, Y)
'''
plt.plot(X,Y,'.r')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid()
plt.title('Get data from csv file by using Pandas')
... | _____no_output_____ | CC0-1.0 | L10_1.ipynb | m0fauzi/BEP2073_S21 | |
import tensorflow as tf
import numpy as np
from tensorflow import keras
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
ys = np.array([-2.0, 2.0, 5.0, 8.0, 11.0, 14.0], dtype=float)
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtyp... | [[2.9803178]]
| MIT | compare_numb.ipynb | kOllA666/ADMSync | |
Chapter 7 - Iterations ------------------------------- Computers do not get bored. If you want the computer to repeat a certain task hundreds of thousands of times, it does not protest. Humans hate too much repetition. Therefore, repetitious tasks should be performed by computers. All programming languages support rep... | from pcinput import getInteger
num1 = getInteger( "Number 1: " )
num2 = getInteger( "Number 2: " )
num3 = getInteger( "Number 3: " )
num4 = getInteger( "Number 4: " )
num5 = getInteger( "Number 5: " )
print( "Total is", num1 + num2 + num3 + num4 + num5 ) | _____no_output_____ | MIT | notebooks uni/PC07 - Iterations.ipynb | tintin10q/RandomPythonProjects |
But what if I want you to ask the user for 500 numbers? Are you going to create a block of code of more than 500 lines long? Surely there must be an easier way to do this?Of course there is. You can use a loop to do this. The first loop I am going to present to you is the `while` loop. A `while` statement is quite simi... | num = 1
while num <= 5:
print( num )
num += 1
print( "Done" ) | _____no_output_____ | MIT | notebooks uni/PC07 - Iterations.ipynb | tintin10q/RandomPythonProjects |
This code is represented by the flow chart below.Figure 7.1: Simple while-loop. It is crucial that you understand this code, so let's discuss it step by step.The first line initializes a variable `num`. This is the variable that the code will print, so it is initialized to `1`, as `1` is the first value that must be pr... | from pcinput import getInteger
total = 0
count = 0
while count < 5:
total += getInteger( "Please give a number: " )
count += 1
print( "Total is", total ) | _____no_output_____ | MIT | notebooks uni/PC07 - Iterations.ipynb | tintin10q/RandomPythonProjects |
Study this code closely. There are two variables used. `total` is used to add up the five numbers that the user enters. It is started at zero, as at the start of the code the user has not yet entered any numbers, so the total is still zero. `count` is used to count how often the code has gone through the loop. Since th... | from pcinput import getInteger
num = -1
total = 0
while num != 0:
num = getInteger( "Enter a number: " )
total += num
print( "Total is", total ) | _____no_output_____ | MIT | notebooks uni/PC07 - Iterations.ipynb | tintin10q/RandomPythonProjects |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.