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 |
|---|---|---|---|---|---|
From a sample of the RMS Titanic data, we can see the various features present for each passenger on the ship:- **Survived**: Outcome of survival (0 = No; 1 = Yes)- **Pclass**: Socio-economic class (1 = Upper class; 2 = Middle class; 3 = Lower class)- **Name**: Name of passenger- **Sex**: Sex of the passenger- **Age**:... | # Store the 'Survived' feature in a new variable and remove it from the dataset
outcomes = full_data['Survived']
data = full_data.drop('Survived', axis = 1)
# Show the new dataset with 'Survived' removed
display(data.head()) | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
The very same sample of the RMS Titanic data now shows the **Survived** feature removed from the DataFrame. Note that `data` (the passenger data) and `outcomes` (the outcomes of survival) are now *paired*. That means for any passenger `data.loc[i]`, they have the survival outcome `outcomes[i]`.To measure the performanc... | def accuracy_score(truth, pred):
""" Returns accuracy score for input truth and predictions. """
# Ensure that the number of predictions matches number of outcomes
if len(truth) == len(pred):
# Calculate and return the accuracy as a percent
return "Predictions have an accuracy... | Predictions have an accuracy of 60.00%.
| MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
> **Tip:** If you save an iPython Notebook, the output from running code blocks will also be saved. However, the state of your workspace will be reset once a new session is started. Make sure that you run all of the code blocks from your previous session to reestablish variables and functions before picking up where yo... | def predictions_0(data):
""" Model with no features. Always predicts a passenger did not survive. """
predictions = []
for _, passenger in data.iterrows():
# Predict the survival of 'passenger'
predictions.append(0)
# Return our predictions
return pd.Series(predictions... | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
Question 1*Using the RMS Titanic data, how accurate would a prediction be that none of the passengers survived?* **Hint:** Run the code cell below to see the accuracy of this prediction. | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 61.62%.
| MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
**Answer:** 61.62% ***Let's take a look at whether the feature **Sex** has any indication of survival rates among passengers using the `survival_stats` function. This function is defined in the `visuals.py` Python script included with this project. The first two parameters passed to the function are the RMS Titanic dat... | vs.survival_stats(data, outcomes, 'Sex') | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
Examining the survival statistics, a large majority of males did not survive the ship sinking. However, a majority of females *did* survive the ship sinking. Let's build on our previous prediction: If a passenger was female, then we will predict that they survived. Otherwise, we will predict the passenger did not survi... | def predictions_1(data):
""" Model with one feature:
- Predict a passenger survived if they are female. """
predictions = []
for _, passenger in data.iterrows():
if passenger['Sex'] == 'female':
predictions.append(1)
else:
predictions.append... | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
Question 2*How accurate would a prediction be that all female passengers survived and the remaining passengers did not survive?* **Hint:** Run the code cell below to see the accuracy of this prediction. | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 78.68%.
| MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
**Answer**: 78.68% ***Using just the **Sex** feature for each passenger, we are able to increase the accuracy of our predictions by a significant margin. Now, let's consider using an additional feature to see if we can further improve our predictions. For example, consider all of the male passengers aboard the RMS Tita... | vs.survival_stats(data, outcomes, 'Age', ["Sex == 'male'"]) | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
Examining the survival statistics, the majority of males younger than 10 survived the ship sinking, whereas most males age 10 or older *did not survive* the ship sinking. Let's continue to build on our previous prediction: If a passenger was female, then we will predict they survive. If a passenger was male and younger... | def predictions_2(data):
""" Model with two features:
- Predict a passenger survived if they are female.
- Predict a passenger survived if they are male and younger than 10. """
predictions = []
for _, passenger in data.iterrows():
if passenger['Sex'] == 'femal... | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
Question 3*How accurate would a prediction be that all female passengers and all male passengers younger than 10 survived?* **Hint:** Run the code cell below to see the accuracy of this prediction. | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 79.35%.
| MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
**Answer**: 79.35% ***Adding the feature **Age** as a condition in conjunction with **Sex** improves the accuracy by a small margin more than with simply using the feature **Sex** alone. Now it's your turn: Find a series of features and conditions to split the data on to obtain an outcome prediction accuracy of at leas... | vs.survival_stats(data, outcomes, 'SibSp', ["Sex == 'female'"]) | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
Adding number of siblings and spouses of the passenger for females increased accuracy. Having less than 3 siblings and spouses increasing chance of survive, 3 or 4 siblings and spouses reduce survive and there is no survival chance for females who had more than 4 siblings and spouses. | vs.survival_stats(data, outcomes, 'Age', ["Sex == 'male'", "Pclass == 1"]) | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
For male who was in first class with the age between 30 and 40 has high chance of survive. After exploring the survival statistics visualization, fill in the missing code below so that the function will make your prediction. Make sure to keep track of the various features and conditions you tried before arriving at y... | def predictions_3(data):
""" Model with multiple features. Makes a prediction with an accuracy of at least 80%. """
predictions = []
for _, passenger in data.iterrows():
if passenger['Sex'] == 'female' and passenger['SibSp'] < 3:
predictions.append(1)
e... | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
Question 4*Describe the steps you took to implement the final prediction model so that it got an accuracy of at least 80%. What features did you look at? Were certain features more informative than others? Which conditions did you use to split the survival outcomes in the data? How accurate are your predictions?* **H... | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 80.58%.
| MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
Examples on how to use this package: | from circuit import Circuit | _____no_output_____ | MIT | quantum_circuits/examples.ipynb | JinLi711/quantum_circuits |
Circuit Creation | circ = Circuit(3,5)
circ.X(2)
circ.H()
circ.barrier() | _____no_output_____ | MIT | quantum_circuits/examples.ipynb | JinLi711/quantum_circuits |
Getting the Current State | circ.get_state()
circ.get_state(output='tensor') | _____no_output_____ | MIT | quantum_circuits/examples.ipynb | JinLi711/quantum_circuits |
Execute Simulation | circ.execute(num_instances=800) | _____no_output_____ | MIT | quantum_circuits/examples.ipynb | JinLi711/quantum_circuits |
Code To OpenQASM | print(circ.compile()) | OPENQASM 2.0;
include "qelib1.inc";
qreg q[3]
creg c[5]
x q[2];
h q[None];
barrier q;
| MIT | quantum_circuits/examples.ipynb | JinLi711/quantum_circuits |
Measurement | circ = Circuit(2, 3)
circ.X(1)
# measure qubit one and write the result to classical bit 1
circ.measure(0, 1)
circ.bits[1] | _____no_output_____ | MIT | quantum_circuits/examples.ipynb | JinLi711/quantum_circuits |
Make Corner Plots of Posterior DistributionsThis file allows me to quickly and repeatedly make the cornor plot to examin the results of the MCMC analsys | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
from astropy.table import Table
import corner
# import seaborn
matplotlib.rcParams.update({'font.size': 11}) | _____no_output_____ | MIT | figures/Results-mcmc-corner-plot.ipynb | benjaminrose/SNIa-Local-Environments |
This function is the general function that is repeated called throught the file. One benifite to this system, is that I only need to update to higher quality labels in one place. | def corner_plot(file_, saved_file, truths=None, third=0):
data = Table.read(file_, format='ascii.commented_header', delimiter='\t')
if third !=0:
size = len(data)
data = data[(third-1)*size//3:(third)*size//3]
data = data.to_pandas()
data.dropna(inplace=True)
# look at corn... | _____no_output_____ | MIT | figures/Results-mcmc-corner-plot.ipynb | benjaminrose/SNIa-Local-Environments |
One Object | #run one object
SN = 16185
file_ = f'../resources/SN{SN}_campbell_chain.tsv'
saved_file = f'SN{SN}-mcmc-2018-12-21.pdf'
corner_plot(file_, saved_file) | _____no_output_____ | MIT | figures/Results-mcmc-corner-plot.ipynb | benjaminrose/SNIa-Local-Environments |
Messier Objects | # run all Messier objects
for id in [63, 82, 87, 89, 91, 101, 105, 108]:
file_ = f'../resources/SN{id}_messier_chain.tsv'
saved_file = f'messierTests/12-29-M{id}.pdf'
print(f'\nMaking {saved_file}')
corner_plot(file_, saved_file)
# One Messier Object
ID = 63
file_ = f'../resources/SN{ID}_messier_chain.... |
Making messierTests/12-22-M63.pdf
| MIT | figures/Results-mcmc-corner-plot.ipynb | benjaminrose/SNIa-Local-Environments |
Circle Test -- old | # run on circle test
for id in [1, 2, 3, 4, 5, 6, 7]:
file_ = f'../resources/SN{id}_chain.tsv'
saved_file = f'circleTests/12-19-C{id}.pdf'
print(f'\nMaking {saved_file}')
corner_plot(file_, saved_file)
# run on circle test 3 with truths
file_ = f'../resources/SN3_chain.tsv'
saved_file = f'circleTests/0... | WARNING:root:Too few points to create valid contours
| MIT | figures/Results-mcmc-corner-plot.ipynb | benjaminrose/SNIa-Local-Environments |
Test all Circle Tests | # for slope
# truths = {
# 1 : [-0.5, 0.1, 0.5, 1.5, 9.0, -1.0, -25, 10.68],
# 2 : [-0.5, 0.1, 0.5, 1.5, 9.0, 15.0, -25, 1.41],
# 3 : [-0.5, 0.1, 7.0, 3.0, 10, 15.0, -25, 1.75],
# 4 : [-0.5, 0.1, 7.0, 3.0, 13.0, 0.0, -25, 4.28],
# 5 : [-1.5, 0.1, 0.5, 1.5, 9.0, -1.0, -25, 10.68],
# 6 : [-0.5, 0.8, 7.0, 3.0, 10.0, 15.0,... | /usr/local/lib/python3.6/site-packages/matplotlib/pyplot.py:524: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_op... | MIT | figures/Results-mcmc-corner-plot.ipynb | benjaminrose/SNIa-Local-Environments |
Check sections of chain | file_ = f'../resources/SN2_chain.tsv'
saved_file = f'circleTests/C2-3.pdf'
print(f'\nMaking {saved_file}')
corner_plot(file_, saved_file, truths[2], third=3) |
Making circleTests/C2-3.pdf
| MIT | figures/Results-mcmc-corner-plot.ipynb | benjaminrose/SNIa-Local-Environments |
Question 1: Which team scored the most points when playing at home? | cur = conn.cursor()
cur.execute("SELECT sum(a.home_team_goal) as sum_goals, b.team_api_id, b.team_long_name FROM match a, team b WHERE a.home_team_api_id = b.team_api_id group by b.team_api_id order by sum_goals desc limit 1" )
rows = cur.fetchall()
for row in rows[:]:
print(row)
| (505, 8633, 'Real Madrid CF')
| MIT | Soccer_SQLite.ipynb | gequitz/Issuing-Credit-Cards-and-SQL-Assignment |
Question 2: Did this team also score the most points when playing away? | cur = conn.cursor()
cur.execute("SELECT sum(a.away_team_goal) as sum_goals, b.team_api_id, b.team_long_name FROM match a, team b WHERE a.away_team_api_id = b.team_api_id group by b.team_api_id order by sum_goals desc limit 1" )
rows = cur.fetchall()
for row in rows[:]:
print(row) | (354, 8634, 'FC Barcelona')
| MIT | Soccer_SQLite.ipynb | gequitz/Issuing-Credit-Cards-and-SQL-Assignment |
Question 3: How many matches resulted in a tie? | cur = conn.cursor()
cur.execute("SELECT count(match_api_id) FROM match where home_team_goal = away_team_goal" )
rows = cur.fetchall()
for row in rows[:]:
print(row) | (6596,)
| MIT | Soccer_SQLite.ipynb | gequitz/Issuing-Credit-Cards-and-SQL-Assignment |
Question 4: How many players have Smith for their last name? How many have 'smith' anywhere in their name? | cur = conn.cursor()
cur.execute("SELECT COUNT(player_name) FROM Player where player_name LIKE '% smith' " )
rows = cur.fetchall()
for row in rows[:]:
print(row)
cur = conn.cursor()
cur.execute("SELECT COUNT(player_name) FROM Player where player_name LIKE '%smith%' " )
rows = cur.fetchall()
for row i... | (18,)
| MIT | Soccer_SQLite.ipynb | gequitz/Issuing-Credit-Cards-and-SQL-Assignment |
Question 5: What was the median tie score? Use the value determined in the previous question for the number of tie games. Hint: PostgreSQL does not have a median function. Instead, think about the steps required to calculate a median and use the WITH command to store stepwise results as a table and then operate on the... | cur = conn.cursor()
#cur.execute("WITH goal_list AS (SELECT home_team_goal FROM match where home_team_goal = away_team_goal order \
# by home_team_goal desc) select home_team_goal from goal_list limit 1 offset 6596/2" )
cur.execute("WITH goal_list AS (SELECT home_team_goal FROM match where home_team_goa... | (1,)
| MIT | Soccer_SQLite.ipynb | gequitz/Issuing-Credit-Cards-and-SQL-Assignment |
Question 6: What percentage of players prefer their left or right foot? Hint: Calculate either the right or left foot, whichever is easier based on how you setup the problem. | cur = conn.cursor()
cur.execute("SELECT (COUNT(DISTINCT(player_api_id)) * 100.0 / (SELECT COUNT(DISTINCT(player_api_id)) FROM Player_Attributes)) \
FROM Player_Attributes WHERE preferred_foot LIKE '%right%' " )
rows = cur.fetchall()
for row in rows[:20]:
print(row)
#SELECT (COUNT(DISTINCT(pla... | (81.18444846292948,)
| MIT | Soccer_SQLite.ipynb | gequitz/Issuing-Credit-Cards-and-SQL-Assignment |
Importing the libraries | %pip install tensorflow
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import seaborn as sns | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Importing The Dataset | dataset = pd.read_csv("../input/framingham-heart-study-dataset/framingham.csv") | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Analysing The Data | dataset.shape
dataset.dtypes
dataset.info | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Visualizing the data | fig = plt.figure(figsize = (8,8))
ax = fig.gca()
dataset.hist(ax=ax)
plt.show()
fig, ax = plt.subplots()
ax.hist(dataset["TenYearCHD"],color = "yellow")
ax.set_title(' To predict heart disease')
ax.set_xlabel('TenYearCHD')
ax.set_ylabel('Frequency')
data = np.random.random([100,4])
sns.violinplot(data=data, palette=['r... | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Separating the dependent and independent variables | X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
np.isnan(X).sum()
np.isnan(y).sum() | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Taking Care of Missing Values | from sklearn.impute import SimpleImputer
si = SimpleImputer(missing_values = np.nan, strategy = 'mean')
X = si.fit_transform(X)
y.shape
np.isnan(X).sum()
np.isnan(y).sum()
dataset.isna().sum() | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Splitting into Training and test Data | from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3,random_state = 0) | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Normalising The data | from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
X_train
y_train
np.isnan(X_train).sum()
np.isnan(y_train).sum() | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Preparing ANN Model with two layers | ann = tf.keras.models.Sequential()
ann.add(tf.keras.layers.Dense(units = 6, activation = 'relu'))
ann.add(tf.keras.layers.Dense(units = 6, activation='relu'))
ann.add(tf.keras.layers.Dense(units = 1,activation='sigmoid'))
ann.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
model = ann.... | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Model Accuracy Visualisation | plt.plot(model.history['accuracy'])
plt.plot(model.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='lower right')
plt.show() | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Model Loss Visualisation | plt.plot(model.history['loss'])
plt.plot(model.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper right')
plt.show() | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Calculating Different Metrics | print(classification_report(y_test, y_pred)) | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Using MLP Classifier for Prediction | from sklearn.neural_network import MLPClassifier
classifier = MLPClassifier(hidden_layer_sizes=(150,100,50), max_iter=300,activation = 'relu',solver='adam',random_state=1)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
print(np.concatenate((y_pred.reshape(len(y_pred),1), y_... | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Visualising The MLP Model After Applying the PCA method | from sklearn.decomposition import PCA
pca = PCA(n_components=2)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
classifier.fit(X_train, y_train)
def visualization_train(model):
sns.set_context(context='notebook',font_scale=2)
plt.figure(figsize=(16,9))
from matplotlib.colors import List... | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Saving a machine learning Model | #import joblib
#joblib.dump(ann, 'ann_model.pkl')
#joblib.dump(sc, 'sc_model.pkl')
#knn_from_joblib = joblib.load('mlp_model.pkl')
#sc_model = joblib.load('sc_model.pkl') | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Saving a tensorflow model | #!pip install h5py
#ann.save('ann_model.h5')
#model = tf.keras.models.load_model('ann_model.h5') | _____no_output_____ | MIT | Heart Disease Risk Prediction/Heart Disease Risk Prediction.ipynb | somyasriv16/AN319_H4CK3RS_SIH2020 |
Reinforcement Learningpage 441For details, see- https://github.com/ageron/handson-ml/blob/master/16_reinforcement_learning.ipynb,- https://gym.openai.com,- http://www0.cs.ucl.ac.uk/staff/d.silver/web/Teaching.html,- https://www.jstor.org/stable/24900506?seq=1metadata_info_tab_contents,- http://book.pythontips.com/en/l... | import gym # import gym from OpenAI
env = gym.make("CartPole-v0") # make CartPole environment
print(env) # print the cartpole environment
obs = env.reset() # reset observations (in case this is necessary)
print(obs) # print the observations | [33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
<TimeLimit<CartPoleEnv<CartPole-v0>>>
[ 0.01911763 -0.04981526 0.02235611 0.01423974]
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
The "make()" function creates an environment (here, the CartPole environment). After creation, the environment must be reset via the "reset()" method. This returns the first observation, in the form of four floats in a $1\times4$ NumPy array: (i) the horizontal position (0=center), (ii) the velocity, (iii) the angle of... | # further imports and plot specifications (taken from Github link above)
import numpy as np
%matplotlib nbagg
import matplotlib
import matplotlib.animation as animation
import matplotlib.pyplot as plt
plt.rcParams["axes.labelsize"] = 14
plt.rcParams["xtick.labelsize"] = 12
plt.rcParams["ytick.labelsize"] = 12
# functio... | _____no_output_____ | Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
Nice. So this is a visualization OpenAI's CartPole environment. After the visualization is finished (it may be a movie), it is best to "close" the visualization by tapping the off-button at its top-right corner.**Suggestion or Tip**Unfortunately, the CartPole (and a few other environments) renders the image to the scre... | env.action_space # check what actions are possible | _____no_output_____ | Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
There are two possible actions: accelerating left (represented by the integer 0) or right (integer 1). Other environments are going to have other action spaces. We accelerate the cart in the direction that it is leaning. | obs = env.reset() # reset again to get different first observations when rerunning this cell
print(obs)
angle = obs[2] # get the angle
print(angle)
action = int((1 + np.sign(angle)) / 2) # compute the action
print(action)
obs, reward, done, info ... | [-0.01435942 0.0420023 0.00417418 0.0271142 ]
0.004174176652464501
1
[-0.01351937 0.23706414 0.00471646 -0.26424881] 1.0 False {}
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
The "step()" method executes the chosen action and returns 4 values:1. "obs"This is the next observation.2. "reward"This environment gives a reward for every time step (not more and not less). The only goal is to keep balancing the cart as long as possble.3. "done"The value of this dictionary is "False" while the episo... | # define a basic policy
def basic_policy(obs):
angle = obs[2] # angle
return 0 if angle < 0 else 1 # return action
totals = [] # container for total rewards of different episodes
# run 500 episodes of up to 1000 steps each
for episode in range(500): # run 500 epi... | mean: 41.938 , std: 8.855854334845397 , min: 24.0 , max: 68.0
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
Even for 500 episodes, this policy did not manage to reach only 100 steps, not to speak of 1000. As can be seen from the additional code shown under the above Github link, the reason for this is that the pole quickly begins strongly oscillating back and forth. Certainly, the policy is just too simple: also taking the a... | # code partially taken from Github link above
import tensorflow as tf
def reset_graph(seed=42):
tf.reset_default_graph()
tf.set_random_seed(seed)
np.random.seed(seed)
reset_graph()
# 1. specify the neural network architecture
n_inputs = 4
n_hidden = 4
n_outputs = 1
initializer = tf.variance_scaling_initiali... | /anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:493: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_qint8 = np.dtype([("qint8", np.int8, 1)])
/anaconda3/lib/python3.6/sit... | Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
Above, the numbered comments indicate what is happening in the subsequent code. Here are some details.1. Definition of the Neural Network architecture (c.f. Figure 16-5 on page 449 of the book).2. Building the Neural Network. Obviously, it is a vanilla (most basic) version. Via the sigmoid activation function, the outp... | # build a function that calculates the accumulated and discounted rewards for all steps
def discount_rewards(rewards, discount_rate):
discounted_rewards = np.empty(len(rewards))
cumulative_rewards = 0
for step in reversed(range(len(rewards))): # go from end to start
... | _____no_output_____ | Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
The following cell is a combination of code from the book and from the github link above. It implements the entire algorithm so it is a bit complicated. Comments shall assist in understanding the code. The default value of "n_iterations" ("n_max_steps") ["discount_rate"] is 250 (1000) [0.95] but can be increased for be... | # see also "Visualizing the Graph and Training Curves Using TensorBoard" in chapter / notebook 9 to review ...
# ... how to save a graph and display it in tensorboard; important ingredients: ...
# ... (i) reset_graph(), (ii) file_writer, and (iii) file_writer.close(); possible the "saver" is also important
# create a d... | ./tf_logs/16_RL/Cartpole/policy_gradients-20190919190805/
[33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
Using another function from the github link, we apply the trained model and visualize the performance of the agent in its environment. The performance differs from run to run, presumably due to random initialization of the environment. | # use code from the github link above to apply the trained model to the cartpole environment and show the results
model = 1
def render_policy_net(model_path, action, X, n_max_steps = 1000):
frames = []
env = gym.make("CartPole-v0")
obs = env.reset()
with tf.Session() as sess:
saver.restore(sess,... | [33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
INFO:tensorflow:Restoring parameters from ./tf_logs/16_RL/Cartpole/my_policy_net_pg.ckpt
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
This looks much better than without updating the gradients. Almost skillful, at least witn "n_iterations = 1000", "n_max_steps = 1000", and "discount_rate = 0.999". The according model is saved under "./tf_logs/Cartpole/my_1000_1000_0999_policy_net_pg.ckpt". In fact, **this algorithm is really powerful**. It can be use... | nan = np.nan # for transitions that do not exist (and thus have probability 0 but shall not be updated)
# transition probabilities
T = np.array([
[[0.7, 0.3, 0.0], [1.0, 0.0, 0.0], [0.8, 0.2, 0.0]], # at state s_0: actions a_0, a_1, a_2 to states s_0, s_1, s_2
[[0.0, 1.0, 0.0], [nan, nan, nan], [0.0, 0.0, 1.0]]... | 0 [0, 1, 2]
1 [0, 2]
2 [1]
[[ 0. 0. 0.]
[ 0. -inf 0.]
[-inf 0. -inf]]
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
Above, we have specified the model (lists of transition probabilities T, rewards R, and possible actions) and initialized the Q-values. Using $-\infty$ for impossible actions ensures that those actions will not be chosen by the policy. The enumerate command can be quite helpful and is therefore shortly introduced below... | # see the python tips link above
for counter, value in enumerate(["apple", "banana", "grapes", "pear"]):
print(counter, value)
print()
for counter, value in enumerate(["apple", "banana", "grapes", "pear"], 1):
print(counter, value)
print()
counter_list = list(enumerate(["apple", "banana", "grapes", "pear"], 1))... | 0 apple
1 banana
2 grapes
3 pear
1 apple
2 banana
3 grapes
4 pear
[(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
Now, define residual parameters and run the Q-value iteration algorithm. The results are very similar to the ones in the book. | # learning parameters
learning_rate = 0.01
discount_rate = 0.95 # try 0.95 and 0.9 (they give different results)
n_iterations = 100
# Q-value iteration
for iteration in range(n_iterations): # loop over iterations
Q_prev = Q.copy() # previous Q
for s in range(3): # loop over states... | [[21.88646117 20.79149867 16.854807 ]
[ 1.10804034 -inf 1.16703135]
[ -inf 53.8607061 -inf]]
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
The Q-value iteration algorithm gives different results for different discount rates $\gamma$. For $\gamma=0.95$, the optimal policy is to choose action 0 (2) [1] in state 0 (1) [2]. But this changes to actions 0 (0) [1] if $\gamma=0.9$. And it makes sense: when someone appreciates the present more than possible future... | n_states = 3 # number of MDP states
n_actions = 3 # number of actions
n_steps = 20000 # number of steps (=iterations)
alpha = 0.01 # learning rate
gamma = 0.99 # discount rate
# class for a Markov Decision Process (taken from the github link above)
class MDPEnvironment(object):
def __init__(self, start_s... | [[ 0. 0. 0.]
[ 0. -inf 0.]
[-inf 0. -inf]]
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
The above implementation is different from the book (where prior knowledge on the transition probabilities is used). Accordingly, the resulting Q-values are different from those in the book and closer to the ones listed in the github link above.With enough iterations, this algorithm will converge towards theo optimal Q... | env = gym.make("MsPacman-v0")
obs = env.reset()
print(obs.shape) # [height, width, channels]
print(env.action_space) # possible actions | (210, 160, 3)
Discrete(9)
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
So the agent observes a picture (screenshot) of 210 pixels height and 160 pixels width, with each pixel having three color values: the intensity of red, green, and blue. The agent may react by returning an action to the environment. There are nine discrete actions, corresponding to the nine joystick positions ([up, mid... | # see https://docs.python.org/2.3/whatsnew/section-slices.html for details on slices
trial_list = [[0.0,0.1,0.2,0.3,0.4],
[0,1,2,3,4],
[0,10,20,30,40]]
print(trial_list[:2]) # print list elements until before element 2, i.e., 0 and 1
print(trial_list[::2]) # print all list elements that are... | [[0.0, 0.1, 0.2, 0.3, 0.4], [0, 1, 2, 3, 4]]
[[0.0, 0.1, 0.2, 0.3, 0.4], [0, 10, 20, 30, 40]]
[[0.0, 0.1, 0.2, 0.3, 0.4], [0, 1, 2, 3, 4], [0, 10, 20, 30, 40]]
[[0.0, 0.1, 0.2, 0.3, 0.4]]
(88, 80, 1)
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
The next task will be to build the DQN (*Deep Q-Network*). In principle, one could just feed it a state-action pair (s, a) and have it estimate the Q-Value Q(s, a). But since the actions are discrete and only 9 actions are possible, one can also feed the DQN the state s and have it estimate Q(s, a) for all 9 possible a... | ### construction phase
# resetting the graph seems to always be a good idea
reset_graph()
# DQN architecture / hyperparameters
input_height = 88
input_width = 80
input_channels = 1
conv_n_maps = [32, 64, 64]
conv_kernel_sizes = [(8,8), (4,4), (3,3)]
conv_strides = [4, 2, 1]
conv_paddings = ["SAME"] * 3
conv_activation ... | next, some text...
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
The somehow initialized Q-values will have the actor network play the game (initially somehow random), update the encountered Q-values (via the default discounted rewards), and leave the remaining Q-values unchanged. Every now and then, the critic network is tasked with predicting all Q-values by fitting the weights an... | # the actor DQN computes 9 Q-values: 1 for each possible action; use one-hot encoding to select only the one that ...
# ... is actually chosen (https://www.tensorflow.org/api_docs/python/tf/one_hot)
X_action = tf.placeholder(tf.int32, shape=[None])
q_value = tf.reduce_sum(critic_q_values * tf.one_hot(X_action, n_output... | WARNING:tensorflow:From <ipython-input-17-483165648def>:4: calling reduce_sum (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.
Instructions for updating:
keep_dims is deprecated, use keepdims instead
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
For the execution phase, we will need the following tools. | # time keeping; for details, see the contribution of user "daviewales" on ...
# ... https://codereview.stackexchange.com/questions/26534/is-there-a-better-way-to-count-seconds-in-python
import time
time_start = time.time()
# another import, see https://docs.python.org/3/library/collections.html#collections.deque
from c... | 14.940124988555908
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
With a function from the github link above, we can visualize the play of the trained model. | frames = []
n_max_steps = 10000
with tf.Session() as sess:
saver.restore(sess, checkpoint_path)
obs = env.reset()
for step in range(n_max_steps):
state = preprocess_observation(obs)
q_values = actor_q_values.eval(feed_dict={X_state: [state]}) # from "online_q_values" to "actor_q_values"
... | INFO:tensorflow:Restoring parameters from ./tf_logs/16_RL/MsPacMan/my_dqn.ckpt
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
**Suggestion or Tip**Unfortunately, training is very slow: if you use your laptop for training, it will take days before Ms. Pac-Man gets any good, and if you look at the learning curve, measuring the average rewards per episode, you will notice that it is extremely noisy. At some points there may be no apparent progre... | # everything below is mainly from the github link above
# the rendering command (see github link) does not work here; the according code is adapted; frames are not ...
# ... displayed, here
env = gym.make("BipedalWalker-v2")
print(env)
obs = env.reset()
print(obs)
print(env.action_space)
print(env.action_space.low)
pri... | [33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
[33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
<TimeLimit<BipedalWalker<BipedalWalker-v2>>>
[ 2.74743512e-03 -1.15991896e-05 9.02299415e-04 -1.5999922... | Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
Build all possible combinations of actions (cf. above). | # see https://docs.python.org/3.7/library/itertools.html#itertools.product
from itertools import product
possible_torques = np.array([-1.0, 0.0, 1.0])
possible_actions = np.array(list(product(possible_torques, repeat=4)))
possible_actions.shape
print(possible_actions) | [[-1. -1. -1. -1.]
[-1. -1. -1. 0.]
[-1. -1. -1. 1.]
[-1. -1. 0. -1.]
[-1. -1. 0. 0.]
[-1. -1. 0. 1.]
[-1. -1. 1. -1.]
[-1. -1. 1. 0.]
[-1. -1. 1. 1.]
[-1. 0. -1. -1.]
[-1. 0. -1. 0.]
[-1. 0. -1. 1.]
[-1. 0. 0. -1.]
[-1. 0. 0. 0.]
[-1. 0. 0. 1.]
[-1. 0. 1. -1.]
[-1. 0. 1. 0... | Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
Build a network and see how it performs. | tf.reset_default_graph()
# 1. Specify the network architecture
n_inputs = env.observation_space.shape[0] # == 24
n_hidden = 10
n_outputs = len(possible_actions) # == 625
initializer = tf.variance_scaling_initializer()
# 2. Build the neural network
X = tf.placeholder(tf.float32, shape=[None, n_inputs])
hidden = tf.laye... | [33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
[33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
| Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
The model does not perform well because it has not been trained, yet. This shall be done! | n_games_per_update = 10 # default is 10
n_max_steps = 10 # default is 1000
n_iterations = 100 # default is 1000
save_iterations = 10 # default is 10
discount_rate = 0.95 # default is 0.95
with tf.Session() as sess:
init.run()
for iteration in range(n_iterations):
print("\rIteration: {}... | Iteration: 100/100[33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
[33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
INFO:tensorflow:Restoring parameters from ./tf_logs/16_RL/BiPedal/my_bipedal_walker_pg... | Apache-2.0 | 16. Reinforcement Learning.ipynb | MRD-Git/Hands-On-Machine-Learning |
Dynamic Recurrent Neural Network.TensorFlow implementation of a Recurrent Neural Network (LSTM) that performs dynamic computation over sequences with variable length. This example is using a toy dataset to classify linear sequences. The generated sequences have variable length. RNN OverviewReferences:- [Long Short T... | from __future__ import print_function
import tensorflow as tf
import random
# ====================
# TOY DATA GENERATOR
# ====================
class ToySequenceData(object):
""" Generate sequence of data with dynamic length.
This class generate samples for training:
- Class 0: linear sequences (i.e. [0, ... | Step 1, Minibatch Loss= 0.864517, Training Accuracy= 0.42188
Step 200, Minibatch Loss= 0.686012, Training Accuracy= 0.43269
Step 400, Minibatch Loss= 0.682970, Training Accuracy= 0.48077
Step 600, Minibatch Loss= 0.679640, Training Accuracy= 0.50962
Step 800, Minibatch Loss= 0.675208, Training Accuracy= 0.53846
Step 10... | MIT | dynamic_rnn.ipynb | abhihirekhan/-TensorFlow-basic-models-and-neural-networks-Tableau |
**Exploratory Analysis** First of all, let's import some useful libraries that will be used in the analysis. | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
Now, the dataset stored in drive needs to be retieved. I am using google colab for this exploration with TPU hardware accelerator for faster computation. To get the data from drive the drive needs to be mounted first. | from google.colab import drive
drive.mount('/content/drive/') | Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdocs.test%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive%2... | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
Once the drive is successfully mounted, I fetched the data and stored it in a pandas dataframe. | dataset = pd.read_csv("/content/drive/My Drive/Colab Notebooks/DOB_Permit_Issuance.csv") | /usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py:2718: DtypeWarning: Columns (1,8,9,10,15,25,31,33,34,35,36,51,52) have mixed types. Specify dtype option on import or set low_memory=False.
interactivity=interactivity, compiler=compiler, result=result)
| MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
To get the gist of the dataset, I used pandas describe function that gives a very broad understanding of the data. | pd.set_option('display.max_colwidth', 1000)
pd.set_option('display.max_rows', 1000)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
dataset.describe() | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
From the describe function, we now know that the dataset has almost 3.5 M data. Let's take a look at the dataset now. | dataset.head() | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
I can see there are lot's of NaNs in many columns. To better analyse the data, the NaNs needs to be removed or dealt with. But first, let's see hoe many NaNs are there is each column. | dataset.isna().sum() | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
---The information above is very useful in feature selection. Observing the columns with very high number of NaNs, such as :Column | NaNs ------------|-------- Special District 1 | 3121182 Special District 2 | 3439516 Permittee's Other Title |... | values = {'Residential': 'No','Site Fill':'NONE', 'Oil Gas':'None', 'Self_Cert':'N', 'Act as Superintendent':'N',
'Non-Profit':'N' }
dataset = dataset.fillna(value= values) | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
Since there are many columns with blank spaces and we cannot fill the blanks with appropriate information, it's better to drop these column as they do not add value to the analysis.I will drop the following columns :* Special District 1* Special District 2* Work Type* Permit Subtype* Permittee's First Name* Permittee's... | dataset.drop("Special District 1", axis=1, inplace=True)
dataset.drop("Special District 2", axis=1, inplace=True)
dataset.drop("Work Type", axis=1, inplace=True) #since work type and permit type give same information
dataset.drop("Permit Subtype", axis=1, inplace=True)
dataset.drop("Permittee's First Name", axis=1, inp... | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
Let's take a look at the remaining columns and their number of blanks again. | dataset.isna().sum() | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
We still have blanks in few columns left. One way to deal with them is to replace them with mean of that column or the most frequent entry of that column. Mean can onlly be applied to numerical columns and even for numerical columns such as Longitude and Lattitude, this mean might not be right to replace all the missin... | dataset.dropna(inplace=True)
dataset.isna().sum() | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
---Now the dataset looks clean and we can proceed with analysis. I will try find the correlation between columns using the correlation matrix. | # Correlation matrix
def plotCorrelationMatrix(df, graphWidth):
filename = 'DOB_Permit_Issuance.csv'
df = df[[col for col in df if df[col].nunique() > 1]] # keep columns where there are more than 1 unique values
corr = df.corr()
plt.figure(num=None, figsize=(graphWidth, graphWidth), dpi=80, facecolor='w... | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
We can see that there is strong positive relationship between :* Zip Code and Job * Job and Council_District* Zip Code and Council_District ---To get more insight of the data and its column-wise data distribution, I will plot the columns using bar graphs. For displaying purposes, I will pick columns that have betwee... | def plotColumns(dataframe, nGraphShown, nGraphPerRow):
nunique = dataframe.nunique()
dataframe = dataframe[[col for col in dataframe if nunique[col] > 1 and nunique[col] < 50]]
nRow, nCol = dataframe.shape
columnNames = list(dataframe)
nGraphRow = (nCol + nGraphPerRow - 1) / nGraphPerRow
plt.fig... | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
From the Borough graph, it's evident that the Manhattan has highest number of filing for the permit. Then the second popuar borough after manhattan is Brooklyn with huge margin. Then comes the Queens with almost same number of permits as Brooklyn. We see another plunge in permit numbers with Bronx and Staten Island.---... | manhattan_bldg_type = dataset[dataset.BOROUGH == 'MANHATTAN'][['Bldg Type']]
manhattan_bldg_type.reset_index(drop=True, inplace=True)
brooklyn_bldg_type = dataset[dataset.BOROUGH == 'BROOKLYN'][['Bldg Type']]
brooklyn_bldg_type.reset_index(drop=True, inplace=True)
bronx_bldg_type = dataset[dataset.BOROUGH == 'BRONX']... | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
**Analysis**The builing type is either '1' or '2' and we earlier discovered that type '2' were significantly popular as compared to type '1'. However, this is not true for all the Boroughs. For manhattan, this trend still holds true. But for other locations, the type '1' buildings are comparable in number with that of ... | manhattan_permit_type = dataset[dataset.BOROUGH == 'MANHATTAN'][['Permit Type']]
manhattan_permit_type.reset_index(drop=True, inplace=True)
brooklyn_permit_type = dataset[dataset.BOROUGH == 'BROOKLYN'][['Permit Type']]
brooklyn_permit_type.reset_index(drop=True, inplace=True)
bronx_permit_type = dataset[dataset.BOROU... | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
**Analysis**In Permit Type we earlier discovered that type 'EW' was the most popular and significantly higher in number as compared to other types. However, this is true for most of the Boroughs except Staten Island. However, other types of Permit are shuffled in each Borough. Below is the type of permits in decreasing... | manhattan_owners_business_type = dataset[dataset.BOROUGH == 'MANHATTAN'][['Owner\'s Business Type']]
manhattan_owners_business_type.reset_index(drop=True, inplace=True)
brooklyn_owners_business_type = dataset[dataset.BOROUGH == 'BROOKLYN'][['Owner\'s Business Type']]
brooklyn_owners_business_type.reset_index(drop=True... | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
**Analysis**We earlier discovered that the 'Corporation' was the most popular 'Owner's Business type' and 'Individual' type was closely competing with it. Taking a closer look at each borough reveals that the trend highly varies in all the Boroughs. In Manhattan, the 'Corporation' is still the highest but the 'Individu... | manhattan_job_type = dataset[dataset.BOROUGH == 'MANHATTAN'][['Job Type']]
manhattan_job_type.reset_index(drop=True, inplace=True)
brooklyn_job_type = dataset[dataset.BOROUGH == 'BROOKLYN'][['Job Type']]
brooklyn_job_type.reset_index(drop=True, inplace=True)
bronx_job_type = dataset[dataset.BOROUGH == 'BRONX'][['Job ... | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
**Analysis**We earlier discovered that the 'A2' was the most popular 'Job type' and numbers showed a decreasing trend with 'NB', 'A3', 'A1', 'DM', and 'SG'. Taking a closer look at each borough revealsa slightly different trend. For example, in Manhattan, the 'A2' is still the highest but the 'NB' is pushed beyond 'A1'... | dataset['Issuance Date'] = pd.to_datetime(dataset['Issuance Date'])
dataset['Issuance Date'] =dataset['Issuance Date'].dt.year | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
Once the dates are replaced by the corresponding years, we can plot the graph. | timeline = dataset['Issuance Date'].value_counts(ascending=True)
timeline = timeline.sort_index()
timeline.to_frame()
timeline.plot.bar() | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
**Analysis**We can observe that the number of permits has been consistently increasing each year. The number got stagnant from 1993 to 1996 and then it increased exponentially from 1997 until 2007. The applications decreasedfor a couple of years and then rose exponentially from 2010 to 2017. Borough-Wise Analysis of T... | manhattan_permits_issued = dataset[dataset.BOROUGH == 'MANHATTAN'][['Issuance Date']]
manhattan_permits_issued.reset_index(drop=True, inplace=True)
brooklyn_permits_issued = dataset[dataset.BOROUGH == 'BROOKLYN'][['Issuance Date']]
brooklyn_permits_issued.reset_index(drop=True, inplace=True)
bronx_permits_issued = da... | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
In Manhattan and Brooklyn, most number of applications were filed during 2010 and 2015 period.Bronx and Queens observed the highest number of filings in recent years from 2015 to 2019. Staten Island had most applications during 2000 to 2015 and then there is again a surge in applications around 2015 but the number of a... | dataset['Filing Date'] = pd.to_datetime(dataset['Filing Date'])
dataset['Filing Date'] =dataset['Filing Date'].dt.month
months = dataset['Filing Date'].value_counts()
months.to_frame()
months = months.sort_index()
plotColumns(months, 1, 1) | _____no_output_____ | MIT | NY Permits.ipynb | parasgulati8/Data-Analysis |
Laboratorio 7 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import altair as alt
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
alt.themes.enable('opaque')
%matplotlib inline | _____no_output_____ | MIT | labs/lab07.ipynb | Dhannai/MAT281_portfolio |
En este laboratorio utilizaremos los mismos datos de diabetes vistos en la clase | diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True, as_frame=True)
diabetes = pd.concat([diabetes_X, diabetes_y], axis=1)
diabetes.head() | _____no_output_____ | MIT | labs/lab07.ipynb | Dhannai/MAT281_portfolio |
Pregunta 1(1 pto)* ¿Por qué la columna de sexo tiene esos valores?* ¿Cuál es la columna a predecir?* ¿Crees que es necesario escalar o transformar los datos antes de comenzar el modelamiento? __Respuesta:__* Porque los valores se encuentran escalados y centrados por su desviación estandar multiplicada por la cantidad ... | regr_with_incerpet = linear_model.LinearRegression(fit_intercept=True)
regr_with_incerpet.fit(diabetes_X, diabetes_y)
diabetes_y_pred_with_intercept = regr_with_incerpet.predict(diabetes_X)
# Coeficientes
print(f"Coefficients: \n{regr_with_incerpet.coef_}\n")
# Intercepto
print(f"Intercept: \n{regr_with_incerpet.interc... | Coefficients:
[ -10.01219782 -239.81908937 519.83978679 324.39042769 -792.18416163
476.74583782 101.04457032 177.06417623 751.27932109 67.62538639]
Mean squared error: 26004.29
Coefficient of determination: -3.39
| MIT | labs/lab07.ipynb | Dhannai/MAT281_portfolio |
**Pregunta: ¿Qué tan bueno fue el ajuste del modelo?** __Respuesta:__No es muy bueno, ya que el coeficiente de determinación es 0.52 para el caso con intercepto, y para que sea una buena aproximación debería ser cercano a 1. Para el caso sin intercepto el R2 es negativo por lo que es mejor utilizar el promedio de los d... | for col in diabetes_X.columns:
X_i = diabetes_X[col].to_frame()
regr_i = linear_model.LinearRegression(fit_intercept=True)
regr_i.fit(X_i,diabetes_y)
diabetes_y_pred_i = regr_i.predict(X_i)
print(f"Feature: {col}")
print(f"\tCoefficients: {regr_i.coef_}")
print(f"\tIntercept: {regr_i.interce... | Feature: age
Coefficients: [304.18307453]
Intercept: 152.13348416289605
Mean squared error: 5720.55
Coefficient of determination: 0.04
Feature: sex
Coefficients: [69.71535568]
Intercept: 152.13348416289594
Mean squared error: 5918.89
Coefficient of determination: 0.00
Feature: bmi
Coefficients: [949.43526038... | MIT | labs/lab07.ipynb | Dhannai/MAT281_portfolio |
**Pregunta: Si tuvieras que escoger una sola _feauture_, ¿Cuál sería? ¿Por qué?** **Respuesta:** Escogería la Feature bmi, porque es la que tiene le menor error y el coeficiente de determinación más cercano a 1. Ejercicio 4(1 pto)Con la feature escogida en el ejercicio 3 realiza el siguiente gráfico:- Scatter Plot- Ej... | regr = linear_model.LinearRegression(fit_intercept=True).fit(diabetes_X['bmi'].to_frame(), diabetes_y)
diabetes_y_pred_bmi = regr.predict(diabetes_X['bmi'].to_frame())
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16
x = d... | _____no_output_____ | MIT | labs/lab07.ipynb | Dhannai/MAT281_portfolio |
Design 1 | !tar -xzvf ../Data/Design1/entk.session-design1-54875/entk.session-design1-54875.tar.gz -C ../Data/Design1/entk.session-design1-54875/
!tar -xzvf ../Data/Design1/entk.session-design1-54875/entk_workflow.tar.gz -C ../Data/Design1/entk.session-design1-54875/
des1DF = pd.DataFrame(columns=['TTX','AgentOverhead','ClientOve... | TTX AgentOverhead ClientOverhead EnTKOverhead
0 11717.529445 978.254925 45306.359832 12857.508548
| MIT | Geolocation/Notebooks/Des1Des2OverheadComp.ipynb | radical-experiments/iceberg_escience |
Design 2 | des2DF = pd.DataFrame(columns=['TTX','SetupOverhead','SetupOverhead2','AgentOverhead','ClientOverhead'])
sids = ['design2_11K_run5']
for sid in sids:
Node1 = pd.DataFrame(columns=['Start','End','Type'])
Node1Tilling = pd.read_csv('../Data/Design2/'+sid+'/pilot.0000/unit.000002/geolocate1.csv')
for index,ro... | TTX SetupOverhead SetupOverhead2 AgentOverhead ClientOverhead
0 6703.852195 81.679263 7.051244 0.18611 22.274512
| MIT | Geolocation/Notebooks/Des1Des2OverheadComp.ipynb | radical-experiments/iceberg_escience |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.