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 |
|---|---|---|---|---|---|
The syllables of the word `ભાવના` will thus be: | print(gujarati_syllables) | ['ભા', 'વ', 'ના']
| MIT | languages/south_asia/Gujarati_tutorial.ipynb | glaserti/tutorials |
Project 3: Implement SLAM --- Project OverviewIn this project, you'll implement SLAM for robot that moves and senses in a 2 dimensional, grid world!SLAM gives us a way to both localize a robot and build up a map of its environment as a robot moves and senses in real-time. This is an active area of research in the fie... | import numpy as np
from helpers import make_data
# your implementation of slam should work with the following inputs
# feel free to change these input values and see how it responds!
# world parameters
num_landmarks = 5 # number of landmarks
N = 20 # time steps
world_size = ... |
Landmarks: [[12, 44], [62, 98], [19, 13], [45, 12], [7, 97]]
Robot: [x=69.61429 y=95.52181]
| MIT | 3. Landmark Detection and Tracking.ipynb | mitsunami/SLAM |
A note on `make_data`The function above, `make_data`, takes in so many world and robot motion/sensor parameters because it is responsible for:1. Instantiating a robot (using the robot class)2. Creating a grid world with landmarks in it**This function also prints out the true location of landmarks and the *final* robot... | # print out some stats about the data
time_step = 0
print('Example measurements: \n', data[time_step][0])
print('\n')
print('Example motion: \n', data[time_step][1]) | Example measurements:
[[0, -38.94955155697709, -7.2954814723926384], [1, 11.679250951477753, 46.597074026819655], [2, -30.450451619432496, -37.41378043748835], [3, -4.896442127766177, -38.434283116881524], [4, -43.08341118340028, 47.17699212819607]]
Example motion:
[-15.396274422511562, -12.765372454680524]
| MIT | 3. Landmark Detection and Tracking.ipynb | mitsunami/SLAM |
Try changing the value of `time_step`, you should see that the list of measurements varies based on what in the world the robot sees after it moves. As you know from the first notebook, the robot can only sense so far and with a certain amount of accuracy in the measure of distance between its location and the location... | def initialize_constraints(N, num_landmarks, world_size):
''' This function takes in a number of time steps N, number of landmarks, and a world_size,
and returns initialized constraint matrices, omega and xi.'''
## Recommended: Define and store the size (rows/cols) of the constraint matrix in a var... | _____no_output_____ | MIT | 3. Landmark Detection and Tracking.ipynb | mitsunami/SLAM |
Test as you goIt's good practice to test out your code, as you go. Since `slam` relies on creating and updating constraint matrices, `omega` and `xi` to account for robot sensor measurements and motion, let's check that they initialize as expected for any given parameters.Below, you'll find some test code that allows ... | # import data viz resources
import matplotlib.pyplot as plt
from pandas import DataFrame
import seaborn as sns
%matplotlib inline
# define a small N and world_size (small for ease of visualization)
N_test = 5
num_landmarks_test = 2
small_world = 10
# initialize the constraints
initial_omega, initial_xi = initialize_co... | _____no_output_____ | MIT | 3. Landmark Detection and Tracking.ipynb | mitsunami/SLAM |
--- SLAM inputs In addition to `data`, your slam function will also take in:* N - The number of time steps that a robot will be moving and sensing* num_landmarks - The number of landmarks in the world* world_size - The size (w/h) of your world* motion_noise - The noise associated with motion; the update confidence fo... | ## TODO: Complete the code to implement SLAM
## slam takes in 6 arguments and returns mu,
## mu is the entire path traversed by a robot (all x,y poses) *and* all landmarks locations
def slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise):
## TODO: Use your initilization to create constr... | _____no_output_____ | MIT | 3. Landmark Detection and Tracking.ipynb | mitsunami/SLAM |
Helper functionsTo check that your implementation of SLAM works for various inputs, we have provided two helper functions that will help display the estimated pose and landmark locations that your function has produced. First, given a result `mu` and number of time steps, `N`, we define a function that extracts the po... | # a helper function that creates a list of poses and of landmarks for ease of printing
# this only works for the suggested constraint architecture of interlaced x,y poses
def get_poses_landmarks(mu, N):
# create a list of poses
poses = []
for i in range(N):
poses.append((mu[2*i].item(), mu[2*i+1].it... | _____no_output_____ | MIT | 3. Landmark Detection and Tracking.ipynb | mitsunami/SLAM |
Run SLAMOnce you've completed your implementation of `slam`, see what `mu` it returns for different world sizes and different landmarks! What to ExpectThe `data` that is generated is random, but you did specify the number, `N`, or time steps that the robot was expected to move and the `num_landmarks` in the world (whi... | # call your implementation of slam, passing in the necessary parameters
mu = slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise)
# print out the resulting landmarks and poses
if(mu is not None):
# get the lists of poses and landmarks
# and print them out
poses, landmarks = get_poses_l... |
Estimated Poses:
[50.000, 50.000]
[35.859, 35.926]
[21.364, 23.942]
[6.980, 11.344]
[24.945, 20.405]
[43.518, 30.202]
[62.058, 37.373]
[79.693, 44.655]
[95.652, 52.956]
[77.993, 43.819]
[60.450, 33.659]
[41.801, 24.066]
[23.993, 15.292]
[7.068, 7.322]
[23.995, -0.325]
[32.465, 17.730]
[41.235, 37.599]
[50.421, 57.362... | MIT | 3. Landmark Detection and Tracking.ipynb | mitsunami/SLAM |
Visualize the constructed worldFinally, using the `display_world` code from the `helpers.py` file (which was also used in the first notebook), we can actually visualize what you have coded with `slam`: the final position of the robot and the positon of landmarks, created from only motion and measurement data!**Note th... | # import the helper function
from helpers import display_world
# Display the final world!
# define figure size
plt.rcParams["figure.figsize"] = (20,20)
# check if poses has been created
if 'poses' in locals():
# print out the last pose
print('Last pose: ', poses[-1])
# display the last position of the ro... | Last pose: (67.35712814937992, 93.71611790835976)
| MIT | 3. Landmark Detection and Tracking.ipynb | mitsunami/SLAM |
Question: How far away is your final pose (as estimated by `slam`) compared to the *true* final pose? Why do you think these poses are different?You can find the true value of the final pose in one of the first cells where `make_data` was called. You may also want to look at the true landmark locations and compare the... | # Here is the data and estimated outputs for test case 1
test_data1 = [[[[1, 19.457599255548065, 23.8387362100849], [2, -13.195807561967236, 11.708840328458608], [3, -30.0954905279171, 15.387879242505843]], [-12.2607279422326, -15.801093326936487]], [[[2, -0.4659930049620491, 28.088559771215664], [4, -17.8663823748909... |
Estimated Poses:
[50.000, 50.000]
[69.181, 45.665]
[87.743, 39.703]
[76.270, 56.311]
[64.317, 72.176]
[52.257, 88.154]
[44.059, 69.401]
[37.002, 49.918]
[30.924, 30.955]
[23.508, 11.419]
[34.180, 27.133]
[44.155, 43.846]
[54.806, 60.920]
[65.698, 78.546]
[77.468, 95.626]
[96.802, 98.821]
[75.957, 99.971]
[70.200, 81.... | MIT | 3. Landmark Detection and Tracking.ipynb | mitsunami/SLAM |
In this notebook we investigate a designed simple Inception network on PDU data | %reload_ext autoreload
%autoreload 2
%matplotlib inline | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Importing the libraries | import torch
import torch.nn as nn
import torch.utils.data as Data
from torch.autograd import Function, Variable
from torch.optim import lr_scheduler
import torchvision
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
from pathlib import Path
import os
import copy
import math
import ... | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Checking whether the GPU is active | torch.backends.cudnn.enabled
torch.cuda.is_available()
torch.cuda.init() | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Dataset paths | PATH = Path("/home/saman/Saman/data/PDU_Raw_Data01/Test06_600x30/")
train_path = PATH / 'train' / 'Total'
valid_path = PATH / 'valid' / 'Total'
test_path = PATH / 'test' / 'Total' | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Model parameters | Num_Filter1= 16
Num_Filter2= 64
Ker_Sz1 = 5
Ker_Sz2 = 5
learning_rate= 0.0001
Dropout= 0.2
BchSz= 32
EPOCH= 5 | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Data Augmenation | # Mode of transformation
transformation = transforms.Compose([
transforms.RandomVerticalFlip(),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0,0,0), (0.5,0.5,0.5)),
])
transformation2 = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0,0,0),... | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Defining models Defining a class of our simple model | class ConvNet(nn.Module):
def __init__(self, Num_Filter1 , Num_Filter2, Ker_Sz1, Ker_Sz2, Dropout, num_classes=2):
super(ConvNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d( # input shape (3, 30, 600)
in_channels=3, # input height
... | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Defining inception classes | class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, **kwargs):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_planes, out_planes, bias=False, **kwargs)
self.bn = nn.BatchNorm2d(out_planes, eps=0.001)
self.relu = nn.ReLU(inplace=True)
def forwar... | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Finding number of parameter in our model | def print_num_params(model):
TotalParam=0
for param in list(model.parameters()):
print("Individual parameters are:")
nn=1
for size in list(param.size()):
print(size)
nn = nn*size
print("Total parameters: {}" .format(param.numel()))
TotalParam += nn... | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Training and Validating Training and validation function | def train_model(model, criterion, optimizer, Dropout, learning_rate, BATCHSIZE, num_epochs):
print(str(datetime.now()).split('.')[0], "Starting training and validation...\n")
print("====================Data and Hyperparameter Overview====================\n")
print("Number of training examples:... | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Testing function | def test_model(model, test_loader):
print("Starting testing...\n")
model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
with torch.no_grad():
correct = 0
total = 0
test_loss_vect=[]
test_acc_vect=[]
since = time... | _____no_output_____ | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Applying aumentation and batch size | ## Using batch size to load data
train_data = torchvision.datasets.ImageFolder(train_path,transform=transformation)
train_loader =torch.utils.data.DataLoader(train_data, batch_size=BchSz, shuffle=True,
num_workers=8)
valid_data = torchvision.datasets.ImageFolder(valid_path,tra... | 2019-03-01 15:11:27 Starting training and validation...
====================Data and Hyperparameter Overview====================
Number of training examples: 24000 , Number of validation examples: 8000
Dropout:0.20, Learning rate: 0.00010
Batch size: 32, Number of epochs: 5
Number of parameter in the model: 63337... | MIT | Nets on Spectral data/01_PDU_Total_Designed_Inception.ipynb | Saman689/Weed-sensing-basics |
Import all needed package | import os
import ast
import numpy as np
import pandas as pd
from keras import optimizers
from keras.models import Sequential
from keras.layers import Dense, Activation, LSTM, Dropout
from keras.utils import to_categorical
from keras.datasets import mnist
from sklearn.preprocessing import OneHotEncoder
import matplotlib... | Using TensorFlow backend.
| MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Define the input data Using the full data set | sample_filename = ('10000_from_20190612130111781831_percentiles_els_binarized_homogeneous_deflanked_'
'sequences_with_exp_levels.txt.gz') | _____no_output_____ | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Define the absolute path | sample_path = ROOT_DIR + 'example/processed_data/' + sample_filename | _____no_output_____ | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Encode sequences | # Seems to give slightly better accuracy when expression level values aren't scaled.
scale_els = False
X_padded, y_scaled, abs_max_el = encode.encode_sequences_with_method(sample_path, method='One-Hot', scale_els=scale_els)
num_seqs, max_sequence_len = organize.get_num_and_len_of_seqs_from_file(sample_path) | _____no_output_____ | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Bulid the 3 dimensions LSTM model Reshape encoded sequences | X_padded = X_padded.reshape(-1)
X_padded = X_padded.reshape(int(num_seqs), 1, 5 * int(max_sequence_len)) | _____no_output_____ | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Reshape expression levels | y_scaled = y_scaled.reshape(len(y_scaled), 1, 1) | _____no_output_____ | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Perform a train-test split | test_size = 0.25
X_train, X_test, y_train, y_test = train_test_split(X_padded, y_scaled, test_size=test_size) | _____no_output_____ | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Build the model | # Define the model parameters
batch_size = int(len(y_scaled) * 0.01) # no bigger than 1 % of data
epochs = 50
dropout = 0.3
learning_rate = 0.01
# Define the checkpointer to allow saving of models
model_type = 'lstm_sequential_3d_onehot'
save_path = SAVE_DIR + model_type + '.hdf5'
checkpointer = ModelCheckpoint(monit... | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_87 (Dense) (None, 1, 1024) 410624
________________________________________________________... | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Fit and Evaluate the model | # Fit
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=eposhs,verbose=1,
validation_data=(X_test, y_test), callbacks=[checkpointer])
# Evaluate
score = max(history.history['val_acc'])
print("%s: %.2f%%" % (model.metrics_names[1], score*100))
plt = construct.plot_results(history.... | Train on 7500 samples, validate on 2500 samples
Epoch 1/500
7500/7500 [==============================] - 4s 594us/step - loss: 0.4805 - acc: 0.4929 - val_loss: 0.4735 - val_acc: 0.4740
Epoch 00001: val_acc improved from -inf to 0.47400, saving model to C:\Users\Lisboa\011019\ExpressYeaself/expressyeaself/models/lstm/s... | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Bulid the 2 dimensions LSTM model As for the data we have, we only have 1 output and that means we only have 1 time step, if we can delete that dimension in that model, then we can have a 2 dimensions LSTM model. Load the data again | X_padded, y_scaled, abs_max_el = encode.encode_sequences_with_method(sample_path, method='One-Hot', scale_els=scale_els)
num_seqs, max_sequence_len = organize.get_num_and_len_of_seqs_from_file(sample_path)
test_size = 0.25
X_train, X_test, y_train, y_test = train_test_split(X_padded, y_scaled, test_size=test_size) | _____no_output_____ | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Build up the model | # Define the model parameters
batch_size = int(len(y_scaled) * 0.01) # no bigger than 1 % of data
epochs = 50
dropout = 0.3
learning_rate = 0.01
# Define the checkpointer to allow saving of models
model_type = 'lstm_sequential_2d_onehot'
save_path = SAVE_DIR + model_type + '.hdf5'
checkpointer = ModelCheckpoint(monit... | WARNING:tensorflow:From C:\Users\Lisboa\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
WARNING:tensorflow:Fr... | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Fit and Evaluate the model | # Fit
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs,verbose=1,
validation_data=(X_test, y_test), callbacks=[checkpointer])
# Evaluate
score = max(history.history['val_acc'])
print("%s: %.2f%%" % (model.metrics_names[1], score*100))
plt = construct.plot_results(history.... | WARNING:tensorflow:From C:\Users\Lisboa\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
Train on 7500 samples, validate on 2500 samples
Epoch 1/500
75... | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Checking predictions on a small sample of native data | input_seqs = ROOT_DIR + 'expressyeaself/models/lstm/native_sample.txt'
model_to_use = 'lstm_sequential_2d'
lstm_result = construct.get_predictions_for_input_file(input_seqs, model_to_use, sort_df=True, write_to_file=False)
lstm_result.to_csv('lstm_result')
lstm_result | _____no_output_____ | MIT | expressyeaself/models/lstm/LSTM_builder.ipynb | yeastpro/expressYeaself |
Welcome to the Woodgreen Data Science & Python Program by Fireside AnalyticsData science is the process of ethically acquiring, engineering, analyzing, visualizaing and ultimately, creating value with data.In this tutorial, participants will be introduced to the Python programming language in this Python cloud environ... | ## Your first computer progam can be to say hello!
print ("Hello, World")
# We will need to learn some syntax! Syntax are the words used in a Python program
# the '#' sign tells Python to ignore a line. We use it for notes that we want humans to read
# print() is a function built into the core of Python
# For more soph... | _____no_output_____ | MIT | Woodgreen_Data_Science_&_Python_Nov_2021_Week_3.ipynb | tjido/woodgreen |
**We can do simple calculations in Python** | 5 + 5
# Some actions already programmed in:
x = 5
print(x + 7)
# What happens when we say "X=5"
# x 'points' at the number 5
x = 5
print("Initial x is:", x)
# y now 'points' at 'x' which 'points' at 5, so then y points at 5
y = x
print("Initial y is:", y)
x = 6
# What happens when we now change what x is?
print("C... | _____no_output_____ | MIT | Woodgreen_Data_Science_&_Python_Nov_2021_Week_3.ipynb | tjido/woodgreen |
------------------------------------------------------------------------ **We can do complex calculations in Python** - Remember we said Netflix users stream 404,444 hours of movies every minute? Let's calculate how many days that is! | ## In Python we create objects
## Converting from 404444 hours to days, we divide by___________?
days_watching_netflix = 404444/24 | _____no_output_____ | MIT | Woodgreen_Data_Science_&_Python_Nov_2021_Week_3.ipynb | tjido/woodgreen |
How can we do a survey in Python? We type 'input' to let Python know to wait for a user response. Once you type in the name, Python will remember it!Press 'enter' after your input. | response_1 = input("Response 1: What is your name?")
## We can now look at the response
response_1
response_2 = input("Response 2: What is your name?")
response_3 = input("Response 3: What is your name?")
response_4 = input("Response 4: What is your name?")
response_5 = input("Response 5: What is your name?") | _____no_output_____ | MIT | Woodgreen_Data_Science_&_Python_Nov_2021_Week_3.ipynb | tjido/woodgreen |
Let's look at response_5 | print(response_1,
response_2,
response_3,
response_4,
response_5) | _____no_output_____ | MIT | Woodgreen_Data_Science_&_Python_Nov_2021_Week_3.ipynb | tjido/woodgreen |
We can also add the names one at a time by typing them. | ## Let's create an object for the 5 names from question 1
survey_names = [response_1, response_2, response_3, response_4, response_5]
## Let's look at the object we've just created!
survey_names
print(survey_names) | _____no_output_____ | MIT | Woodgreen_Data_Science_&_Python_Nov_2021_Week_3.ipynb | tjido/woodgreen |
Let's make a simple bar chart in Python | import matplotlib.pyplot as plt
x = ['A', 'B', 'C', 'D', 'E']
y = [22, 9, 40, 27, 55]
plt.bar(x, y, color = 'red')
plt.title('Simple Bar Chart')
plt.xlabel('Width Names')
plt.ylabel('Height Values')
plt.show()
# Replot the same chart and change the color of the bars | _____no_output_____ | MIT | Woodgreen_Data_Science_&_Python_Nov_2021_Week_3.ipynb | tjido/woodgreen |
Here's a sample chart with some survey responses. | import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
data = [3,2]
labels = ['yes', 'no']
plt.xticks(range(len(data)), labels)
plt.xlabel('Responses')
plt.ylabel('Number of People')
plt.title('Shingai - Woodgreen Data Science & Python Program: Survey Results for Qu... | _____no_output_____ | MIT | Woodgreen_Data_Science_&_Python_Nov_2021_Week_3.ipynb | tjido/woodgreen |
CREAZIONE MODELLO SARIMA REGIONE SARDEGNA | import pandas as pd
df = pd.read_csv('../../csv/regioni/sardegna.csv')
df.head()
df['DATA'] = pd.to_datetime(df['DATA'])
df.info()
df=df.set_index('DATA')
df.head() | _____no_output_____ | Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Creazione serie storica dei decessi totali della regione Sardegna | ts = df.TOTALE
ts.head()
from datetime import datetime
from datetime import timedelta
start_date = datetime(2015,1,1)
end_date = datetime(2020,9,30)
lim_ts = ts[start_date:end_date]
#visulizzo il grafico
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
plt.title('Decessi mensili regione Sardegna dal 2015 a s... | _____no_output_____ | Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Decomposizione | from statsmodels.tsa.seasonal import seasonal_decompose
decomposition = seasonal_decompose(ts, period=12, two_sided=True, extrapolate_trend=1, model='multiplicative')
ts_trend = decomposition.trend #andamento della curva
ts_seasonal = decomposition.seasonal #stagionalità
ts_residual = decomposition.resid #parti rima... | _____no_output_____ | Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Test di stazionarietà | from statsmodels.tsa.stattools import adfuller
def test_stationarity(timeseries):
dftest = adfuller(timeseries, autolag='AIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for key,value in dftest[4].items():
dfoutput['Critical ... | X is not stationary
| Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Suddivisione in Train e Test Train: da gennaio 2015 a ottobre 2019; Test: da ottobre 2019 a dicembre 2019. | from datetime import datetime
train_end = datetime(2019,10,31)
test_end = datetime (2019,12,31)
covid_end = datetime(2020,9,30)
from dateutil.relativedelta import *
tsb = ts[:test_end]
decomposition = seasonal_decompose(tsb, period=12, two_sided=True, extrapolate_trend=1, model='multiplicative')
tsb_trend = decomposi... | X is not stationary
X is not stationary
X is not stationary
X is stationary
3
| Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Grafici di Autocorrelazione e Autocorrelazione Parziale | from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
plot_acf(ts, lags =12)
plot_pacf(ts, lags =12)
plt.show() | _____no_output_____ | Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Creazione del modello SARIMA sul Train | from statsmodels.tsa.statespace.sarimax import SARIMAX
model = SARIMAX(train, order=(6,1,8))
model_fit = model.fit()
print(model_fit.summary()) | c:\users\monta\appdata\local\programs\python\python38\lib\site-packages\statsmodels\tsa\base\tsa_model.py:524: ValueWarning: No frequency information was provided, so inferred frequency M will be used.
warnings.warn('No frequency information was'
c:\users\monta\appdata\local\programs\python\python38\lib\site-packages... | Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Verifica della stazionarietà dei residui del modello ottenuto | residuals = model_fit.resid
test_stationarity(residuals)
plt.figure(figsize=(12,6))
plt.title('Confronto valori previsti dal modello con valori reali del Train', size=20)
plt.plot (train.iloc[1:], color='red', label='train values')
plt.plot (model_fit.fittedvalues.iloc[1:], color = 'blue', label='model values')
plt.le... | _____no_output_____ | Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Predizione del modello sul Test | #inizio e fine predizione
pred_start = test.index[0]
pred_end = test.index[-1]
#pred_start= len(train)
#pred_end = len(tsb)
#predizione del modello sul test
predictions_test= model_fit.predict(start=pred_start, end=pred_end)
plt.plot(test, color='red', label='actual')
plt.plot(predictions_test, label='prediction' )
p... | NRMSE: 0.028047
| Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Predizione del modello compreso l'anno 2020 | #inizio e fine predizione
start_prediction = ts.index[0]
end_prediction = ts.index[-1]
predictions_tot = model_fit.predict(start=start_prediction, end=end_prediction)
plt.figure(figsize=(12,6))
plt.title('Previsione modello su dati osservati - dal 2015 al 30 settembre 2020', size=20)
plt.plot(ts, color='blue', label=... | _____no_output_____ | Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Intervalli di confidenza della previsione totale | forecast = model_fit.get_prediction(start=start_prediction, end=end_prediction)
in_c = forecast.conf_int()
print(forecast.predicted_mean)
print(in_c)
print(forecast.predicted_mean - in_c['lower TOTALE'])
plt.plot(in_c)
plt.show()
upper = in_c['upper TOTALE']
lower = in_c['lower TOTALE']
lower.to_csv('../../csv/lower/pr... | _____no_output_____ | Unlicense | Modulo 4 - Analisi per regioni/regioni/Sardegna/SARDEGNA - SARIMA mensile.ipynb | SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths |
Preparation | import pandas as pd
df_mortality = pd.read_excel(io='MortalityDataWHR2021C2.xlsx')
df_happiness = pd.read_excel(io='DataForFigure2.1WHR2021C2.xls')
df_regions = df_happiness[['Country name', 'Regional indicator']]
df = df_regions.merge(df_mortality)
df.head() | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Islands Number of Islands | df.Island.sum() | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Which region had more Islands? | df.groupby('Regional indicator').Island.sum() | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Show all Columns for these Islands | mask_region = df['Regional indicator'] == 'Western Europe'
mask_island = df['Island'] == 1
df_europe_islands = df[mask_region & mask_island]
df_europe_islands | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Mean Age of across All Islands? | df_europe_islands['Median age'].mean() | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Female Heads of State Number of Countries with Female Heads of State | df['Female head of government'].sum() | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Which region had more Female Heads of State? | df.groupby('Regional indicator')['Female head of government'].sum().sort_values(ascending=False) | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Show all Columns for these Countries | mask_region = df['Regional indicator'] == 'Western Europe'
mask_female = df['Female head of government'] == 1
df_europe_femaleheads = df[mask_region & mask_female]
df_europe_femaleheads | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Mean Age of across All Countries? | df_europe_femaleheads['Median age'].mean() | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Pivot Tables | df_panel = pd.read_excel(io='DataPanelWHR2021C2.xls')
df = df_panel.merge(df_regions)
df.pivot_table(index='Regional indicator', columns='year', values='Log GDP per capita') | _____no_output_____ | MIT | #01. Data Tables & Basic Concepts of Programming/Untitled.ipynb | gabisintope/machine-learning-program |
Occupation Introduction:Special thanks to: https://github.com/justmarkham for sharing the dataset and materials. Step 1. Import the necessary libraries | import pandas as pd
import numpy as np | _____no_output_____ | BSD-3-Clause | 03_Grouping/Occupation/Exercise.ipynb | mtzupan/pandas_exercises |
Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user). Step 3. Assign it to a variable called users. | url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user'
users = pd.read_csv(url, sep='\|')
users | _____no_output_____ | BSD-3-Clause | 03_Grouping/Occupation/Exercise.ipynb | mtzupan/pandas_exercises |
Step 4. Discover what is the mean age per occupation | users.groupby(['occupation'])['age'].mean() | _____no_output_____ | BSD-3-Clause | 03_Grouping/Occupation/Exercise.ipynb | mtzupan/pandas_exercises |
Step 5. Discover the Male ratio per occupation and sort it from the most to the least | if 'is_male' not in users:
users['is_male'] = users['gender'].apply(lambda x: x == 'M')
users
male_employees = users.loc[users['gender'] == 'M'].groupby(['occupation']).size().astype('float')
# print("male employees:", male_employees)
female_employees = users.loc[users['gender'] == 'F'].groupby(['occupation']).size... | _____no_output_____ | BSD-3-Clause | 03_Grouping/Occupation/Exercise.ipynb | mtzupan/pandas_exercises |
Step 6. For each occupation, calculate the minimum and maximum ages | users.groupby(['occupation'])['age'].min()
users.groupby(['occupation'])['age'].max() | _____no_output_____ | BSD-3-Clause | 03_Grouping/Occupation/Exercise.ipynb | mtzupan/pandas_exercises |
Step 7. For each combination of occupation and gender, calculate the mean age | users.loc[users['gender'] == 'M'].groupby(['occupation'])['age'].mean()
users.loc[users['gender']=='F'].groupby(['occupation'])['age'].mean() | _____no_output_____ | BSD-3-Clause | 03_Grouping/Occupation/Exercise.ipynb | mtzupan/pandas_exercises |
Step 8. For each occupation present the percentage of women and men | percent_male = np.abs((male_employees - female_employees))/male_employees
percent_male
percent_female = 1 - percent_male
percent_female | _____no_output_____ | BSD-3-Clause | 03_Grouping/Occupation/Exercise.ipynb | mtzupan/pandas_exercises |
Sentiment analysis with support vector machinesIn this notebook, we will revisit a learning task that we encountered earlier in the course: predicting the *sentiment* (positive or negative) of a single sentence taken from a review of a movie, restaurant, or product. The data set consists of 3000 labeled sentences, whi... | %matplotlib inline
import string
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rc('xtick', labelsize=14)
matplotlib.rc('ytick', labelsize=14)
from sklearn.feature_extraction.text import CountVectorizer
## Read in the data set.
with open("sentiment_labelled_sentences/full_set.txt") as... | train data: (2500, 4500)
test data: (500, 4500)
| MIT | Assignment 6/sentiment_svm/sentiment-svm.ipynb | ksopan/Edx_Machine_Learning_DSE220x |
2. Fitting a support vector machine to the dataIn support vector machines, we are given a set of examples $(x_1, y_1), \ldots, (x_n, y_n)$ and we want to find a weight vector $w \in \mathbb{R}^d$ that solves the following optimization problem:$$ \min_{w \in \mathbb{R}^d} \| w \|^2 + C \sum_{i=1}^n \xi_i $$$$ \text{sub... | from sklearn import svm
def fit_classifier(C_value=1.0):
clf = svm.LinearSVC(C=C_value, loss='hinge')
clf.fit(train_data,train_labels)
## Get predictions on training data
train_preds = clf.predict(train_data)
train_error = float(np.sum((train_preds > 0.0) != (train_labels > 0.0)))/len(train_labels)
... | Error rate for C = 0.01: train 0.215 test 0.250
Error rate for C = 0.10: train 0.074 test 0.174
Error rate for C = 1.00: train 0.011 test 0.152
Error rate for C = 10.00: train 0.002 test 0.188
Error rate for C = 100.00: train 0.002 test 0.198
Error rate for C = 1000.00: train 0.003 test 0.212
Error rate for C = 10000.0... | MIT | Assignment 6/sentiment_svm/sentiment-svm.ipynb | ksopan/Edx_Machine_Learning_DSE220x |
3. Evaluating C by k-fold cross-validationAs we can see, the choice of `C` has a very significant effect on the performance of the SVM classifier. We were able to assess this because we have a separate test set. In general, however, this is a luxury we won't possess. How can we choose `C` based only on the training se... | def cross_validation_error(x,y,C_value,k):
n = len(y)
## Randomly shuffle indices
indices = np.random.permutation(n)
## Initialize error
err = 0.0
## Iterate over partitions
for i in range(k):
## Partition indices
test_indices = indices[int(i*(n/k)):int((i+1)*(n/k) ... | _____no_output_____ | MIT | Assignment 6/sentiment_svm/sentiment-svm.ipynb | ksopan/Edx_Machine_Learning_DSE220x |
4. Picking a value of C The procedure **cross_validation_error** (above) evaluates a single candidate value of `C`. We need to use it repeatedly to identify a good `C`. **For you to do:** Write a function to choose `C`. It will be invoked as follows:* `c, err = choose_parameter(x,y,k)`where* `x,y` is the training data... | def choose_parameter(x,y,k):
C = [0.0001,0.001,0.01,0.1,1,10,100,1000,10000]
err=[]
for c in C:
err.append(cross_validation_error(x,y,c,k))
err_min,cc=min(list(zip(err,C))) #C value for minimum error
plt.plot(np.log(C),err)
plt.xlabel("Log(C)")
plt.ylabel("Corresponding error")
r... | _____no_output_____ | MIT | Assignment 6/sentiment_svm/sentiment-svm.ipynb | ksopan/Edx_Machine_Learning_DSE220x |
Now let's try out your routine! | c, err = choose_parameter(train_data, train_labels, 10)
print("Choice of C: ", c)
print("Cross-validation error estimate: ", err)
## Train it and test it
clf = svm.LinearSVC(C=c, loss='hinge')
clf.fit(train_data, train_labels)
preds = clf.predict(test_data)
error = float(np.sum((preds > 0.0) != (test_labels > 0.0)))/le... | Choice of C: 1
Cross-validation error estimate: 0.18554216867469878
Test error: 0.152
| MIT | Assignment 6/sentiment_svm/sentiment-svm.ipynb | ksopan/Edx_Machine_Learning_DSE220x |
Distribución normal teórica$$P(X) = \frac{1}{\sigma \sqrt{2 \pi}} \exp{\left[-\frac{1}{2}\left(\frac{X-\mu}{\sigma} \right)^2 \right]}$$* $\mu$: media de la distribución* $\sigma$: desviación estándar de la distribución | # definimos nuestra distribución gaussiana
def gaussian(x, mu, sigma):
return 1/(sigma*np.sqrt(2*np.pi))*np.exp(-0.5*pow((x-mu)/sigma,2))
x = np.arange(-4,4,0.1)
y = gaussian(x, 0.0, 1.0)
plt.plot(x, y)
# usando scipy
dist = norm(0, 1)
x = np.arange(-4,4,0.1)
y = [dist.pdf(value) for value in x]
plt.plot(x, y)
# cal... | _____no_output_____ | MIT | probability/probability-course/notebooks/[Clase9]Distribucion_normal.ipynb | Elkinmt19/data-science-dojo |
Distribución normal (gausiana) a partir de los datos* *El archivo excel* lo puedes descargar en esta página: https://seattlecentral.edu/qelp/sets/057/057.html | df = pd.read_excel('s057.xls')
arr = df['Normally Distributed Housefly Wing Lengths'].values[4:]
values, dist = np.unique(arr, return_counts=True)
print(values)
plt.bar(values, dist)
# estimación de la distribución de probabilidad
mu = arr.mean()
#distribución teórica
sigma = arr.std()
dist = norm(mu, sigma)
x = np.ar... | _____no_output_____ | MIT | probability/probability-course/notebooks/[Clase9]Distribucion_normal.ipynb | Elkinmt19/data-science-dojo |
ANS -1 | df_1['diff_in_days'] = df_1['Cut Off Date'] - df_1['Borrower DOB (MM/DD/YYYY)']
df_1['diff_in_years'] = df_1["diff_in_days"] / timedelta(days=365)
avg_borrower_age = df_1.groupby('Product Group')['diff_in_years'].mean()
avg_borrower_age
df_1['orig_year'] = df_1['Origination Date'].dt.year
origination_year = df_1.grou... | _____no_output_____ | MIT | Equipped_AI_Test.ipynb | VAD3R-95/Hackathons_and_Interviews |
ANS -2 | df_test = [origination_year,innsured_loans,loanID_max_maturity,total_balances,total_accounts]
df_ans_2 = reduce(lambda left,right: pd.merge(left,right,on=['Product Group'],how='inner'), df_test)
df_ans_2 | _____no_output_____ | MIT | Equipped_AI_Test.ipynb | VAD3R-95/Hackathons_and_Interviews |
ANS -3 | max_originating_balance = df_1.groupby('Product Group').agg({'Origination Balance':max})
df_merged = pd.merge(max_originating_balance,df_1,on=['Product Group','Origination Balance'],how='inner')
loan_id_originating_balance = df_merged.drop_duplicates(subset = ['Product Group', 'Origination Balance'], keep = 'first').r... | _____no_output_____ | MIT | Equipped_AI_Test.ipynb | VAD3R-95/Hackathons_and_Interviews |
ANS -4 | df_ques3 = pd.merge(df_1,df_2,on='LoanID',how='inner')
df_ans_3 = df_ques3.groupby(['Product Group']).apply(lambda x: x['Outstanding Balance'].sum()/x['Origination Balance'].sum()).reset_index(name='Balance Ammortized')
df_ans_3 | _____no_output_____ | MIT | Equipped_AI_Test.ipynb | VAD3R-95/Hackathons_and_Interviews |
Transfer Learning Template | %load_ext autoreload
%autoreload 2
%matplotlib inline
import os, json, sys, time, random
import numpy as np
import torch
from torch.optim import Adam
from easydict import EasyDict
import matplotlib.pyplot as plt
from steves_models.steves_ptn import Steves_Prototypical_Network
from steves_utils.lazy_iterable_wr... | _____no_output_____ | MIT | experiments/tl_1v2/cores-oracle.run1.framed/trials/14/trial.ipynb | stevester94/csc500-notebooks |
Allowed ParametersThese are allowed parameters, not defaultsEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)Papermill uses the cell tag "parameters" to inject the real parameters below this cell.Enable tags to see what I mean | required_parameters = {
"experiment_name",
"lr",
"device",
"seed",
"dataset_seed",
"n_shot",
"n_query",
"n_way",
"train_k_factor",
"val_k_factor",
"test_k_factor",
"n_epoch",
"patience",
"criteria_for_best",
"x_net",
"datasets",
"torch_default_dtype",
... | _____no_output_____ | MIT | experiments/tl_1v2/cores-oracle.run1.framed/trials/14/trial.ipynb | stevester94/csc500-notebooks |
Logistic Regression on 'HEART DISEASE' Dataset Elif Cansu YILDIZ | from pyspark.sql import SparkSession
from pyspark.sql.types import *
from pyspark.sql.functions import col, countDistinct
from pyspark.ml.feature import OneHotEncoderEstimator, StringIndexer, VectorAssembler, MinMaxScaler, IndexToString
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegre... | _____no_output_____ | MIT | Spark/HeartDataset-MLlib.ipynb | elifcansuyildiz/MachineLearningNotebooks |
The dataset used is 'Heart Disease' dataset from Kaggle. You can get from this [link](https://www.kaggle.com/ronitf/heart-disease-uci). | df = spark.read.csv('datasets/heart.csv', header = True, inferSchema = True) #Kaggle Dataset
df.printSchema()
df.show(5) | root
|-- age: integer (nullable = true)
|-- sex: integer (nullable = true)
|-- cp: integer (nullable = true)
|-- trestbps: integer (nullable = true)
|-- chol: integer (nullable = true)
|-- fbs: integer (nullable = true)
|-- restecg: integer (nullable = true)
|-- thalach: integer (nullable = true)
|-- exang: in... | MIT | Spark/HeartDataset-MLlib.ipynb | elifcansuyildiz/MachineLearningNotebooks |
__HOW MANY DISTINCT VALUE DO COLUMNS HAVE?__ | df.agg(*(countDistinct(col(c)).alias(c) for c in df.columns)).show() | +---+---+---+--------+----+---+-------+-------+-----+-------+-----+---+----+------+
|age|sex| cp|trestbps|chol|fbs|restecg|thalach|exang|oldpeak|slope| ca|thal|target|
+---+---+---+--------+----+---+-------+-------+-----+-------+-----+---+----+------+
| 41| 2| 4| 49| 152| 2| 3| 91| 2| 40| 3| ... | MIT | Spark/HeartDataset-MLlib.ipynb | elifcansuyildiz/MachineLearningNotebooks |
__SET the Label Column and Input Columns__ | labelColumn = "thal"
input_columns = [t[0] for t in df.dtypes if t[0]!=labelColumn]
# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = df.randomSplit([0.7, 0.3])
print("total data count: ", df.count())
print("train data count: ", trainingData.count())
print("test data cou... | total data count: 303
train data count: 218
test data count: 85
| MIT | Spark/HeartDataset-MLlib.ipynb | elifcansuyildiz/MachineLearningNotebooks |
__TRAINING__ | assembler = VectorAssembler(inputCols = input_columns, outputCol='features')
lr = LogisticRegression(featuresCol='features', labelCol=labelColumn,
maxIter=10, regParam=0.3, elasticNetParam=0.8)
stages = [assembler, lr]
partialPipeline = Pipeline().setStages(stages)
model = partialPipeline.fit(... | _____no_output_____ | MIT | Spark/HeartDataset-MLlib.ipynb | elifcansuyildiz/MachineLearningNotebooks |
__MAKE PREDICTIONS__ | predictions = model.transform(testData)
predictionss = predictions.select("probability", "rawPrediction", "prediction",
col(labelColumn).alias("label"))
predictionss[["probability", "prediction", "label"]].show(5, truncate=False) | +--------------------------------------------------------------------------------+----------+-----+
|probability |prediction|label|
+--------------------------------------------------------------------------------+----------+-----+
|[0.0110827882456902... | MIT | Spark/HeartDataset-MLlib.ipynb | elifcansuyildiz/MachineLearningNotebooks |
__EVALUATION for Binary Classification__ | evaluator = BinaryClassificationEvaluator(labelCol="label", rawPredictionCol="prediction", metricName="areaUnderROC")
areaUnderROC = evaluator.evaluate(predictionss)
print("Area under ROC = %g" % areaUnderROC)
evaluator = BinaryClassificationEvaluator(labelCol="label", rawPredictionCol="prediction", metricName="areaUn... | _____no_output_____ | MIT | Spark/HeartDataset-MLlib.ipynb | elifcansuyildiz/MachineLearningNotebooks |
__EVALUATION for Multiclass Classification__ | evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")
accuracy = evaluator.evaluate(predictionss)
print("accuracy = %g" % accuracy)
evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="f1")
f1 = evaluator.ev... | accuracy = 0.564706
f1 = 0.407607
weightedPrecision = 0.318893
weightedRecall = 0.564706
| MIT | Spark/HeartDataset-MLlib.ipynb | elifcansuyildiz/MachineLearningNotebooks |
一个完整的机器学习项目 | import os
import tarfile
import urllib
import pandas as pd
import numpy as np
from CategoricalEncoder import CategoricalEncoder | _____no_output_____ | MIT | sklearn-guide/chapter03/ml-3.ipynb | a630140621/machine-learning-course |
下载数据集 | DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/"
HOUSING_PATH = "../datasets/housing"
HOUSING_URL = DOWNLOAD_ROOT + HOUSING_PATH + "/housing.tgz"
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
if os.path.isfile(housing_path + "/housing.tgz"):
ret... | already download
| MIT | sklearn-guide/chapter03/ml-3.ipynb | a630140621/machine-learning-course |
加载数据集 | def load_housing_data(housing_path=HOUSING_PATH):
csv_path = os.path.join(housing_path, "housing.csv")
return pd.read_csv(csv_path)
housing_data = load_housing_data()
housing_data.head()
housing_data.info()
housing_data["ocean_proximity"].value_counts()
housing_data.describe() | _____no_output_____ | MIT | sklearn-guide/chapter03/ml-3.ipynb | a630140621/machine-learning-course |
绘图 | %matplotlib inline
import matplotlib.pyplot as plt
housing_data.hist(bins=50, figsize=(20, 15)) | _____no_output_____ | MIT | sklearn-guide/chapter03/ml-3.ipynb | a630140621/machine-learning-course |
创建测试集 | from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(housing_data, test_size=0.2, random_state=42)
housing = train_set.copy()
housing.plot(kind="scatter" , x="longitude", y="latitude", alpha= 0.3, s=housing[ "population" ]/100, label= "population", c="median_house_value", cmap=pl... | _____no_output_____ | MIT | sklearn-guide/chapter03/ml-3.ipynb | a630140621/machine-learning-course |
皮尔逊相关系数因为数据集并不是非常大,你以很容易地使用 `corr()` 方法计算出每对属性间的标准相关系数(standard correlation coefficient,也称作皮尔逊相关系数。相关系数的范围是 -1 到 1。当接近 1 时,意味强正相关;例如,当收入中位数增加时,房价中位数也会增加。当相关系数接近 -1 时,意味强负相关;你可以看到,纬度和房价中位数有轻微的负相关性(即,越往北,房价越可能降低)。最后,相关系数接近 0,意味没有线性相关性。> 相关系数可能会完全忽略非线性关系 | corr_matrix = housing.corr()
corr_matrix["median_house_value"].sort_values(ascending=False) | _____no_output_____ | MIT | sklearn-guide/chapter03/ml-3.ipynb | a630140621/machine-learning-course |
创建一些新的特征 | housing["rooms_per_household"] = housing["total_rooms"] / housing["households"]
housing["bedrooms_per_room"] = housing["total_bedrooms"] / housing["total_rooms"]
housing["population_per_household"] = housing["population"] / housing["households"]
corr_matrix = housing.corr()
corr_matrix["median_house_value"].sort_values... | _____no_output_____ | MIT | sklearn-guide/chapter03/ml-3.ipynb | a630140621/machine-learning-course |
为机器学习准备数据所有的数据处理 __只能在训练集上进行__,不能使用测试集数据。 | housing = train_set.drop("median_house_value", axis=1)
housing_labels = train_set["median_house_value"].copy() | _____no_output_____ | MIT | sklearn-guide/chapter03/ml-3.ipynb | a630140621/machine-learning-course |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.