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 |
|---|---|---|---|---|---|
Question 6:A website requires the users to input username and password to register. Write a program to check the validity of password input by users.Following are the criteria for checking the password:1. At least 1 letter between [a-z]2. At least 1 number between [0-9]1. At least 1 letter between [A-Z]3. At least 1 c... | import re
password= input('Enter your password: ').split(',')
valid = []
for i in password:
if len(i) < 6 or len(i) > 12:
break
elif not re.search('([a-z])+', i):
break
elif not re.search("([A-Z])+", i):
break
elif not re.search("([0-9])+", i):
break
elif not re.se... | Enter your password: ABd1234@1,a F1#,2w3E*,2We3345
ABd1234@1
| CNRI-Python | Programming_Assingment13.ipynb | 14vpankaj/iNeuron_Programming_Assignments |
ابتدا باید کتابخانه های زیر را وارد کنیم: numpy: برای کار با ماتریس ها matplotlib: برای رسم نمودار PCA: برای کاهش بعد OpenCV: برای کار با عکس special_ortho_group: برای تولید پایه اورتونرمال تذکر: اگر کتابخانه cv2 اجرا نشد باید آن را نصب کنید. در command prompt دستور زیر را اجر... | !pip install opencv-python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import cv2
from scipy.stats import special_ortho_group as sog | _____no_output_____ | MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
پروژه ۲: استفاده از کاهش بعد قسمت ۱.۱: تولید دیتا با استفاده از پایه اورتونرمال عملیات زیر را انجام دهید: ابتدا با استفاده از تابع np.zeros آلفا وکتور هایی با ابعاد dim و N بسازید. سعی کنید متغیر آلفا وکتور را طوری پر کنید که به ازای هر اندیس از بعد صفر آن، آرایه ای از توزیع نرمال با میانگین ۰... | dim = 20
N = 1000
alpha_vectors = np.zeros((N, dim))
for i in range(N):
alpha_vectors[i] = np.random.normal(0, i + 1, dim)
V = sog.rvs(dim)
alpha_v = np.matmul(alpha_vectors, V)
print(alpha_v) | [[ 1.85796782e-01 5.95693503e-01 -1.06141413e+00 ... 1.25360933e+00
-1.49196549e+00 -1.71645212e+00]
[-5.52355256e-01 -2.32208128e-01 -1.45257747e+00 ... -5.75353815e-01
5.32574186e-01 -1.13204072e+00]
[ 1.62991497e+00 3.05093383e-01 1.85496227e+00 ... -2.02565163e+00
3.66097985e+00 3.27154903e+00]
...
... | MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
قسمت ۱.۲:استفاده از PCA برای کاهش بعد عملیات زیر را انجام دهید: ابتدا یک شیی از PCA بسازید. با استفاده از تابع fit موجود در شیی PCA عملیات pca را روی دیتا alpha_v انجام دهید. با استفاده از تابع components_ موجود در شیی pca بردار های تکین را مشاهده کنید. با استفاده از تابع explai... | pca = PCA()
pca.fit(alpha_v)
print(pca.components_)
print(pca.explained_variance_)
| [[ 3.34017742e-02 -1.18904961e-01 -4.25147294e-01 1.26947115e-01
3.13449083e-01 2.54046525e-01 2.71726916e-01 1.80475336e-01
-1.14252489e-01 -5.92359744e-02 -7.92421226e-02 -3.44459207e-01
2.23677760e-01 4.90444010e-01 -1.12590124e-01 1.54180027e-01
-5.84606532e-03 1.51139626e-01 -6.85230914e-02 1.503... | MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
قسمت ۱.۳: کاهش بعد به ۳ بعد ابتدا یک شیی از PCA با ورودی n_components=3 بسازید. با استفاده از تابع fit موجود در شیی PCA عملیات pca را روی دیتا alpha_v انجام دهید. تابع explained_variance_ratio_ موجود در شیی pca درصد حفظ دیتا به ازای هر کدام از بعد ها را می دهد. با کاهش بعد به ۳، چند درصد از... | pca = PCA(n_components = 3)
pca.fit(alpha_v)
print(str(100 * np.sum(pca.explained_variance_ratio_)) + " percent of data is preserved in 3 dimensions!")
| 19.544901432955598 percent of data is preserved in 3 dimensions!
| MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
برای حفظ ۹۰ درصد از اطلاعات به چند بعد نیاز داریم؟ | min_dim = 0
for i in range(1, dim):
pca = PCA(n_components = i)
pca.fit(alpha_v)
if (np.sum(pca.explained_variance_ratio_) >= 0.9):
min_dim = i
break
print("Almost " + str(100 * np.sum(pca.explained_variance_ratio_)) + " percent of data is preserved in at least " + str(min_dim) + " dimension... | Almost 93.01006062812166 percent of data is preserved in at least 18 dimensions!
| MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
قسمت ۲.۱: خواندن فایل تصویرابتدا فایل تصویری رنگی باکیفیتی را از گوگل دانلود کنید.با استفاده از تابع imread موجود در کتابخانه OpenCV عکس مربوطه را فراخوانی کنید: | image1 = cv2.imread("mona.jpg") | _____no_output_____ | MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
عکس خوانده شده را به فرمت RGB در می آوریم: | image = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB) | _____no_output_____ | MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
همانطور که می بینید عکس خوانده شده به ازای هر پیکسل ۳ عدد دارد: بنابراین برای هر عکس رنگی x*y یک آرایه x*y*3 خواهیم داشت. | dim = image.shape
print('Image shape =', dim) | Image shape = (720, 483, 3)
| MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
قسمت ۲.۲: نمایش تصویربا استفاده از تابع imshow موجود در matplotlib تصویر خوانده شده را نمایش دهید: | plt.imshow(image)
plt.show() | _____no_output_____ | MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
قسمت ۲.۳: آماده سازی تصویر برای کاهش بعدسه ماتریس رنگ را در ماتریس های R,G,B ذخیره کنید: | R = image[:, :, 0]
G = image[:, :, 1]
B = image[:, :, 2]
print(R.shape)
print(G.shape)
print(B.shape) | (720, 483)
(720, 483)
(720, 483)
| MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
قسمت ۲.۴:استفاده از PCA برای کاهش بعد با استفاده از کلاس PCA در کتابخانه sklearn کاهش بعد را انجام میدهیم. عملیات زیر را انجام دهید: راهنمایی برای هر یک از ماتریس های R,G,B یک شی PCA ایجاد کنید. تعداد مولفه ها را ۱۰ قرار دهید. با استفاده از تابع fit موجود در pca الگوریتم را روی ماتریس ها فیت ... | k = 10
rpca = PCA(n_components = k)
gpca = PCA(n_components = k)
bpca = PCA(n_components = k)
rpca.fit(R)
gpca.fit(G)
bpca.fit(B)
print("First " + str(k) + " components of Red Matrix have " + str(100 * np.sum(rpca.explained_variance_ratio_)) + " percent of data.")
print("First " + str(k) + " components of Green Matri... | _____no_output_____ | MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
عملیات زیر را انجام دهید: با استفاده از تابع transform موجود در pca دیتا با بعد کمتر را تولید کنید با استفاده از تابع inverse_transform دیتا را به بعد اولیه برگردانید | Transform_R = rpca.transform(R)
Transform_B = gpca.transform(G)
Transform_G = bpca.transform(B)
Reduced_R = rpca.inverse_transform(Transform_R)
Reduced_G = gpca.inverse_transform(Transform_G)
Reduced_B = bpca.inverse_transform(Transform_B)
print('Transform Matrix Shape = ', Transform_R.shape)
print('Inverse Transform ... | Transform Matrix Shape = (720, 10)
Inverse Transform Matrix Shape = (720, 483)
| MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
با استفاده از دستور concatenate سه ماتریس ً Reduced_R,Reduced_G,Reduced_B را کنار هم قرار دهید تا یک آرایه x*y*3 ایجاد شود. x , y همان ابعاد تصویر اولیه (image) هستند با استفاده از دستور astype ماتریس بدست آمده را به عدد صحیح تبدیل کنید.عکس بدست آمده را با imshow نمایش دهید. | Reduced_R = Reduced_R.reshape((dim[0], dim[1], 1))
Reduced_G = Reduced_G.reshape((dim[0], dim[1], 1))
Reduced_B = Reduced_B.reshape((dim[0], dim[1], 1))
reduced_image = np.dstack((Reduced_R, Reduced_G, Reduced_B))
final_image = reduced_image.astype(int)
print('final_image shape = ', final_image.shape)
plt.imshow(final... | Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
| MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
قسمت ۲.۵:استفاده از PCA برای کاهش بعد و حفظ ۹۹ درصد داده ها کل قسمت ۲.۴ را مجددا اجرا کنید. این بار تعداد مولفه ها را عددی قرار دهید که در هر سه ماتریس R,G,B حداقل ۹۹ درصد داده ها حفظ شود. | k = 188
rpca = PCA(n_components = k)
gpca = PCA(n_components = k)
bpca = PCA(n_components = k)
rpca.fit(R)
gpca.fit(G)
bpca.fit(B)
Transform_R = rpca.transform(R)
Transform_B = gpca.transform(G)
Transform_G = bpca.transform(B)
Reduced_R = rpca.inverse_transform(Transform_R)
Reduced_G = gpca.inverse_transform(Transform... | Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
| MIT | mini-project 2/CSPRJ2_9816603_abrehforoush.ipynb | Alireza-Abrehforoush/Mathematical-Foundations-of-Data-Science |
**Create Database in MongoDB** **Connect to Mongo DB Mars DB** | conn = 'mongodb://localhost:27017'
client = pymongo.MongoClient(conn)
# Define database and collection
db = client.mars
collection = db.items | _____no_output_____ | ADSL | Missions_to_Mars/.ipynb_checkpoints/mission_to_mars-checkpoint.ipynb | goldenMJ/web-scraping-challenge |
**Get executable_path** | !which chromedriver | /usr/local/bin/chromedriver
| ADSL | Missions_to_Mars/.ipynb_checkpoints/mission_to_mars-checkpoint.ipynb | goldenMJ/web-scraping-challenge |
**Step 1 - Scraping** **NASA Mars News**Scrape the NASA Mars News Site and collect the latest News Title and Paragraph Text. Assign the text to variables that you can reference later. | def latest_nasa_news():
executable_path = {'executable_path': '/usr/local/bin/chromedriver'}
browser = Browser('chrome', **executable_path, headless=False)
url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=L... | November 27, 2019
NASA's Briefcase-Size MarCO Satellite Picks Up Honors
The twin spacecraft, the first of their kind to fly into deep space, earn a Laureate from Aviation Week & Space Technology.
| ADSL | Missions_to_Mars/.ipynb_checkpoints/mission_to_mars-checkpoint.ipynb | goldenMJ/web-scraping-challenge |
**JPL Mars Space Images - Featured Image**Latest Mars image | def latest_mars_image():
executable_path = {'executable_path': '/usr/local/bin/chromedriver'}
browser = Browser('chrome', **executable_path, headless=False)
url_mars_image = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars"
browser.visit(url_mars_image)
#need timer to ensure page ha... | _____no_output_____ | ADSL | Missions_to_Mars/.ipynb_checkpoints/mission_to_mars-checkpoint.ipynb | goldenMJ/web-scraping-challenge |
**Twitter Latest Mars Weather** | def latest_mars_weather():
executable_path = {'executable_path': '/usr/local/bin/chromedriver'}
browser = Browser('chrome', **executable_path, headless=False)
url_mars_weather = "https://twitter.com/marswxreport?lang=en"
browser.visit(url_mars_weather)
#need timer to ensure page has load before... | ----------------------------------
6,792 km
----------------------------------
<br/>
| ADSL | Missions_to_Mars/.ipynb_checkpoints/mission_to_mars-checkpoint.ipynb | goldenMJ/web-scraping-challenge |
**Mars Hemispheres**Visit the USGS Astrogeology site here to obtain high resolution images for each of Mar's hemispheres.You will need to click each of the links to the hemispheres in order to find the image url to the full resolution image.Save both the image url string for the full resolution hemisphere image, and th... | def mars_image():
executable_path = {'executable_path': '/usr/local/bin/chromedriver'}
browser = Browser('chrome', **executable_path, headless=False)
url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars"
browser.visit(url)
#need a pause to ensure page has load ... | [<div class="description"><a class="itemLink product-item" href="/search/map/Mars/Viking/cerberus_enhanced"><h3>Cerberus Hemisphere Enhanced</h3></a><span class="subtitle" style="float:left">image/tiff 21 MB</span><span class="pubDate" style="float:right"></span><br/><p>Mosaic of the Cerberus hemisphere of Mars project... | ADSL | Missions_to_Mars/.ipynb_checkpoints/mission_to_mars-checkpoint.ipynb | goldenMJ/web-scraping-challenge |
Generate a realization of 5000 points within a single halo of conc=5 | from ellipsoidal_nfw import random_nfw_ellipsoid
npts = 5_000
conc = np.zeros(npts)+5.
x, y, z = random_nfw_ellipsoid(conc, b=2, c=3)
fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(12, 4))
fig.tight_layout(pad=3.0)
for ax in ax0, ax1, ax2:
xlim = ax.set_xlim(-4, 4)
ylim = ax.set_ylim(-4, 4)
__=ax0.scatt... | _____no_output_____ | BSD-3-Clause | notebooks/demo_ellipsoidal_nfw.ipynb | aphearin/ellipsoidal_nfw |
Generate a realization of a collection of 10 halos, each with 5000 points, each with different concentrations | npts_per_halo = 5_000
n_halos = 10
conc = np.linspace(5, 25, n_halos)
conc_halopop = np.repeat(conc, npts_per_halo)
x, y, z = random_nfw_ellipsoid(conc_halopop, b=2, c=3)
x = x.reshape((n_halos, npts_per_halo))
y = y.reshape((n_halos, npts_per_halo))
z = z.reshape((n_halos, npts_per_halo))
| _____no_output_____ | BSD-3-Clause | notebooks/demo_ellipsoidal_nfw.ipynb | aphearin/ellipsoidal_nfw |
This is Task 2 of GRIP internshipTo Explore Supervised Machine Learning | #Importing all the libraries required for the code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Loading Data from the given URL
url = "http://bit.ly/w-data"
data = pd.read_csv(url)
print("shape of dataset: {}".format(data.shape))
print(data.head(5))
# Plotting the dist... | _____no_output_____ | MIT | #Task_3/task_3.ipynb | ViKrAm-Bais/sparks_foundation_grip |
Preparing the data for training Dividing the data into attributes (Inputs) and labels (Outputs) | # Dividing the data into attributes(Inputs) and label(Outputs)
x = data.iloc[:, :-1].values
y = data.iloc[:, 1].values | _____no_output_____ | MIT | #Task_3/task_3.ipynb | ViKrAm-Bais/sparks_foundation_grip |
splitting the data set into tranining and testing 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.2, random_state=0)
print("training dataset shape: {}".format(x_train.shape))
print("testing dataset shape: {}".format(x_test.shape)) | training dataset shape: (20, 1)
testing dataset shape: (5, 1)
| MIT | #Task_3/task_3.ipynb | ViKrAm-Bais/sparks_foundation_grip |
Training the model | # Importing library for linear regression
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x_train, y_train) | _____no_output_____ | MIT | #Task_3/task_3.ipynb | ViKrAm-Bais/sparks_foundation_grip |
Plotting the linear regression line with training data | # Defining the equation of line
print("coefficient: {}, intercept: {}".format(model.coef_, model.intercept_))
line = model.coef_*x + model.intercept_
# plotting line with data
plt.figure(figsize=(10, 6), dpi=100)
#plotting training data
plt.scatter(x_train, y_train, color="c",marker="*")
#plotting testing data
plt.scat... | coefficient: [9.91065648], intercept: 2.018160041434662
| MIT | #Task_3/task_3.ipynb | ViKrAm-Bais/sparks_foundation_grip |
Results | # getting predictions for test data
y_predicted = model.predict(x_test)
# Comparing Actual vs Predicted
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_predicted})
print(df) | Actual Predicted
0 20 16.884145
1 27 33.732261
2 69 75.357018
3 30 26.794801
4 62 60.491033
| MIT | #Task_3/task_3.ipynb | ViKrAm-Bais/sparks_foundation_grip |
predicted score if a student study for 9.25 hrs in a day | s_hours = 9.25
s_score = model.predict([[shours]])
print("predicted score if a student study for {} hrs in a day is {}".format(s_hours, s_score[0])) | predicted score if a student study for 9.25 hrs in a day is 93.69173248737539
| MIT | #Task_3/task_3.ipynb | ViKrAm-Bais/sparks_foundation_grip |
Calculating error for the model | from sklearn import metrics
print('Mean Absolute Error: {}'.format(metrics.mean_absolute_error(y_test, y_predicted)))
accuracy = 100 * model.score(x_test, y_test)
print("Accuracy(%): ", accuracy)
| _____no_output_____ | MIT | #Task_3/task_3.ipynb | ViKrAm-Bais/sparks_foundation_grip |
Project 2: Spotify Table of ContentsBackground Knowledge: Topic1. The Data Science Life Cycle a. Formulating a question or problem b. Acquiring and cleaning data c. Conducting exploratory data analysis d. Using prediction and inference to draw conclusions Background Knowledge If you listen to music, ... | spotify = Table.read_table('data/spotify.csv')
spotify.show(10) | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: It's important to evalute our data source. What do you know about the source? What motivations do they have for collecting this data? What data is missing? *Insert answer here* Question: Do you see any missing (nan) values? Why might they be there? *Insert answer here* Question: We want to learn more ab... | total_rows = spotify.num_rows
total_rows | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
*Insert answer here* Conducting Exploratory Data Analysis Visualizations help us to understand what the dataset is telling us. We will be using bar charts, scatter plots, and line plots to try to answer questions like the following:> What audio features make a song popular and which artists have these songs? How have... | #Access the duration column as an array.
duration = spotify.column("duration_ms")
duration
#Divide the milliseconds by 1000
duration_seconds = duration / 1000
duration_seconds
#Now convert duration_seconds to minutes.
duration_minutes = duration_seconds / 60
duration_minutes | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: How would we find the average duration (in minutes) of the songs in this dataset? | avg_song_length_mins = np.mean(duration_minutes)
avg_song_length_mins | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Now, we can add in the duration for each song (in minutes) by adding a column to our `spotify` table called `duration_min`. Run the following cell to do so. | #This cell will add the duration in minutes column we just created to our dataset.
spotify = spotify.with_columns('duration_min', duration_minutes)
spotify | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Artist Comparison Let's see if we can find any meaningful difference in the average length of song for different artists. Note: Now that we have the average duration for each song, you can compare average song length between two artists. Below is an example! | sam_smith = spotify.where("track_artist", are.equal_to("Sam Smith"))
sam_smith
sam_smith_mean = sam_smith.column("duration_min").mean()
sam_smith_mean
#In this cell, choose an artist you want to look at.
artist_name = spotify.where("track_artist", "Kanye West").column("duration_min").mean()
artist_name
#In this cell, c... | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
This exercise was just one example of how you can play around with data and answer questions. Top Genres and ArtistsIn this section, we are interested in the categorical information in our dataset, such as the playlist each song comes from or the genre. There are almost 33,000 songs in our dataset, so let's do some in... | genre_counts = spotify.group('playlist_genre')
genre_counts | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: In our dataset, it looks like the most popular genre is EDM. Make a barchart below to show how the other genres compare. | genre_counts.barh('playlist_genre', 'count') | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Notice that it was difficult to analyze the above bar chart because the data wasn't sorted first. Let's sort our data and make a new bar chart so that it is much easier to make comparisons. | genre_counts_sorted = genre_counts.sort('count', descending = True)
genre_counts_sorted
genre_counts_sorted.barh('playlist_genre', 'count') | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: Was this what you expected? Which genre did you think would be the most popular? *Insert answer here.* Question: Let's take a look at all the artists in the dataset. We can take a look at the top 25 artists based on the number of songs they have in our dataset. We'll follow a similar method as we did when ... | #Here, we will group and sort in the same line.
artists_grouped = spotify.group('track_artist').sort('count', descending=True)
artists_grouped
top_artists = artists_grouped.take(np.arange(0, 25))
top_artists
top_artists.barh('track_artist', 'count') | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: What do you notice about the top 25 artists in our dataset? *insert answer here* Playlist Popularity In our dataset, each song is listed as belonging to a particular playlist, and each song is given a "popularity score", called the `track_popularity`. Using the `track_popularity`, we can calculate an *agg... | spotify_subset = spotify.select(['playlist_name', 'track_popularity'])
spotify_subset | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Note: By grouping, we can get the number of songs from each playlist. | playlists = spotify_subset.group('playlist_name')
playlists | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: We can use the group method again, this time passing in a second argument collect, which says that we want to take the sum rather than the count when grouping. This results in a table with the total aggregate popularity of each playlist. | #Run this cell.
total_playlist_popularity = spotify_subset.group('playlist_name', collect = sum)
total_playlist_popularity | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Similar to when we found duration in minutes, we can once again use the `column` method to access just the `track_popularity sum` column, and add it to our playlists table using the `with_column` method. | agg_popularity = total_playlist_popularity.column('track_popularity sum')
playlists = playlists.with_column('aggregate_popularity', agg_popularity)
playlists | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: Do you think that the most popular playlist would be the one with the highest aggregate_popularity score, or the one with the highest number of songs? We can sort our playlists table and compare the outputs. | playlists.sort('count', descending=True) | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: Now sort by aggregate popularity. | playlists.sort('aggregate_popularity', descending=True) | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Comparing these two outputs shows us that the "most popular playlist" depends on how we judge popularity. If we have a playlist that has only a few songs, but each of those songs are really popular, should that playlist be higher on the popularity rankings? By way of calculation, playlists with more songs will have a h... | #Run this cell to get the average.
avg_popularity = playlists.column('aggregate_popularity') / playlists.column('count')
#Now add it to the playlists table.
playlists = playlists.with_column('average_popularity', avg_popularity)
playlists | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Let's see if our "most popular playlist" changes when we judge popularity by the average popularity of the songs on a playlist. | playlists.sort('average_popularity', descending=True) | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Looking at the table above, we notice that 8/10 of the top 10 most popular playlists by the `average_popularity` metric are playlists with less than 100 songs. Just because a playlist has a lot of songs, or a high aggregate popularity, doesn't mean that the average popularity of a song on that playlist is high. Our new... | top_25_playlists = playlists.sort('average_popularity', descending=True).take(np.arange(25))
top_25_playlists.barh('playlist_name', 'average_popularity') | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Creating a new metric like `average_popularity` helps us more accurately and fairly measure the popularity of a playlist. We saw before when looking at the top 25 artists that they were all male. Now looking at the top playlists, we see that the current landscape of popular playlists and music may have an effect on the... | spotify.show(5) | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: Fill in the following cell the data according to the creation_year you choose. | #Fill in the year as an integer.
by_year = spotify.where("creation_year", are.equal_to(2018))
by_year | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Based on the dataset you have now, use previous techniques to find the most popular song during that year. First group by what you want to look at, for example, artist/playlist/track. | your_grouped = by_year.group("playlist_name")
pop_track = your_grouped.sort("count", descending = True)
pop_track
pop_track.take(np.arange(25)).barh("playlist_name", "count") | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
Question: Finally, use this cell if you want to look at the popularity of a track released on a specific date. It's very similar to the process above. | by_date = spotify.where("track_album_release_date", are.equal_to("2019-06-14"))
your_grouped = by_date.group("track_artist")
pop_track = your_grouped.sort("count", descending = True)
pop_track.take(np.arange(10)).barh("track_artist", "count") | _____no_output_____ | BSD-3-Clause | Project_2/Spotify/Spotify_Solutions.ipynb | ds-modules/BUDS-SU21-Dev |
[01/02/22] LTH on a Data Diet -- 2 Pass Initial Results | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pathlib import Path
import seaborn as sns
plt.style.use('default')
sns.set_theme(
style='ticks',
font_scale=1.2,
rc={
'axes.linewidth': '0.8',
'axes.grid': True,
'figure.constrained_layout.use': True,
... | _____no_output_____ | MIT | nbs/22_01_02__LTH_Data_Diet_2_Pass_Initial.ipynb | mansheej/open_lth |
Figure 0016 | exp_meta_paths = [
Path(f'/home/mansheej/open_lth_data/lottery_b279562b990bac9b852b17b287fca1ef/'),
Path(f'/home/mansheej/open_lth_data/lottery_78a119e24960764e0de0964887d2597f/'),
Path(f'/home/mansheej/open_lth_data/lottery_2cb77ad7e940a06d07b04a4b63fd718d/'),
Path(f'/home/mansheej/open_lth_data/lotter... | _____no_output_____ | MIT | nbs/22_01_02__LTH_Data_Diet_2_Pass_Initial.ipynb | mansheej/open_lth |
Naive Bayes and Logistic Regression In this tutorial, we'll explore training and evaluation of Naive Bayes and Logitistic Regression Classifiers.To start, we import the standard BIDMach class definitions. | import $exec.^.lib.bidmach_notebook_init | 1 CUDA device found, CUDA version 8.0
| BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
Now we load some training and test data, and some category labels. The data come from a news collection from Reuters, and is a "classic" test set for classification. Each article belongs to one or more of 103 categories. The articles are represented as Bag-of-Words (BoW) column vectors. For a data matrix A, element A(i... | val dict = "../data/rcv1/"
val traindata = loadSMat(dict+"docs.smat.lz4")
val traincats = loadFMat(dict+"cats.fmat.lz4")
val testdata = loadSMat(dict+"testdocs.smat.lz4")
val testcats = loadFMat(dict+"testcats.fmat.lz4")
min(traindata, 1, traindata) // the first "traindata" argument is the input, ... | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
Get the word and document counts from the data. This turns out to be equivalent to a matrix multiply. For a data matrix A and category matrix C, we want all (cat, word) pairs (i,j) such that C(i,k) and A(j,k) are both 1 - this means that document k contains word j, and is also tagged with category i. Summing over all d... | val truecounts = traincats *^ traindata
val wcounts = truecounts + 0.5
val negwcounts = sum(truecounts) - truecounts + 0.5
val dcounts = sum(traincats,2) | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
Now compute the probabilities * pwordcat = probability that a word is in a cat, given the cat.* pwordncat = probability of a word, given the complement of the cat.* pcat = probability that doc is in a given cat. * spcat = sum of pcat probabilities (> 1 because docs can be in multiple cats) | val pwordcat = wcounts / sum(wcounts,2) // Normalize the rows to sum to 1.
val pwordncat = negwcounts / sum(negwcounts,2) // Each row represents word probabilities conditioned on one cat.
val pcat = dcounts / traindata.ncols
val spcat = sum(pcat) | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
Now take the logs of those probabilities. Here we're using the formula presented here to match Naive Bayes to Logistic Regression for independent data.For each word, we compute the log of the ratio of the complementary word probability over the in-class word probability. For each category, we compute the log of the rat... | val lpwordcat = ln(pwordncat/pwordcat) // ln is log to the base e (natural log)
val lpcat = ln((spcat-pcat)/pcat) | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
Here's where we apply Naive Bayes. The formula we're using is borrowed from here.$${\rm Pr}(c|X_1,\ldots,X_k) = \frac{1}{1 + \frac{{\rm Pr}(\neg c)}{{\rm Pr}(c)}\prod_{i-1}^k\frac{{\rm Pr}(X_i|\neg c)}{{\rm Pr}(X_i|c)}}$$and we can rewrite$$\frac{{\rm Pr}(\neg c)}{{\rm Pr}(c)}\prod_{i-1}^k\frac{{\rm Pr}(X_i|\neg c)}{{\... | val logodds = lpwordcat * testdata + lpcat
val preds = 1 / (1 + exp(logodds)) | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
To measure the accuracy of the predictions above, we can compute the probability that the classifier outputs the right label. We used this formula in class for the expected accuracy for logistic regression. The "dot arrow" operator takes dot product along rows: | val acc = ((preds ∙→ testcats) + ((1-preds) ∙→ (1-testcats)))/preds.ncols
acc.t | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
Raw accuracy is not a good measure in most cases. When there are few positives (instances in the class vs. its complement), accuracy simply drives down false-positive rate at the expense of false-negative rate. In the worst case, the learner may always predict "no" and still achieve high accuracy. ROC curves and ROC Ar... | val itest = 6
val scores = preds(itest,?)
val good = testcats(itest,?)
val bad = 1-testcats(itest,?)
val rr =roc(scores,good,bad,100) | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
> TODO 1: In the cell below, write an expression to derive the ROC Area under the curve (AUC) given the curve rr. rr gives the ROC curve y-coordinates at 100 evenly-spaced X-values from 0 to 1.0. | // auc = | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
> TODO 2: In the cell below, write the value of AUC returned by the expression above. Logistic Regression Now lets train a logistic classifier on the same data. BIDMach has an umbrella classifier called GLM for Generalized Linear Model. GLM includes linear regression, logistic regression (with log accuracy or direct a... | val predcats = zeros(testcats.nrows, testcats.ncols)
val (mm,mopts) = GLM.learner(traindata, traincats, GLM.maxp)
mopts.what | Option Name Type Value
=========== ==== =====
addConstFeat boolean false
aopts Opts null
autoReset boolean true
batchSize int 10000
checkPointFile String null
checkPointInterval float 0.0
clipByValue f... | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
The most important options are:* lrate: the learning rate* batchSize: the minibatch size* npasses: the number of passes over the datasetWe'll use the following parameters for this training run. | mopts.lrate=1.0
mopts.batchSize=1000
mopts.npasses=2
mm.train
val (nn, nopts) = GLM.predictor(mm.model, testdata)
nn.predict
val predcats = FMat(nn.preds(0))
val lacc = (predcats ∙→ testcats + (1-predcats) ∙→ (1-testcats))/preds.ncols
lacc.t
mean(lacc) | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
Since we have the accuracy scores for both Naive Bayes and Logistic regression, we can plot both of them on the same axes. Naive Bayes is red, Logistic regression is blue. The x-axis is the category number from 0 to 102. The y-axis is the absolute accuracy of the predictor for that category. | val axaxis = row(0 until 103)
plot(axaxis, acc, axaxis, lacc) | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
> TODO 3: With the full training set (700k training documents), Logistic Regression is noticeably more accurate than Naive Bayes in every category. What do you observe in the plot above? Why do you think this is? Next we'll compute the ROC plot and ROC area (AUC) for Logistic regression for category itest. | val lscores = predcats(itest,?)
val lrr =roc(lscores,good,bad,100)
val auc = mean(lrr) // Fill in using the formula you used before | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
We computed the ROC curve for Naive Bayes earlier, so now we can plot them on the same axes. Naive Bayes is once again in red, Logistic regression in blue. | val rocxaxis = row(0 until 101)
plot(rocxaxis, rr, rocxaxis, lrr) | _____no_output_____ | BSD-3-Clause-No-Nuclear-License-2014 | tutorials/NBandLR.ipynb | oeclint/BIDMach |
I'll be demonstrating just the classification problems , you can build regression following a very similar process | # data prep from previous module
ci_train=pd.read_csv('census_income.csv')
# if you have a test data, you can combine as shown in the earlier modules
ci_train.head()
pd.crosstab(ci_train['education'],ci_train['education.num'])
ci_train.drop(['education'],axis=1,inplace=True)
ci_train['Y'].value_counts().index
ci_train... | _____no_output_____ | Apache-2.0 | Census_income.ipynb | umairnsr87/deploying-ml-model-with-django |
Hyper Parameters For Decision Trees* criterion : there are two options available , "entropy" and "gini". These are the homogeneity measures that we discussed. By default "gini" is used * The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_... | from sklearn.model_selection import RandomizedSearchCV
params={ 'class_weight':[None,'balanced'],
'criterion':['entropy','gini'],
'max_depth':[None,5,10,15,20,30,50,70],
'min_samples_leaf':[1,2,5,10,15,20],
'min_samples_split':[2,5,10,15,20]
}
2*2*8*6*5
from sklearn.tree... | _____no_output_____ | Apache-2.0 | Census_income.ipynb | umairnsr87/deploying-ml-model-with-django |
Printing the tree model is a little tricky in python. We'll have to output our tree to a .dot file using graphviz package. From there using graphviz.Source function we can print our tree for display. Here is how : | random_search.best_estimator_
def report(results, n_top=3):
for i in range(1, n_top + 1):
candidates = np.flatnonzero(results['rank_test_score'] == i)
for candidate in candidates:
print("Model with rank: {0}".format(i))
print("Mean validation score: {0:.3f} (std: {1:.5f})".fo... | _____no_output_____ | Apache-2.0 | Census_income.ipynb | umairnsr87/deploying-ml-model-with-django |
Open mytree.dot file in a simple text editor and copy and paste the code here to visualise your tree : http://webgraphviz.com Additional Hyper paprameters for RandomForests* n_estimators : number of trees in the forest . defaults to 10. good starting point will be 100. Its one of the hyper parameters. We'll see how to... |
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier()
# this here is the base classifier we are going to try
# we will be supplying different parameter ranges to our randomSearchCV which in turn
# will pass it on to this classifier
# Utility function to report best scores. This simply ac... | _____no_output_____ | Apache-2.0 | Census_income.ipynb | umairnsr87/deploying-ml-model-with-django |
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=50, max_features=10, max_leaf_nodes=None, min_impurity_split=1e-07, min_samples_leaf=10, min_samples_split=20, min_weight_fraction_leaf=0.0, n_estimators=300, n_jobs=1, oob_score=False, rand... | report(random_search.cv_results_,5)
# select the best values from results above, they will vary slightly with each run
rf=RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=50,
max_features=10, max_leaf_nodes=None, min_impurity_split=1e-07,
... | _____no_output_____ | Apache-2.0 | Census_income.ipynb | umairnsr87/deploying-ml-model-with-django |
Feature Importance | feat_imp_df=pd.DataFrame({'features':x_train.columns,'importance':rf.feature_importances_})
feat_imp_df.sort_values('importance',ascending=False) | _____no_output_____ | Apache-2.0 | Census_income.ipynb | umairnsr87/deploying-ml-model-with-django |
Partial Dependence Plot | var_name='education.num'
preds=rf.predict_proba(x_train)[:,1]
# part_dep_data
var_data=pd.DataFrame({'var':x_train[var_name],'response':preds})
import seaborn as sns
sns.lmplot(x='var',y='response',data=var_data,fit_reg=False)
import statsmodels.api as sm
smooth_data=sm.nonparametric.lowess(var_data['response'],var_d... | _____no_output_____ | Apache-2.0 | Census_income.ipynb | umairnsr87/deploying-ml-model-with-django |
Data Cleaning | # Checking for Consistent Column Name
df.columns
# Checking for Datatypes
df.dtypes
# Check for missing nan
df.isnull().isnull().sum()
# Checking for Date
df["DATE"]
df.AUTHOR
# Convert the Author Name to First Name and Last Name
#df[["FIRSTNAME","LASTNAME"]] = df['AUTHOR'].str.split(expand=True) | _____no_output_____ | Unlicense | Youtube_Comments-checkpoint.ipynb | Vineeta12345/spam-detection |
Working With Text Content | df_data = df[["CONTENT","CLASS"]]
df_data.columns
df_x = df_data['CONTENT']
df_y = df_data['CLASS'] | _____no_output_____ | Unlicense | Youtube_Comments-checkpoint.ipynb | Vineeta12345/spam-detection |
Feature Extraction From Text CountVectorizer TfidfVectorizer | cv = CountVectorizer()
ex = cv.fit_transform(["Great song but check this out","What is this song?"])
ex.toarray()
cv.get_feature_names()
# Extract Feature With CountVectorizer
corpus = df_x
cv = CountVectorizer()
X = cv.fit_transform(corpus) # Fit the Data
X.toarray()
# get the feature names
cv.get_feature_names() | _____no_output_____ | Unlicense | Youtube_Comments-checkpoint.ipynb | Vineeta12345/spam-detection |
Model Building | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, df_y, test_size=0.33, random_state=42)
X_train
# Naive Bayes Classifier
from sklearn.naive_bayes import MultinomialNB
clf = MultinomialNB()
clf.fit(X_train,y_train)
clf.score(X_test,y_test)
# Accuracy of our Mode... | _____no_output_____ | Unlicense | Youtube_Comments-checkpoint.ipynb | Vineeta12345/spam-detection |
Save The Model | import pickle
naivebayesML = open("YtbSpam_model.pkl","wb")
pickle.dump(clf,naivebayesML)
naivebayesML.close()
# Load the model
ytb_model = open("YtbSpam_model.pkl","rb")
new_model = pickle.load(ytb_model)
new_model
# Sample Prediciton 3
comment2 = ["Hey Music Fans I really appreciate all of you,but see this song too"]... | Spam
| Unlicense | Youtube_Comments-checkpoint.ipynb | Vineeta12345/spam-detection |
Self-Driving Car Engineer Nanodegree Project: **Finding Lane Lines on the Road** ***In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a se... | #importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline | _____no_output_____ | MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Read in an Image | #reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type(image), 'with dimensions:', image.shape)
plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gra... | This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
| MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Ideas for Lane Detection Pipeline **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**`cv2.inRange()` for color selection `cv2.fillPoly()` for regions selection `cv2.line()` to draw lines on an image given endpoints `cv2.addWeighted()` to coadd / overlay two i... | import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, c... | _____no_output_____ | MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Test ImagesBuild your pipeline to work on the images in the directory "test_images" **You should make sure your pipeline works well on these images before you try the videos.** | import os
os.listdir("test_images/") | _____no_output_____ | MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Build a Lane Finding Pipeline Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters. | # TODO: Build your pipeline that will draw lane lines on the test_images
# then save them to the test_images_output directory.
#output all processed images for documentation
images=os.listdir("test_images/")
for filename in images:
#first read image and change to gray scale
image = mpimg.imread("test_images/... | C:\Users\Redaaaaaa\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py:3373: RuntimeWarning: Mean of empty slice.
out=out, **kwargs)
C:\Users\Redaaaaaa\Anaconda3\lib\site-packages\numpy\core\_methods.py:170: RuntimeWarning: invalid value encountered in double_scalars
ret = ret.dtype.type(ret / rcount)
| MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Test on VideosYou know what's cooler than drawing lanes over images? Drawing lanes over video!We can test our solution on two provided videos:`solidWhiteRight.mp4``solidYellowLeft.mp4`**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel... | # Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
def process_image(image):
# NOTE: The output you return should be a color image (3 channel) for processing video below
# TODO: put your pipeline here,
#color select for lane to... | _____no_output_____ | MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Let's try the one with the solid white lane on the right first ... | white_output = 'test_videos_output/solidWhiteRight.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and... |
t: 0%| | 0/221 [00:00<?, ?it/s, now=None] | MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice. | HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output)) | _____no_output_____ | MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Improve the draw_lines() function**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about de... | yellow_output = 'test_videos_output/solidYellowLeft.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start an... | _____no_output_____ | MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Writeup and SubmissionIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_templat... | challenge_output = 'test_videos_output/challenge.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and e... | _____no_output_____ | MIT | P1.ipynb | RedaMokarrab/Nano_Degree_Self_Driving |
Data Science Unit 1 Sprint Challenge 1 Loading, cleaning, visualizing, and analyzing dataIn this sprint challenge you will look at a dataset of the survival of patients who underwent surgery for breast cancer.http://archive.ics.uci.edu/ml/datasets/Haberman%27s+SurvivalData Set Information:The dataset contains cases f... | import pandas as pd
breast = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/haberman/haberman.data',names=['age','year_operation','nodes','survived'])
print(breast.shape)
print(breast.isna().sum())
labels = {'survived': {2:0}}
breast.replace(labels, inplace=True)
breast.survived.value_counts()
pr... | age year_operation nodes survived
0 30 64 1 1
1 30 62 3 1
2 30 65 0 1
3 31 59 2 1
4 31 65 4 1
| MIT | Boris_Krant_DS_Unit_1_Sprint_Challenge_1.ipynb | bkrant/DS-Unit-1-Sprint-1-Dealing-With-Data |
Part 2 - Examine the distribution and relationships of the featuresExplore the data - create at least *2* tables (can be summary statistics or crosstabulations) and *2* plots illustrating the nature of the data.This is open-ended, so to remind - first *complete* this task as a baseline, then go on to the remaining sec... | print(breast.corr())
print(breast.describe())
sns.heatmap(breast.corr());
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
sns.pairplot(breast);
g = sns.FacetGrid(breast, row="survived", margin_titles=True)
bins = np.linspace(0, breast.age.max())
g.map(plt.hist, "age", color="steelblue", bins=bi... | _____no_output_____ | MIT | Boris_Krant_DS_Unit_1_Sprint_Challenge_1.ipynb | bkrant/DS-Unit-1-Sprint-1-Dealing-With-Data |
HVAC with Amazon SageMaker RL--- IntroductionHVAC stands for Heating, Ventilation and Air Conditioning and is responsible for keeping us warm and comfortable indoors. HVAC takes up a whopping 50% of the energy in a building and accounts for 40% of energy use in the US [1, 2]. Several control system optimizations have... | import sagemaker
import boto3
import sys
import os
import glob
import re
import subprocess
import numpy as np
from IPython.display import HTML
import time
from time import gmtime, strftime
sys.path.append("common")
from misc import get_execution_role, wait_for_s3_object
from docker_utils import build_and_push_docker_im... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Setup S3 bucketCreate a reference to the default S3 bucket that will be used for model outputs. | sage_session = sagemaker.session.Session()
s3_bucket = sage_session.default_bucket()
s3_output_path = 's3://{}/'.format(s3_bucket)
print("S3 bucket path: {}".format(s3_output_path)) | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Define Variables We define a job below that's used to identify our jobs. | # create unique job name
job_name_prefix = 'rl-hvac' | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Configure settingsYou can run your RL training jobs locally on the SageMaker notebook instance or on SageMaker training. In both of these scenarios, you can run in either 'local' (where you run the commands) or 'SageMaker' mode (on SageMaker training instances). 'local' mode uses the SageMaker Python SDK to run your c... | # run local (on this machine)?
# or on sagemaker training instances?
local_mode = False
if local_mode:
instance_type = 'local'
else:
# choose a larger instance to avoid running out of memory
instance_type = "ml.m4.4xlarge" | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Create an IAM roleEither get the execution role when running from a SageMaker notebook instance `role = sagemaker.get_execution_role()` or, when running from local notebook instance, use utils method `role = get_execution_role()` to create an execution role. | try:
role = sagemaker.get_execution_role()
except:
role = get_execution_role()
print("Using IAM role arn: {}".format(role)) | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Install docker for `local` modeIn order to work in `local` mode, you need to have docker installed. When running from your local machine, please make sure that you have docker or docker-compose (for local CPU machines) and nvidia-docker (for local GPU machines) installed. Alternatively, when running from a SageMaker n... | # Only run from SageMaker notebook instance
if local_mode:
!/bin/bash ./common/setup.sh | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_hvac_coach_energyplus/rl_hvac_coach_energyplus.ipynb | P15241328/amazon-sagemaker-examples |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.