Dataset Viewer
content
stringlengths 73
1.12M
| license
stringclasses 3
values | path
stringlengths 9
197
| repo_name
stringlengths 7
106
| chain_length
int64 1
144
|
---|---|---|---|---|
<jupyter_start><jupyter_text>___
___
Note-
1) First make the copy of the project in your drive then start with the solution.
2) Dont run the cell directly, first add a call above it then run the cell so that you dont miss the solution.
# Logistic Regression Project
In this project we will be working with a fake advertising data set, indicating whether or not a particular internet user clicked on an Advertisement. We will try to create a model that will predict whether or not they will click on an ad based off the features of that user.
This data set contains the following features:
* 'Daily Time Spent on Site': consumer time on site in minutes
* 'Age': cutomer age in years
* 'Area Income': Avg. Income of geographical area of consumer
* 'Daily Internet Usage': Avg. minutes a day consumer is on the internet
* 'Ad Topic Line': Headline of the advertisement
* 'City': City of consumer
* 'Male': Whether or not consumer was male
* 'Country': Country of consumer
* 'Timestamp': Time at which consumer clicked on Ad or closed window
* 'Clicked on Ad': 0 or 1 indicated clicking on Ad
## Import Libraries
**Import a few libraries you think you'll need (Or just import them as you go along!)**<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns<jupyter_output><empty_output><jupyter_text>## Get the Data
**Read in the advertising.csv file and set it to a data frame called ad_data.**<jupyter_code>df = pd.read_csv('advertising.csv')<jupyter_output><empty_output><jupyter_text>**Check the head of ad_data**<jupyter_code>df.head()
df.tail()
df['Ad Topic Line']
ad = pd.get_dummies(df['Ad Topic Line'])
ad<jupyter_output><empty_output><jupyter_text>** Use info and describe() on ad_data**<jupyter_code>df.info()
df.describe()
<jupyter_output><empty_output><jupyter_text>## Exploratory Data Analysis
Let's use seaborn to explore the data!
Try recreating the plots shown below!
** Create a histogram of the Age**<jupyter_code>sns.histplot(df['Age'] , bins= 30)
<jupyter_output><empty_output><jupyter_text>**Create a jointplot showing Area Income versus Age.**<jupyter_code>sns.jointplot(x = 'Age' , y = 'Area Income' , data = df)
<jupyter_output><empty_output><jupyter_text>** Create a jointplot of 'Daily Time Spent on Site' vs. 'Daily Internet Usage'**<jupyter_code>sns.jointplot(x = 'Daily Time Spent on Site' , y = 'Daily Internet Usage' , data = df , color = 'Green')
<jupyter_output><empty_output><jupyter_text>** Finally, create a pairplot with the hue defined by the 'Clicked on Ad' column feature.**<jupyter_code>sns.pairplot(data = df ,palette = 'BuGn_r' , hue = 'Clicked on Ad')
<jupyter_output><empty_output><jupyter_text># Logistic Regression
Now it's time to do a train test split, and train our model!
You'll have the freedom here to choose columns that you want to train on!** Split the data into training set and testing set using train_test_split**<jupyter_code>sns.heatmap(df.corr() , annot = True)
from sklearn.model_selection import train_test_split
df.info()
x1 = df[['Age','Area Income','Daily Time Spent on Site','Daily Internet Usage','Male']]
y1 = df['Clicked on Ad']
x1_train , x1_test , y1_train , y1_test = train_test_split(x1,y1,test_size = 0.3)<jupyter_output><empty_output><jupyter_text>** Train and fit a logistic regression model on the training set.**<jupyter_code>from sklearn.linear_model import LogisticRegression
log_model = LogisticRegression()
log_model.fit(x1_train , y1_train)<jupyter_output><empty_output><jupyter_text>## Predictions and Evaluations
** Now predict values for the testing data.**<jupyter_code>predict1 = log_model.predict(x1_test)<jupyter_output><empty_output><jupyter_text>** Create a classification report for the model.**<jupyter_code>from sklearn.metrics import confusion_matrix , classification_report
confusion_matrix( y1_test , predict1)
print(classification_report(y1_test, predict1))
<jupyter_output><empty_output>
|
no_license
|
/Logistic_Regression_Assignment.ipynb
|
young-ai-expert/Data-Science-Projects
| 12 |
<jupyter_start><jupyter_text># Vehicle detection and tracking project*picture by Udacity*<jupyter_code>import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import os
import matplotlib.image as mpimg
%matplotlib qt
%matplotlib inline
vehs = []
for image in os.listdir(os.getcwd() + "/vehicles/GTI_Right"):
vehs.append(os.getcwd() + "/vehicles/GTI_Right/" + image)
for image in os.listdir(os.getcwd() + "/vehicles/GTI_MiddleClose"):
vehs.append(os.getcwd() + "/vehicles/GTI_MiddleClose/" + image)
for image in os.listdir(os.getcwd() + "/vehicles/GTI_Left"):
vehs.append(os.getcwd() + "/vehicles/GTI_Left/" + image)
for image in os.listdir(os.getcwd() + "/vehicles/GTI_Far"):
vehs.append(os.getcwd() + "/vehicles/GTI_Far/" + image)
for image in os.listdir(os.getcwd() + "/vehicles/KITTI_extracted"):
vehs.append(os.getcwd() + "/vehicles/KITTI_extracted/" + image)
non_vehs = []
for image in os.listdir(os.getcwd() + "/non-vehicles/GTI"):
non_vehs.append(os.getcwd() + "/non-vehicles/GTI/" + image)
for image in os.listdir(os.getcwd() + "/non-vehicles/Extras"):
non_vehs.append(os.getcwd() + "/non-vehicles/Extras/" + image)
print(len(vehs))
print(len(non_vehs))
print(non_vehs[0])
testimg1 = mpimg.imread("test_images/test1.jpg")
plt.imshow(testimg1)
plt.show()<jupyter_output><empty_output><jupyter_text>## 1. Functions to extract the features### 1.1 get color features<jupyter_code>def color_hist(img, nbins=32, bins_range=(0, 256)):
# Compute the histogram of the color channels separately
channel1_hist = np.histogram(img[:, :, 0], bins=nbins, range=bins_range)
channel2_hist = np.histogram(img[:, :, 1], bins=nbins, range=bins_range)
channel3_hist = np.histogram(img[:, :, 2], bins=nbins, range=bins_range)
# Concatenate the histograms into a single feature vector
hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))
# Return the individual histograms, bin_centers and feature vector
return hist_features
def bin_spatial(img, size=(32, 32)):
features = cv2.resize(img, size).ravel()
# Return the feature vector
return features<jupyter_output><empty_output><jupyter_text>### 1.2 get hog features<jupyter_code>from skimage.feature import hog
def get_hog_features(img, orient, pix_per_cell, cell_per_block,
vis=False, feature_vec=True):
if vis == True:
features, hog_image = hog(img, orientations=orient,
pixels_per_cell=(pix_per_cell, pix_per_cell),
cells_per_block=(cell_per_block, cell_per_block),
transform_sqrt=True,
visualise=vis, feature_vector=feature_vec)
return features, hog_image
else:
features = hog(img, orientations=orient,
pixels_per_cell=(pix_per_cell, pix_per_cell),
cells_per_block=(cell_per_block, cell_per_block),
transform_sqrt=True,
visualise=vis, feature_vector=feature_vec)
return features
# example
exp_img = cv2.cvtColor(mpimg.imread(vehs[0]), cv2.COLOR_RGB2GRAY)
feats, hogImg = get_hog_features(exp_img, 8, 8, 2, vis=True, feature_vec=True)
fig1 = plt.figure(figsize = (10,10))
ax1 = fig1.add_subplot(121)
ax1.imshow(mpimg.imread(vehs[0]), interpolation='none')
ax1.set_title('Initical picture')
ax3 = fig1.add_subplot(122)
ax3.imshow(hogImg, interpolation='none', cmap="gray")
ax3.set_title('Image with HOG features')
plt.show()<jupyter_output>C:\Anaconda3\envs\tensorflow-with-gpu-10\lib\site-packages\skimage\feature\_hog.py:119: skimage_deprecation: Default value of `block_norm`==`L1` is deprecated and will be changed to `L2-Hys` in v0.15
'be changed to `L2-Hys` in v0.15', skimage_deprecation)
<jupyter_text>### 1.3 combine and normalize<jupyter_code>def extract_features(imgs, color_space='RGB', spatial_size=(32, 32),
hist_bins=32, orient=9,
pix_per_cell=8, cell_per_block=2, hog_channel=0,
spatial_feat=True, hist_feat=True, hog_feat=True):
# Create a list to append feature vectors to
features = []
# Iterate through the list of images
for file in imgs:
file_features = []
# Read in each one by one
image = mpimg.imread(file)
# Apply color conversion
if color_space != 'RGB':
if color_space == 'HSV':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
elif color_space == 'LUV':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV)
elif color_space == 'HLS':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)
elif color_space == 'YUV':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)
elif color_space == 'YCrCb':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb)
else:
feature_image = np.copy(image)
if spatial_feat == True:
spatial_features = bin_spatial(feature_image, size=spatial_size)
file_features.append(spatial_features)
if hist_feat == True:
hist_features = color_hist(feature_image, nbins=hist_bins)
file_features.append(hist_features)
if hog_feat == True:
if hog_channel == 'ALL':
hog_features = []
for channel in range(feature_image.shape[2]):
hog_features.append(get_hog_features(feature_image[:, :, channel],
orient, pix_per_cell, cell_per_block,
vis=False, feature_vec=True))
hog_features = np.ravel(hog_features)
else:
hog_features = get_hog_features(feature_image[:, :, hog_channel], orient,
pix_per_cell, cell_per_block, vis=False, feature_vec=True)
# Append the new feature vector to the list of features
file_features.append(hog_features)
features.append(np.concatenate(file_features))
# Return list of feature vectors
return features<jupyter_output><empty_output><jupyter_text>## 2. Search frames and find boxes**The following functions were built to evaluate and test the performance on single images, later on the functions are implemented in a class object with enhanced performance**### 2.1 sliding windows function<jupyter_code>def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None],
xy_window=(64, 64), xy_overlap=(0.5, 0.5)):
# If x and/or y start/stop positions not defined, set to image size
if x_start_stop[0] == None:
x_start_stop[0] = 0
if x_start_stop[1] == None:
x_start_stop[1] = img.shape[1]
if y_start_stop[0] == None:
y_start_stop[0] = 0
if y_start_stop[1] == None:
y_start_stop[1] = img.shape[0]
# Region to be searched
xspan = x_start_stop[1] - x_start_stop[0]
yspan = y_start_stop[1] - y_start_stop[0]
# Number of pixels per step in x/y
nx_pix_per_step = np.int(xy_window[0] * (1 - xy_overlap[0]))
ny_pix_per_step = np.int(xy_window[1] * (1 - xy_overlap[1]))
# Number of windows in x/y
nx_buffer = np.int(xy_window[0] * (xy_overlap[0]))
ny_buffer = np.int(xy_window[1] * (xy_overlap[1]))
nx_windows = np.int((xspan - nx_buffer) / nx_pix_per_step)
ny_windows = np.int((yspan - ny_buffer) / ny_pix_per_step)
# Initialize a list to append window parameters to
window_list = []
for ys in range(ny_windows):
for xs in range(nx_windows):
# Calculate window position
startx = xs * nx_pix_per_step + x_start_stop[0]
endx = startx + xy_window[0]
starty = ys * ny_pix_per_step + y_start_stop[0]
endy = starty + xy_window[1]
# Append window position to list
window_list.append(((startx, starty), (endx, endy)))
# Return the list of windows
return window_list<jupyter_output><empty_output><jupyter_text>### 2.2 draw boxes function<jupyter_code>def draw_boxes(img, bboxes, color=(0, 0, 255), thick=6):
# Copy the image
imcopy = np.copy(img)
# Iterate through the boxes
for bbox in bboxes:
# Draw a rectangle given bbox coordinates
cv2.rectangle(imcopy, bbox[0], bbox[1], color, thick)
# Return the image copy with boxes drawn
return imcopy<jupyter_output><empty_output><jupyter_text>### 2.3 single image features extraction<jupyter_code>def single_img_features(img, color_space='RGB', spatial_size=(32, 32),
hist_bins=32, orient=9,
pix_per_cell=8, cell_per_block=2, hog_channel=0,
spatial_feat=True, hist_feat=True, hog_feat=True):
# Empty list
img_features = []
# Apply color conversion
if color_space != 'RGB':
if color_space == 'HSV':
feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
elif color_space == 'LUV':
feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2LUV)
elif color_space == 'HLS':
feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
elif color_space == 'YUV':
feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YUV)
elif color_space == 'YCrCb':
feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)
else: feature_image = np.copy(img)
# Compute spatial features
if spatial_feat == True:
spatial_features = bin_spatial(feature_image, size=spatial_size)
# Append features to list
img_features.append(spatial_features)
# Compute histogram features
if hist_feat == True:
hist_features = color_hist(feature_image, nbins=hist_bins)
# Append features to list
img_features.append(hist_features)
# Compute HOG features
if hog_feat == True:
if hog_channel == 'ALL':
hog_features = []
for channel in range(feature_image.shape[2]):
hog_features.extend(get_hog_features(feature_image[:,:,channel],
orient, pix_per_cell, cell_per_block,
vis=False, feature_vec=True))
else:
hog_features = get_hog_features(feature_image[:,:,hog_channel], orient,
pix_per_cell, cell_per_block, vis=False, feature_vec=True)
# Append features to list
img_features.append(hog_features)
# Return concatenated array of features
return np.concatenate(img_features)<jupyter_output><empty_output><jupyter_text>### Search windows function<jupyter_code>
def search_windows(img, windows, clf, scaler, color_space='RGB',
spatial_size=(32, 32), hist_bins=32,
hist_range=(0, 256), orient=9,
pix_per_cell=8, cell_per_block=2,
hog_channel=0):
# Create an empty list for the found windows
on_windows = []
# Iterate over all windows in the windows list
for window in windows:
# Extract the test window from original image
test_img = cv2.resize(img[window[0][1]:window[1][1], window[0][0]:window[1][0]], (64, 64))
# Extract features for that window using single_img_features()
features = single_img_features(test_img, color_space=color_space,
spatial_size=spatial_size, hist_bins=hist_bins,
orient=orient, pix_per_cell=pix_per_cell,
cell_per_block=cell_per_block,
hog_channel=hog_channel, spatial_feat=spatial_feat,
hist_feat=hist_feat, hog_feat=hog_feat)
test_features = scaler.transform(np.array(features).reshape(1, -1))
# Predict using your classifier
prediction = clf.predict(test_features)
#If positive (prediction == 1) then save the window
if prediction == 1:
on_windows.append(window)
# Return windows for positive detections
return on_windows
# RGB, HSV, LUV, HLS, YUV, YCrCb
color_space = 'YCrCb'
# HOG orientations
orient = 9
# Pix per cell
pix_per_cell = 8
# Cells per block
cell_per_block = 2
# Hog channel (1,2,3 or ALL)
hog_channel = "ALL"
# Dimension for spatial binning
spatial_size = (32, 32)
# Number of histogram bins
hist_bins = 32
spatial_feat = True
hist_feat = True
hog_feat = True
y_start_stop = [350, None]
hist_range = (0, 256)<jupyter_output><empty_output><jupyter_text>## 3. Training the classifier<jupyter_code># Get the features of cars and noncars
car_features = extract_features(vehs, color_space, spatial_size, hist_bins, orient, pix_per_cell,
cell_per_block, hog_channel)
noncar_features = extract_features(non_vehs, color_space, spatial_size, hist_bins, orient, pix_per_cell,
cell_per_block, hog_channel)
# Check length of extracted image paths
print(len(car_features))
print(len(noncar_features))
print(np.shape(car_features))
print(np.shape(noncar_features))
y = np.hstack((np.ones(len(car_features)), np.zeros(len(noncar_features))))
print(y.shape)
X = np.vstack((car_features, noncar_features)).astype(np.float64)
print(X.shape)<jupyter_output>(17760, 8460)
<jupyter_text>#### Data normalization and classifier training<jupyter_code># Normalize training data
from sklearn.preprocessing import StandardScaler
X_Scaler = StandardScaler().fit(X)
X_scaled = X_Scaler.transform(X)
from sklearn.model_selection import train_test_split
rand_state = np.random.randint(0, 100)
# Split data in train/test data and shuffle it
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size = 0.2, random_state = rand_state)
from sklearn.svm import LinearSVC
# Train support vector machine
svc = LinearSVC()
svc.fit(X_train, y_train)<jupyter_output><empty_output><jupyter_text>### Get the accuarcy of the classifier<jupyter_code># Check the test accuarcy of the linear support vector machine
svc.score(X_test, y_test)<jupyter_output><empty_output><jupyter_text>## 4. Implementation of sliding windows search (exemplary)<jupyter_code>image = mpimg.imread('test_images/test6.jpg')
draw_image = np.copy(image)
# Scale the image since its a .jpg
image = image.astype(np.float32)/255
# Search with three different window sizes
windows = slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,
xy_window=(100, 100), xy_overlap=(0.5, 0.5))
windows2 = slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,
xy_window=(200, 200), xy_overlap=(0.3, 0.3))
windows3 = slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,
xy_window=(64, 64), xy_overlap=(0.3, 0.3))
# Get the found windows that match the features as list
hot_windows = search_windows(image, windows, svc, X_Scaler, color_space=color_space,
spatial_size=spatial_size, hist_bins=hist_bins,
orient=orient, pix_per_cell=pix_per_cell,
cell_per_block=cell_per_block,
hog_channel=hog_channel)
hot_windows2 = search_windows(image, windows2, svc, X_Scaler, color_space=color_space,
spatial_size=spatial_size, hist_bins=hist_bins,
orient=orient, pix_per_cell=pix_per_cell,
cell_per_block=cell_per_block,
hog_channel=hog_channel)
hot_windows3 = search_windows(image, windows3, svc, X_Scaler, color_space=color_space,
spatial_size=spatial_size, hist_bins=hist_bins,
orient=orient, pix_per_cell=pix_per_cell,
cell_per_block=cell_per_block,
hog_channel=hog_channel)
# Draw the found windows that match the features in boxes
window_img = draw_boxes(draw_image, hot_windows, color=(0, 0, 255), thick=6)
window_img2 = draw_boxes(window_img, hot_windows2, color=(0, 0, 255), thick=6)
window_img3 = draw_boxes(window_img2, hot_windows2, color=(0, 0, 255), thick=6)
plt.imshow(window_img3)
# helper function for color conversion
def convert_color(img, conv='RGB2YCrCb'):
if conv == 'RGB2YCrCb':
return cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)
if conv == 'BGR2YCrCb':
return cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
if conv == 'RGB2LUV':
return cv2.cvtColor(img, cv2.COLOR_RGB2LUV)
<jupyter_output><empty_output><jupyter_text>### 4.1 find cars function<jupyter_code># find cars function as shown in the lession
# function uses a scale-factor to search with different window sizes
# function as well replaces the overlapping with cells_per_steps
def find_cars(img, ystart, ystop, scale, svc, X_scaler, orient, pix_per_cell, cell_per_block,
spatial_size, hist_bins):
draw_img = np.copy(img)
img = img.astype(np.float32)/255
img_tosearch = img[ystart:ystop,:,:]
ctrans_tosearch = convert_color(img_tosearch, conv='RGB2YCrCb')
boxes = []
if scale != 1:
imshape = ctrans_tosearch.shape
ctrans_tosearch = cv2.resize(ctrans_tosearch,(np.int(imshape[1]/scale),(np.int(imshape[0]/scale))))
ch1 = ctrans_tosearch[:,:,0]
ch2 = ctrans_tosearch[:,:,1]
ch3 = ctrans_tosearch[:,:,2]
#Blocks and steps
nxblocks = (ch1.shape[1] // pix_per_cell) - cell_per_block + 1
nyblocks = (ch1.shape[0] // pix_per_cell) - cell_per_block + 1
nfeat_per_block = orient * cell_per_block**2
window = 64
nblocks_per_window = (window // pix_per_cell) - cell_per_block + 1
# Replacing overlapping with cells_per_step
cells_per_step = 2
nxsteps = (nxblocks - nblocks_per_window) // cells_per_step
nysteps = (nyblocks - nblocks_per_window) // cells_per_step
#get hog features
hog1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=False)
hog2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=False)
hog3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=False)
for xb in range(nxsteps):
for yb in range(nysteps):
ypos = yb * cells_per_step
xpos = xb * cells_per_step
# Extract hog features
hog_feat1 = hog1[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
hog_feat2 = hog2[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
hog_feat3 = hog3[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))
x_left = xpos * pix_per_cell
y_top = ypos * pix_per_cell
# Extract img patch
subimg = cv2.resize(ctrans_tosearch[y_top:y_top+window, x_left:x_left+window],(64,64))
spatial_features = bin_spatial(subimg, size=spatial_size)
hist_features = color_hist(subimg, nbins=hist_bins)
#test_features2 = np.concatenate((spatial_features, hist_features, hog_features))
#test_features = X_scaler.transform(np.array(test_features2)).reshape(1, -1)
test_features = X_scaler.transform(np.hstack((spatial_features, hist_features,
hog_features)).reshape(1, -1))
test_prediction = svc.predict(test_features)
if test_prediction == 1:
xbox_left = np.int(x_left * scale)
ytop_draw = np.int(y_top * scale)
win_draw = np.int(window*scale)
cv2.rectangle(draw_img,(xbox_left, ytop_draw+ystart),(xbox_left+win_draw, ytop_draw+
win_draw+ystart),(0,0,255),6)
boxes.append(((xbox_left, ytop_draw+ystart),(xbox_left+win_draw, ytop_draw+
win_draw+ystart)))
return draw_img, boxes
ystart = 400
ystop = 656
scale = 1.5
img_test = mpimg.imread('test_images/test1.jpg')
out_img, boxes = find_cars(img_test, ystart, ystop, scale, svc, X_Scaler, orient, pix_per_cell, cell_per_block, spatial_size, hist_bins)
plt.imshow(out_img)
print(boxes)<jupyter_output>[((48, 424), (144, 520)), ((792, 400), (888, 496)), ((816, 400), (912, 496)), ((840, 400), (936, 496)), ((864, 400), (960, 496)), ((1056, 400), (1152, 496)), ((1128, 400), (1224, 496)), ((1128, 424), (1224, 520)), ((1152, 400), (1248, 496)), ((1152, 424), (1248, 520))]
<jupyter_text>### 4.2 Add heatmap to cut out false-positives<jupyter_code># Heatmap functions / False positives
threshold = 1
heat = np.zeros_like(img_test[:,:,0]).astype(np.float)
def add_heat(heatmap, bbox_list):
for box in bbox_list:
heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1
return heatmap
def apply_threshold(heatmap, threshold):
heatmap[heatmap <= threshold] = 0
return heatmap
def draw_labeled_boxes(img, labels):
for car_number in range(1, labels[1]+1):
nonzero = (labels[0] == car_number).nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))
#print(bbox[0], bbox[1])
#cv2.rectangle(img, bbox[0], bbox[1], (0,0,255), 6)
img = draw_boxes(img, [bbox], color=(0, 0, 255), thick=6)
return img
heat = add_heat(heat, boxes)
heat= apply_threshold(heat, threshold)
heatmap = np.clip(heat, 0, 255)
from scipy.ndimage.measurements import label
labels = label(heatmap)
print(labels[1], 'vehicles found')
plt.imshow(labels[0], cmap='hot')
draw_img2 = draw_labeled_boxes(np.copy(img_test), labels)
plt.imshow(draw_img2)
# pulling everything together
threshold = 1
def vehicle_detection(image, ystart, ystop, scale, svc, X_Scaler, orient,pix_per_cell, cell_per_block, spatial_size,
hist_bins, threshold):
#find cars in image
out_img, boxes = find_cars(image, ystart, ystop, scale, svc, X_Scaler, orient,
pix_per_cell, cell_per_block, spatial_size, hist_bins)
heat = np.zeros_like(img_test[:,:,0]).astype(np.float)
box_list = boxes
heat = add_heat(heat, box_list)
heat= apply_threshold(heat, threshold)
heatmap = np.clip(heat, 0, 255)
labels = label(heatmap)
draw_img = draw_labeled_boxes(np.copy(image), labels)
return draw_img
draw_img = vehicle_detection(np.copy(img_test), ystart, ystop, scale, svc, X_Scaler, orient,pix_per_cell, cell_per_block, spatial_size,
hist_bins, threshold)
plt.imshow(draw_img)
from moviepy.editor import VideoFileClip
from IPython.display import HTML
def process_image(image):
#image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
processed_img = vehicle_detection(image, ystart, ystop, scale, svc, X_Scaler, orient,pix_per_cell, cell_per_block, spatial_size,
hist_bins, threshold)
return processed_img
#smooth the pipeline outcome
def find_cars_multiscale(img, ystart_ystop_scale, svc, X_scaler, orient, pix_per_cell, cell_per_block,
spatial_size, hist_bins):
draw_img = np.copy(img)
img = img.astype(np.float32)/255
for (ystart, ystop, scale) in ystart_ystop_scale:
img_tosearch = img[ystart:ystop,:,:]
ctrans_tosearch = convert_color(img_tosearch, conv='RGB2YCrCb')
boxes = []
if scale != 1:
imshape = ctrans_tosearch.shape
ctrans_tosearch = cv2.resize(ctrans_tosearch,(np.int(imshape[1]/scale),(np.int(imshape[0]/scale))))
ch1 = ctrans_tosearch[:,:,0]
ch2 = ctrans_tosearch[:,:,1]
ch3 = ctrans_tosearch[:,:,2]
# Blocks and steps
nxblocks = (ch1.shape[1] // pix_per_cell) - cell_per_block + 1
nyblocks = (ch1.shape[0] // pix_per_cell) - cell_per_block + 1
nfeat_per_block = orient * cell_per_block**2
window = 64
nblocks_per_window = (window // pix_per_cell) - cell_per_block + 1
cells_per_step = 2
nxsteps = (nxblocks - nblocks_per_window) // cells_per_step
nysteps = (nyblocks - nblocks_per_window) // cells_per_step
# Extract hog features
hog1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=False)
hog2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=False)
hog3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=False)
for xb in range(nxsteps):
for yb in range(nysteps):
ypos = yb * cells_per_step
xpos = xb * cells_per_step
# Extract hog features
hog_feat1 = hog1[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
hog_feat2 = hog2[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
hog_feat3 = hog3[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))
x_left = xpos * pix_per_cell
y_top = ypos * pix_per_cell
#extract img patch
subimg = cv2.resize(ctrans_tosearch[y_top:y_top+window, x_left:x_left+window],(64,64))
spatial_features = bin_spatial(subimg, size=spatial_size)
hist_features = color_hist(subimg, nbins=hist_bins)
#test_features2 = np.concatenate((spatial_features, hist_features, hog_features))
#test_features = X_scaler.transform(np.array(test_features2)).reshape(1, -1)
test_features = X_scaler.transform(np.hstack((spatial_features, hist_features,
hog_features)).reshape(1, -1))
test_prediction = svc.predict(test_features)
if test_prediction == 1:
xbox_left = np.int(x_left * scale)
ytop_draw = np.int(y_top * scale)
win_draw = np.int(window*scale)
cv2.rectangle(draw_img,(xbox_left, ytop_draw+ystart),(xbox_left+win_draw, ytop_draw+
win_draw+ystart),(0,0,255),6)
boxes.append(((xbox_left, ytop_draw+ystart),(xbox_left+win_draw, ytop_draw+
win_draw+ystart)))
return draw_img, boxes
from collections import deque
heatmaps = deque(maxlen=3)
threshold = 2
ystart_ystop_scale = [(400, 560, 1.5), (450, 650, 1.8), (500, 700, 2.5)]
def vehicle_detection_smooth(image, ystart_ystop_scale, svc, X_Scaler, orient,pix_per_cell,
cell_per_block, spatial_size, hist_bins, threshold):
# find cars in image
out_img, boxes = find_cars_multiscale(image, ystart_ystop_scale, svc, X_Scaler, orient,
pix_per_cell, cell_per_block, spatial_size, hist_bins)
heat = np.zeros_like(img_test[:,:,0]).astype(np.float)
box_list = boxes
current_heatmap = add_heat(image, box_list)
heatmaps.append(current_heatmap)
heatmap_sum = sum(heatmaps)
heat = apply_threshold(heatmap_sum, threshold)
heatmap = np.clip(heat, 0, 255)
labels = label(heatmap)
draw_img = draw_labeled_boxes(np.copy(image), labels)
return draw_img
draw_img = vehicle_detection_smooth(np.copy(img_test), ystart_ystop_scale, svc, X_Scaler, orient,pix_per_cell, cell_per_block, spatial_size,
hist_bins, threshold)
plt.imshow(draw_img)<jupyter_output><empty_output><jupyter_text>## 5. VehicleDetector Class Object**This class object combines the prework described above in one class object**<jupyter_code># To make thing easier the following class object, comprising the relevant functions to detect vehicles, is created.
class VehicleDetector:
def __init__(self):
# Init the class using the parameters as for the single functions before
self.color_space = 'YCrCb'
self.orient = 9
self.pix_per_cell = 8
self.cell_per_block = 2
self.hog_channel = "ALL"
self.spatial_size = (32, 32)
self.hist_bins = 32
self.spatial_feat = True
self.hist_feat = True
self.hog_feat = True
# Current heatmap
self.heatmap = None
# Heatmaps of last 3 frames
self.heat_images = deque(maxlen=3)
self.frame_count = 0
self.full_frame_processing_interval = 10
# Xstart
self.xstart = 600
# Various Scales
self.ystart_ystop_scale = None
# Kernal For Dilation
self.kernel = np.ones((50, 50))
# Threshold for Heatmap
self.threshold = None
self.X_scaler = X_Scaler
self.svc = svc
def find_cars_smooth(self, img):
X_scaler = self.X_scaler
orient = self.orient
pix_per_cell = self.pix_per_cell
cell_per_block = self.cell_per_block
spatial_size = self.spatial_size
hist_bins = self.hist_bins
svc = self.svc
box_list = []
draw_img = np.copy(img)
img = img.astype(np.float32) / 255
if self.frame_count % self.full_frame_processing_interval == 0:
mask = np.ones_like(img[:, :, 0])
else:
mask = np.sum(np.array(self.heat_images), axis=0)
mask[(mask > 0)] = 1
mask = cv2.dilate(mask, self.kernel, iterations=1)
self.frame_count += 1
for (ystart, ystop, scale) in self.ystart_ystop_scale:
nonzero = mask.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
if len(nonzeroy) != 0:
ystart = max(np.min(nonzeroy), ystart)
ystop = min(np.max(nonzeroy), ystop)
if len(nonzeroy) != 0:
xstart = max(np.min(nonzerox), self.xstart)
xstop = np.max(nonzerox)
else:
continue
if xstop <= xstart or ystop <= ystart:
continue
img_tosearch = img[ystart:ystop, xstart:xstop, :]
ctrans_tosearch = convert_color(img_tosearch, conv='RGB2YCrCb')
if scale != 1:
imshape = ctrans_tosearch.shape
ys = np.int(imshape[1] / scale)
xs = np.int(imshape[0] / scale)
if (ys < 1 or xs < 1):
continue
ctrans_tosearch = cv2.resize(ctrans_tosearch, (np.int(imshape[1] / scale), np.int(imshape[0] / scale)))
if ctrans_tosearch.shape[0] < 64 or ctrans_tosearch.shape[1] < 64:
continue
ch1 = ctrans_tosearch[:, :, 0]
ch2 = ctrans_tosearch[:, :, 1]
ch3 = ctrans_tosearch[:, :, 2]
nxblocks = (ch1.shape[1] // pix_per_cell) - 1
nyblocks = (ch1.shape[0] // pix_per_cell) - 1
nfeat_per_block = orient * cell_per_block ** 2
window = 64
nblocks_per_window = (window // pix_per_cell) - 1
cells_per_step = 2
nxsteps = (nxblocks - nblocks_per_window) // cells_per_step
nysteps = (nyblocks - nblocks_per_window) // cells_per_step
# Compute individual channel HOG features for the entire image
hog1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, feature_vec=False)
hog2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, feature_vec=False)
hog3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, feature_vec=False)
for xb in range(nxsteps + 1):
for yb in range(nysteps + 1):
ypos = yb * cells_per_step
xpos = xb * cells_per_step
# Extract HOG for this patch
hog_feat1 = hog1[ypos:ypos + nblocks_per_window, xpos:xpos + nblocks_per_window].ravel()
hog_feat2 = hog2[ypos:ypos + nblocks_per_window, xpos:xpos + nblocks_per_window].ravel()
hog_feat3 = hog3[ypos:ypos + nblocks_per_window, xpos:xpos + nblocks_per_window].ravel()
hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))
xleft = xpos * pix_per_cell
ytop = ypos * pix_per_cell
# Extract the image patch
subimg = ctrans_tosearch[ytop:ytop + window, xleft:xleft + window]
# Get color features
spatial_features = bin_spatial(subimg, size=spatial_size)
hist_features = color_hist(subimg, nbins=hist_bins)
# Scale features and make a prediction
test_features = X_scaler.transform(
np.hstack((spatial_features, hist_features, hog_features)).reshape(1, -1))
# test_features = X_scaler.transform(np.hstack((shape_feat, hist_feat)).reshape(1, -1))
test_prediction = svc.predict(test_features)
if test_prediction == 1:
xbox_left = xstart + np.int(xleft * scale)
ytop_draw = np.int(ytop * scale)
win_draw = np.int(window * scale)
box_list.append(
((xbox_left, ytop_draw + ystart), (xbox_left + win_draw, ytop_draw + win_draw + ystart)))
# Add heat to each box in box list
self.add_heatmap_and_threshold(draw_img, box_list, self.threshold)
# Find final boxes from heatmap using label function
labels = label(self.heatmap)
VehicleDetector.draw_labeled_bboxes_smooth(draw_img, labels)
return draw_img
def add_heatmap_and_threshold(self, draw_img, bbox_list, threshold):
heatmap = np.zeros_like(draw_img[:, :, 0]).astype(np.float)
for box in bbox_list:
# Add += 1 for all pixels inside each bbox
heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1
self.heat_images.append(heatmap)
self.heatmap = np.sum(np.array(self.heat_images), axis=0)
self.heatmap[self.heatmap <= threshold] = 0
@staticmethod
def draw_labeled_bboxes_smooth(img, labels):
# Iterate through all detected cars
for car_number in range(1, labels[1] + 1):
# Find pixels with each car_number label value
nonzero = (labels[0] == car_number).nonzero()
# Identify x and y values
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Box based on min/max x and y
bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))
# Draw the box on the image
cv2.rectangle(img, bbox[0], bbox[1], (0, 0, 255), 6)<jupyter_output><empty_output><jupyter_text>## 6. Combining it with my last project submission<jupyter_code>import pickle
with open('objs.pkl', 'rb') as f:
mtx, dist = pickle.load(f)
def undistort_img(img, mtx, dist):
img_undist = cv2.undistort(img, mtx, dist, None, mtx)
return img_undist
def grayscale(img):
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img_gray
def SobelOp(img, kernelSize, thresh_min, thresh_max):
sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize = kernelSize)
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize = kernelSize)
abs_sobelx = np.absolute(sobelx)
scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[(scaled_sobel > thresh_min) & (scaled_sobel <= thresh_max)] = 1
return scaled_sobel, sxbinary
def HLSconv(img, s_thresh_min, s_thresh_max):
# convert to hls
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
s_chan = hls[:,:,2]
s_binary = np.zeros_like(s_chan)
s_binary[(s_chan > s_thresh_min) & (s_chan <= s_thresh_max)] = 1
return s_binary
def StackFilters(sxbinary, s_binary):
color_binary = np.dstack((np.zeros_like(sxbinary), sxbinary, s_binary))*255
comb_binary = np.zeros_like(sxbinary)
comb_binary[(s_binary == 1) | (sxbinary == 1)] = 1
return comb_binary
def IMGwarp(img):
src = np.float32([[740, 460], [1050, 680], [280, 680], [580, 460]])
dst = np.float32([[950, 0], [950, 720], [370, 720], [370, 0]])
img_size = (img.shape[1], img.shape[0])
M = cv2.getPerspectiveTransform(src, dst)
Minv = cv2.getPerspectiveTransform(dst, src)
img_warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)
return M, Minv, img_warped
def maskImage(img_w):
mask = np.zeros_like(img_w)
ignore_mask_color = 255
ignore_mask_color2 = 0
vertices = np.array([[(200, 720),(300, 200), (1100, 200), (1250,720)]], dtype=np.int32)
vertices2 = np.array([[(600, 720),(675, 450), (725, 450), (800,720)]], dtype=np.int32)
cv2.fillPoly(mask, vertices, ignore_mask_color)
cv2.fillPoly(mask, vertices2, ignore_mask_color2)
img_masked = cv2.bitwise_and(img_w, mask)
return img_masked
def FindLanes(img_warped):
histogram = np.sum(img_warped[img_warped.shape[0]//2:,:], axis=0)
out_img = np.dstack((img_warped, img_warped, img_warped))*255
midpoint = np.int(histogram.shape[0]/2)
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:])+midpoint
offset_shadow = 100
detected_left = False
detected_right = False
if (leftx_base > 300) & (leftx_base < 500):
detected_left = True
if (rightx_base > 800) & (rightx_base < 1000):
detected_right = True
if detected_left == False:
leftx_base = np.argmax(histogram[:midpoint-offset_shadow])
if detected_right == False:
rightx_base = np.argmax(histogram[midpoint+offset_shadow:])+midpoint
return midpoint, leftx_base, rightx_base, detected_left, out_img
def distanceMid(img2, right_fitx, left_fitx):
camera_position = img2.shape[1]/2
lane_center = (right_fitx[719] + left_fitx[719])/2
center_offset_pixels = abs(camera_position - lane_center)
center_offset = center_offset_pixels*xm_per_pix
return center_offset
def WindowSearch(img_warped, n_win, marg, minpix, leftx_base, rightx_base, out_img):
nwindows = n_win #9
window_height = np.int(img_warped.shape[0]/nwindows)
nonzero = img_warped.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
leftx_current = leftx_base
rightx_current = rightx_base
margin = marg
minpix = minpix
left_lane_inds = []
right_lane_inds = []
for window in range(nwindows):
win_y_low = img_warped.shape[0] - (window + 1) * window_height
win_y_high = img_warped.shape[0] - window * window_height
win_x_left_low = leftx_current - margin
win_x_left_high = leftx_current + margin
win_x_right_low = rightx_current - margin
win_x_right_high = rightx_current + margin
cv2.rectangle(out_img, (win_x_left_low, win_y_low),(win_x_left_high, win_y_high), (0, 255, 0), 2)
cv2.rectangle(out_img, (win_x_right_low, win_y_low),(win_x_right_high, win_y_high), (0, 255, 0), 2)
good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_x_left_low) &
(nonzerox < win_x_left_high)).nonzero()[0]
good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_x_right_low) &
(nonzerox < win_x_right_high)).nonzero()[0]
left_lane_inds.append(good_left_inds)
right_lane_inds.append(good_right_inds)
if (len(good_left_inds) > minpix) & (len(good_right_inds) > minpix):
leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
rightx_current = np.int(np.mean(nonzerox[good_right_inds]))
# concatenate found lane indices
left_lane_inds = np.concatenate(left_lane_inds)
right_lane_inds = np.concatenate(right_lane_inds)
# extract the pixel positions
left_x = nonzerox[left_lane_inds]
left_y = nonzeroy[left_lane_inds]
right_x = nonzerox[right_lane_inds]
right_y = nonzeroy[right_lane_inds]
# fit second order polynomial
left_fit = np.polyfit(left_y, left_x, 2)
right_fit = np.polyfit(right_y, right_x, 2)
# Visualize sliding windows
ploty = np.linspace(0, img_warped.shape[0]-1, img_warped.shape[0])
left_fitx = left_fit[0]*ploty**2 + left_fit[1] * ploty + left_fit[2]
right_fitx = right_fit[0]*ploty**2 + right_fit[1] * ploty + right_fit[2]
return left_lane_inds, right_lane_inds, left_fitx, right_fitx, ploty, left_x, left_y, right_x, right_y
def curvature(left_x, left_y, right_x, right_y, ploty):
lane_length = 30
lane_width = 3.7
y_eval = np.max(ploty)
ym_per_pix = lane_length/720
xm_per_pix = lane_width/580
left_fit_cr = np.polyfit(left_y * ym_per_pix, left_x * xm_per_pix, 2)
right_fit_cr = np.polyfit(right_y * ym_per_pix, right_x * xm_per_pix, 2)
left_curverad_cr = ((1 + (2 * left_fit_cr[0] * y_eval*ym_per_pix + left_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * left_fit_cr[0])
right_curverad_cr = ((1 + (2 * right_fit_cr[0] * y_eval*ym_per_pix + right_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * right_fit_cr[0])
return left_curverad_cr, right_curverad_cr
def lanePosition():
left_pos = (midpoint - leftx_base) * xm_per_pix
right_pos = (rightx_base - midpoint) * xm_per_pix
line_base_pos = np.min([left_pos, right_pos])
return left_pos, right_pos, line_base_pos
def warpBack(img_warped, left_fitx, right_fitx, ploty, Minv, image_undist):
warp_zero = np.zeros_like(img_warped).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
# Recast the points
pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane
cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))
# Warp back to original image
newwarp = cv2.warpPerspective(color_warp, Minv, (image_undist.shape[1], image_undist.shape[0]))
result = cv2.addWeighted(image_undist, 1, newwarp, 0.3, 0)
return result
def select_yellow(image_in):
image_in2 = cv2.cvtColor(image_in, cv2.COLOR_BGR2RGB)
hsv = cv2.cvtColor(image_in2, cv2.COLOR_RGB2HSV)
lower = np.array([20,60,60])
upper = np.array([38,174, 250])
mask = cv2.inRange(hsv, lower, upper)
return mask
def select_white(image_in):
lower = np.array([202,202,202])
upper = np.array([255,255,255])
mask = cv2.inRange(image_in, lower, upper)
return mask
def comb_thresh(image_in):
yellow = select_yellow(image_in)
white = select_white(image_in)
combined_binary = np.zeros_like(yellow)
combined_binary[(yellow >= 1) | (white >= 1)] = 1
return combined_binary
def pipeline3(image, mtx, dist, kernelSize):
out1 = undistort_img(image, mtx, dist)
out2 = comb_thresh(out1)
M, Minv, out3 = IMGwarp(out2)
mid, leftxbase, rightxbase, detected, out_img = FindLanes(out3)
left_inds, right_inds, leftfit, rightfit, plotyy, leftx, lefty, rightx, righty = WindowSearch(out3,
9, 100, 10,
leftxbase, rightxbase,
out_img)
left_curverad_cr, right_curverad_cr = curvature(leftx, lefty, rightx, righty, plotyy)
left_fitx = leftfit
right_fitx = rightfit
global l_fit_buffer
global r_fit_buffer
global old_img_lines
if old_img_lines is None:
old_img_lines = out2
# Compare new frame to previous frame
ret = cv2.matchShapes(old_img_lines, out2, 1, 0.0)
if ret < 50:
old_img_lines = out2
if l_fit_buffer is None:
l_fit_buffer = np.array([left_fitx])
if r_fit_buffer is None:
r_fit_buffer = np.array([right_fitx])
l_fit_buffer = np.append(l_fit_buffer, [left_fitx], axis=0)[-filter_size:]
r_fit_buffer = np.append(r_fit_buffer, [right_fitx], axis=0)[-filter_size:]
# Compute the mean
l_fit_mean = np.mean(l_fit_buffer, axis=0)
r_fit_mean = np.mean(r_fit_buffer, axis=0)
result2 = warpBack(out3, leftfit, rightfit, plotyy, Minv, out1)
return result2
vehicleDetector = VehicleDetector()
vehicleDetector.ystart_ystop_scale = [(380, 480, 1), (400, 600, 1.5), (500, 700, 2.5)]
vehicleDetector.threshold = 2
image3 = mpimg.imread('test_images/test1.jpg')
output3 = vehicleDetector.find_cars_smooth(image3)
plt.figure()
plt.imshow(output3)
plt.title('Car Positions')
filter_size = 10
old_img_lines = None
l_fit_buffer = None
r_fit_buffer = None
def process_image_lanes(image):
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
processed_img = pipeline3(image, mtx, dist, 5)
return processed_img
#combine both
vehicleDetector = VehicleDetector()
vehicleDetector.ystart_ystop_scale = [(380, 480, 1), (400, 600, 1.5), (500, 700, 2.5)]
vehicleDetector.threshold = 2
filter_size = 10
old_img_lines = None
l_fit_buffer = None
r_fit_buffer = None
def process_image_comb(image):
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
processed_img = pipeline3(image, mtx, dist, 5)
processed_img = cv2.cvtColor(processed_img, cv2.COLOR_RGB2BGR)
processed_img2 = vehicleDetector.find_cars_smooth(processed_img)
return processed_img2
project_video_output = './output_videos/project_video_output_comb.mp4'
clip9000 = VideoFileClip("./project_video.mp4")
white_clip9000 = clip9000.fl_image(process_image_comb)
%time white_clip9000.write_videofile(project_video_output, audio=False)<jupyter_output>[MoviePy] >>>> Building video ./output_videos/project_video_output_comb.mp4
[MoviePy] Writing video ./output_videos/project_video_output_comb.mp4
|
no_license
|
/CarND-Vehicle-Detection-master-P5.ipynb
|
azumf/CarND-Vehicle-Detection-P5
| 16 |
<jupyter_start><jupyter_text># 교차검증 그리드 서치 (cross_val_score) p324~<jupyter_code>from sklearn.model_selection import cross_val_score
import numpy as np
best_score = 0
for gamma in [0.001, 0.01, 0.1, 1, 10, 100]:
for C in [0.001, 0.01, 0.1, 1, 10, 100]:
# 매개변수의 각 조합에 대해 SVC를 훈련시킵니다
svm = SVC(gamma=gamma, C=C)
scores = cross_val_score(svm, X_trainval, y_trainval, cv=5)
# print(scores)
score=np.mean(scores)
if score > best_score: # 점수가 더 높으면 매개변수와 함께 기록합니다
best_score = score
best_parameters = {'C': C, 'gamma': gamma}
# 훈련 세트와 검증 세트를 합쳐 모델을 다시 만든 후 테스트 세트를 사용해 평가
svm = SVC(**best_parameters) # **best_parameters : SVC(C=C, gamma=gamma) -> SVC(C=10, gamma=0.001)
svm.fit(X_trainval, y_trainval)
test_score = svm.score(X_test, y_test)
print("검증 세트에서 최고 점수: {:.2f}".format(best_score))
print("최적 파라미터: ", best_parameters)
print("최적 파라미터에서 테스트 세트 점수: {:.2f}".format(test_score))
from sklearn.model_selection import GridSearchCV
param_grid = {'C':[0.001, 0.01, 0.1, 1, 10, 100],'gamma':[0.001, 0.01, 0.1, 1, 10, 100]}
# 반복문 돌려 최적값 찾기
gsc = GridSearchCV(SVC(), param_grid, cv=5, return_train_score=True)
gsc.fit(X_trainval, y_trainval) #(6개 * 6개 * 5번 반복)
print(gsc.best_score_)
print(gsc.best_params_)
print(gsc.score(X_test, y_test))
import pandas as pd
results = pd.DataFrame(gsc.cv_results_)
# results.head()
results.iloc[:, 4:].head()
import mglearn
# results['mean_test_score'] # 36개 값,
scores = results['mean_test_score'].values.reshape(6,6)
# print(scores)
mglearn.tools.heatmap(scores, xlabel='gamma', ylabel='C',
yticklabels=param_grid['C'],
xticklabels=['gamma'])
param_grid = [{'kernel': ['rbf'], 'C': [0.001, 0.01, 0.1, 1, 10, 100],
'gamma': [0.001, 0.01, 0.1, 1, 10, 100]},
{'kernel': ['linear'],
'C': [0.001, 0.01, 0.1, 1, 10, 100]}]
grid_search = GridSearchCV(SVC(), param_grid, cv=5,
return_train_score=True)
grid_search.fit(X_train, y_train)
print("최적 파라미터: {}".format(grid_search.best_params_))
print("최고 교차 검증 점수: {:.2f}".format(grid_search.best_score_))
# grid_search.cv_results_
pd.DataFrame(grid_search.cv_results_).iloc[:, 4:].T.head()
param_grid = {'C':[0.001, 0.01, 0.1, 1, 10, 100],'gamma':[0.001, 0.01, 0.1, 1, 10, 100]}
gsc = GridSearchCV(SVC(), param_grid, cv=5, return_train_score=True)
scores = cross_val_score(gsc, iris.data, iris.target, cv=5)
print(scores, scores.mean())<jupyter_output>[0.96666667 1. 0.96666667 0.96666667 1. ] 0.9800000000000001
|
no_license
|
/머신러닝/l.evalueation(모델평가, 성능 향상).ipynb
|
chayoonjung/yun-python
| 1 |
<jupyter_start><jupyter_text>Create a array<jupyter_code>data = np.arange(10)
print (data.shape)
data
data = data.reshape(2,5)
print (data.shape)
data
data_1 = np.ones([3,3])
print (type(data_1))
print (data_1)
data_1 = np.zeros([3,3])
print (data_1)
data = np.eye(3,3)
data
data =np.diag((1,2,3))
data
data = np.empty([3,3])
data
data = np.random.rand(3,3)
print (data)
data = np.array([[1,2,3],[2,3,4],[3,4,5]])
data
data_list = list(range(9))
data = np.array(data_list).reshape(3,3)
data<jupyter_output><empty_output><jupyter_text>Matrix Operation<jupyter_code>a = np.arange(3)
print (a)
a.shape
b = a.T
print (b)
b.shape
a = a.reshape(1,3) # row first, column second
print (a)
a.shape
b = a.T
print (b)
b.shape
c = np.dot(b,a)
c
c = b @ a
c
c = c + np.ones([3,3])
c
c ** 2
d = c * c
d
a = np.random.rand(3,3)
a
all_max = a.max()
x_max = a.max(axis = 0) # axis means along which axis
y_max = a.max(axis = 1)
print (all_max,x_max,y_max)
all_max_arg = a.argmax()
x_max_arg = a.argmax(axis = 0)
print (all_max_arg, x_max_arg)
a = np.random.rand(12)
a
ind = a.argsort()
ind
a.sort()
a<jupyter_output><empty_output><jupyter_text>Indexing, Slicing and Iterating<jupyter_code>b= a[:,2]
b
for row in a:
print (row)
for element in a.flat:
print (element)
a = np.random.rand(4,4)
a
b = a.reshape(8,-1)
b<jupyter_output><empty_output><jupyter_text>Stacking together different arrays<jupyter_code>a = np.random.rand(2,2)
b = np.random.rand(2,2)
print (a,b)
np.vstack((a,b)) # vertical stack
np.hstack((a,b)) # horizontal stack<jupyter_output><empty_output><jupyter_text>Copies and Views<jupyter_code>a = np.arange(12)
# No copy at all, different names, but share same memory address
# shape of a and data are changable via b
b= a
# Shallow copy: shape of a doesn't change and data of a changes
c = a.view()
# Deep copy: a's shape and data don't change
d= a.copy()<jupyter_output><empty_output><jupyter_text>Indexing with Boolean Arrays<jupyter_code>a = np.random.rand(3,3)
a
a[[0,2],[1,2]]
a[a>0.5]<jupyter_output><empty_output><jupyter_text>Linear Algebra<jupyter_code>a = np.array([[1.0, 2.0], [3.0, 4.0]])
np.linalg.inv(a)
np.linalg.eig(a)
<jupyter_output><empty_output><jupyter_text>Questions<jupyter_code>data = np.eye(3,3)
data
np.nonzero(data)
np.any(data)<jupyter_output><empty_output>
|
permissive
|
/Numpy.ipynb
|
yuzhipeter/Data_Structure_Numpy_Pandas
| 8 |
<jupyter_start><jupyter_text># Read in the data<jupyter_code>import pandas as pd
import numpy
import re
data_files = [
"ap_2010.csv",
"class_size.csv",
"demographics.csv",
"graduation.csv",
"hs_directory.csv",
"sat_results.csv"
]
data = {}
for f in data_files:
d = pd.read_csv("schools/{0}".format(f))
data[f.replace(".csv", "")] = d<jupyter_output><empty_output><jupyter_text># Read in the surveys<jupyter_code>all_survey = pd.read_csv("schools/survey_all.txt", delimiter="\t", encoding='windows-1252')
d75_survey = pd.read_csv("schools/survey_d75.txt", delimiter="\t", encoding='windows-1252')
survey = pd.concat([all_survey, d75_survey], axis=0)
survey["DBN"] = survey["dbn"]
survey_fields = [
"DBN",
"rr_s",
"rr_t",
"rr_p",
"N_s",
"N_t",
"N_p",
"saf_p_11",
"com_p_11",
"eng_p_11",
"aca_p_11",
"saf_t_11",
"com_t_11",
"eng_t_11",
"aca_t_11",
"saf_s_11",
"com_s_11",
"eng_s_11",
"aca_s_11",
"saf_tot_11",
"com_tot_11",
"eng_tot_11",
"aca_tot_11",
]
survey = survey.loc[:,survey_fields]
data["survey"] = survey<jupyter_output><empty_output><jupyter_text># Add DBN columns<jupyter_code>data["hs_directory"]["DBN"] = data["hs_directory"]["dbn"]
def pad_csd(num):
string_representation = str(num)
if len(string_representation) > 1:
return string_representation
else:
return "0" + string_representation
data["class_size"]["padded_csd"] = data["class_size"]["CSD"].apply(pad_csd)
data["class_size"]["DBN"] = data["class_size"]["padded_csd"] + data["class_size"]["SCHOOL CODE"]<jupyter_output><empty_output><jupyter_text># Convert columns to numeric<jupyter_code>cols = ['SAT Math Avg. Score', 'SAT Critical Reading Avg. Score', 'SAT Writing Avg. Score']
for c in cols:
data["sat_results"][c] = pd.to_numeric(data["sat_results"][c], errors="coerce")
data['sat_results']['sat_score'] = data['sat_results'][cols[0]] + data['sat_results'][cols[1]] + data['sat_results'][cols[2]]
def find_lat(loc):
coords = re.findall("\(.+, .+\)", loc)
lat = coords[0].split(",")[0].replace("(", "")
return lat
def find_lon(loc):
coords = re.findall("\(.+, .+\)", loc)
lon = coords[0].split(",")[1].replace(")", "").strip()
return lon
data["hs_directory"]["lat"] = data["hs_directory"]["Location 1"].apply(find_lat)
data["hs_directory"]["lon"] = data["hs_directory"]["Location 1"].apply(find_lon)
data["hs_directory"]["lat"] = pd.to_numeric(data["hs_directory"]["lat"], errors="coerce")
data["hs_directory"]["lon"] = pd.to_numeric(data["hs_directory"]["lon"], errors="coerce")<jupyter_output><empty_output><jupyter_text># Condense datasets<jupyter_code>class_size = data["class_size"]
class_size = class_size[class_size["GRADE "] == "09-12"]
class_size = class_size[class_size["PROGRAM TYPE"] == "GEN ED"]
class_size = class_size.groupby("DBN").agg(numpy.mean)
class_size.reset_index(inplace=True)
data["class_size"] = class_size
data["demographics"] = data["demographics"][data["demographics"]["schoolyear"] == 20112012]
data["graduation"] = data["graduation"][data["graduation"]["Cohort"] == "2006"]
data["graduation"] = data["graduation"][data["graduation"]["Demographic"] == "Total Cohort"]<jupyter_output><empty_output><jupyter_text># Convert AP scores to numeric<jupyter_code>cols = ['AP Test Takers ', 'Total Exams Taken', 'Number of Exams with scores 3 4 or 5']
for col in cols:
data["ap_2010"][col] = pd.to_numeric(data["ap_2010"][col], errors="coerce")<jupyter_output><empty_output><jupyter_text># Combine the datasets<jupyter_code>combined = data["sat_results"]
combined = combined.merge(data["ap_2010"], on="DBN", how="left")
combined = combined.merge(data["graduation"], on="DBN", how="left")
to_merge = ["class_size", "demographics", "survey", "hs_directory"]
for m in to_merge:
combined = combined.merge(data[m], on="DBN", how="inner")
combined = combined.fillna(combined.mean())
combined = combined.fillna(0)<jupyter_output><empty_output><jupyter_text># Add a school district column for mapping<jupyter_code>def get_first_two_chars(dbn):
return dbn[0:2]
combined["school_dist"] = combined["DBN"].apply(get_first_two_chars)<jupyter_output><empty_output><jupyter_text># Find correlations<jupyter_code>correlations = combined.corr()
correlations = correlations["sat_score"]
print(correlations)<jupyter_output>SAT Critical Reading Avg. Score 0.986820
SAT Math Avg. Score 0.972643
SAT Writing Avg. Score 0.987771
sat_score 1.000000
AP Test Takers 0.523140
Total Exams Taken 0.514333
Number of Exams with scores 3 4 or 5 0.463245
Total Cohort 0.325144
CSD 0.042948
NUMBER OF STUDENTS / SEATS FILLED 0.394626
NUMBER OF SECTIONS 0.362673
AVERAGE CLASS SIZE 0.381014
SIZE OF SMALLEST CLASS 0.249949
SIZE OF LARGEST CLASS 0.314434
SCHOOLWIDE PUPIL-TEACHER RATIO NaN
schoolyear NaN
fl_percent NaN
frl_percent -0.722225
total_enrollment 0.367857
ell_num -0.153778
ell_percent [...]<jupyter_text># Plotting survey correlations<jupyter_code># Remove DBN since it's a unique identifier, not a useful numerical value for correlation.
survey_fields.remove("DBN")
%matplotlib inline
combined.corr()["sat_score"][survey_fields].plot.bar()
combined.plot.scatter(x="saf_s_11", y="sat_score")
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
districts = combined.groupby("school_dist").agg(numpy.mean)
districts.reset_index(inplace=True)
m = Basemap(
projection='merc',
llcrnrlat=40.496044,
urcrnrlat=40.915256,
llcrnrlon=-74.255735,
urcrnrlon=-73.700272,
resolution='i'
)
m.drawmapboundary(fill_color='#85A6D9')
m.drawcoastlines(color='#6D5F47', linewidth=.4)
m.drawrivers(color='#6D5F47', linewidth=.4)
longitudes = districts["lon"].tolist()
latitudes = districts["lat"].tolist()
m.scatter(longitudes, latitudes, s=50, zorder=2, latlon=True, c=districts["saf_s_11"], cmap="summer")
plt.show()
race_fields = ["white_per", "asian_per", "black_per", "hispanic_per"]
combined.corr()["sat_score"][race_fields].plot.bar()
combined.plot.scatter(x="hispanic_per", y="sat_score")
print(combined[combined["hispanic_per"] > 95]["SCHOOL NAME"])
low_hispanic = combined[combined["hispanic_per"] < 10]
print(low_hispanic[low_hispanic["sat_score"] > 1800]["SCHOOL NAME"])
print(combined[(combined["hispanic_per"] < 10) & (combined["sat_score"] > 1800)]["SCHOOL NAME"])
gender = ["male_per", "female_per"]
print(combined.corr()["sat_score"][gender].plot.bar())
print(combined.plot.scatter(x="female_per", y="sat_score"))
print(combined[(combined["female_per"] > 60) & (combined["sat_score"] > 170)]["SCHOOL NAME"])
combined["ap_per"] = combined["AP Test Takers "]/combined["total_enrollment"]
print(combined.plot.scatter(x="ap_per", y="sat_score"))<jupyter_output>Axes(0.125,0.125;0.775x0.775)
|
no_license
|
/Guided Project: Analyzing NYC High School Data/Schools.ipynb
|
isabellechiu/Self-Project-Dataquest
| 10 |
<jupyter_start><jupyter_text># Mô tả dữ liệu bằng Arviz
### Bs. Lê Ngọc Khả Nhi
Bài thực hành nảy nhằm hướng dẫn dùng package Arviz để thực hiện các biểu đồ mô tả đữ liệu đơn giản.
Arviz (https://arviz-devs.github.io/arviz/index.html) là một thư viện đồ họa chuyên dụng cho Thống kê Bayes, cho phép vẽ các biểu đồ để diễn giải posterior distribution từ các mô hình Bayes. Tuy nhiên, ta có thể lợi dụng các hàm của Arviz cho mục tiêu thống kê mô tả đơn giản, vì sẽ tiện lợi hơn nhiều so với vẽ thủ công bằng matplotlib.<jupyter_code>import arviz as az
import numpy as np
import pandas as pd
print('Arviz', az.__version__)<jupyter_output>Arviz 0.6.1
<jupyter_text>Trước khi dùng arviz, dữ liệu đầu vào cần được chuyển đổi thành cấu trúc "inference_data" bằng hàm convert_to_inference_data; hàm này chấp nhận những output từ mô hình Bayes (pymc3, pystan, pyro, ...); tuy nhiên nó cũng dung nạp 2 kiểu đữ liệu không phải là mô hình Bayes, gồm numpy array và dictionary## Từ 1D numpy array<jupyter_code>n = 1000
np_1D_dat = az.convert_to_inference_data(np.random.normal(2,2,size = n))
print(np_1D_dat)
np_1D_dat.posterior<jupyter_output>Inference data with groups:
> posterior
<jupyter_text>## Từ pandas Series<jupyter_code>pd_S = pd.Series(np.random.gamma(0.5, size = n))
pd_S_dat = az.convert_to_inference_data(pd_S.values)
print(pd_S_dat)
pd_S_dat.posterior<jupyter_output>Inference data with groups:
> posterior
<jupyter_text>## Từ nD numpy array (ma trận 2D, tensor, array đa chiều)<jupyter_code>k = (1,1000,3)
np_3D_dat = az.convert_to_inference_data(np.random.randn(*k))
print(np_3D_dat)
np_3D_dat.posterior<jupyter_output>Inference data with groups:
> posterior
<jupyter_text>## Từ Dictionary<jupyter_code>datadict = {
'X': np.random.normal(1,2,size = n),
'Y': np.random.normal(1,2,size = n)*2 + np.random.rand(1000),
'Z': np.random.normal(1,2,size = n)*(-2) + np.random.rand(1000),
}
data_dict = az.convert_to_inference_data(datadict)
data_dict.posterior<jupyter_output><empty_output><jupyter_text>## Từ pandas dataframe<jupyter_code>pd_df = pd.DataFrame(datadict)
pd_df.head()
data_df= az.convert_to_inference_data(pd_df.to_numpy())
data_df.posterior
data_df= az.convert_to_inference_data(pd_df.values)
data_df.posterior<jupyter_output><empty_output><jupyter_text>Có nhiều phong cách mỹ thuật khác nhau để chọn:<jupyter_code>az.style.available
az.style.use('arviz-whitegrid')<jupyter_output><empty_output><jupyter_text># Hàm plot_dist
Hàm này cho phép biểu diễn hàm mật độ phân phối (PDF, CDF), biểu đồ 1D KDE, 1D Histogram và 2D KDE
Ưu điểm : arviz tự động nhận ra biến liên tục và dùng KDE, biến rời rạc để dùng histogram. Nó cho phép kết hợp thêm Rugs layer, hỗ trợ hàm CDF lẫn PDF<jupyter_code>az.plot_dist(np_1D_dat.posterior.x,
rug = True,
color ="red",
fill_kwargs={'alpha': 0.3, 'color':'#eb3483'},)
az.plot_dist(np_1D_dat.posterior.x,
rug = True,
cumulative =True,
color ="red",
fill_kwargs={'alpha': 0.3, 'color':'#eb3483'},)
az.plot_dist(np.random.poisson(5, 1000),
color ="#eb3483",)
az.plot_dist(np.random.poisson(5, 1000),
color ="#eb3483",
fill_kwargs={'alpha': 0.3, 'color':'#eb3483'},
kind = 'kde')<jupyter_output><empty_output><jupyter_text>Hơn thế nữa, hàm plot_dist vẽ được 2D KDE rất đẹp:<jupyter_code>az.plot_dist(np_1D_dat.posterior.x,
np_1D_dat.posterior.x * 2 + np.random.normal(0,5,1000),
contour = True,
contour_kwargs={'colors': 'white','alpha':0.8,}
)
az.plot_dist(np_1D_dat.posterior.x,
np_1D_dat.posterior.x * 2 + np.random.normal(0,5,1000),
contour = False,
contour_kwargs={'colors': 'white','alpha':0.8,}
)<jupyter_output><empty_output><jupyter_text>## Hàm plot_posterior: Suy diễn thống kê
Hàm này dùng để suy diễn phân phối hậu nghiệm của các mô hình Bayes, tuy nhiên không gì ngăn cản chúng ta dùng nó cho dữ liệu 1D bất kì.
Hàm này dùng làm thống kê mô tả cực kì hiệu quả, vì nó cho phép kết hợp 1D KDE plot và các trị số thống kê median, mean, mode, khoảng tin cậy, và suy diễn thống kê dựa vào các method Bayes như HDP (tương tự như CI), Khoảng vô nghĩa thực dụng (ROPE), ngưỡng vô hiệu (ref_val):<jupyter_code>az.plot_posterior(np_1D_dat,
var_names = ['x'],
credible_interval = 0.95,
point_estimate = 'median',
rope = (-1.5,7),
ref_val = 0,
**{'alpha': 0.8, 'color':'blue'})
az.plot_posterior(np_1D_dat,
var_names = ['x'],
credible_interval = 0.95,
point_estimate = 'median',
rope = (-1.5,7),
ref_val = 0,
kind = 'hist',)<jupyter_output><empty_output><jupyter_text>Hàm này dùng tốt cho dữ liệu đa biến:<jupyter_code>az.plot_posterior(np_3D_dat)<jupyter_output><empty_output><jupyter_text>## Hàm plot_density
Hàm plot_density có công dụng đơn giản hơn plot_posterior, nó trình bày thêm 1 điểm giá trị Median hoặc mean, mode;
Ưu thế của hàm này đó là cho phép so sánh 2 hay nhiều phân nhóm:<jupyter_code>np_3D_dat2 = az.convert_to_inference_data(np.random.randn(*k)-1)
az.plot_density(np_3D_dat,
figsize = (12,3),
shade = 0.3,
point_estimate = "median",
credible_interval =1,
colors = "red")
az.plot_density([np_3D_dat, np_3D_dat2],
figsize = (12,3),
shade = 0.3,
credible_interval =0.95,
point_estimate = "median")<jupyter_output><empty_output><jupyter_text>## Hàm plot_joint
Hàm plot_joint cho phép biểu diễn hình ảnh Xác suất kết hợp (Joint pribability) và Xác suất biên (Marginal prob) trên cùng 1 biểu đồ.
Xác suất kết hợp có thể biểu diễn bằng 3 kiểu hình họa: tán xạ, hex_bin và 2D KDE
Xác suất biên có 2 kiểu hình họa: 1D KDE và Histogram<jupyter_code>datadict = {
'X': np.random.normal(2,2,size = n),
'Y': np.random.normal(2,2,size = n)* 2 + np.random.normal(0,5,1000),
}
az.plot_joint(datadict)
az.plot_joint(datadict,
joint_kwargs = {'color':"red", 'alpha': 0.3},
marginal_kwargs = {'color':'red',
'fill_kwargs':{'alpha': 0.3, 'color':'#eb3483'}}
)
az.plot_joint(datadict,
figsize=(5.7,5),
kind = 'hexbin',
marginal_kwargs = {'color':'black',
'fill_kwargs':{'alpha': 0.9, 'color':'#ebbd34'}}
)
az.plot_joint(datadict,
figsize=(5.7,5),
kind = 'kde',
marginal_kwargs = {'color':'black',
'fill_kwargs':{'alpha': 0.9, 'color':'#ebbd34'}}
)<jupyter_output><empty_output><jupyter_text>## Hàm plot_pair
Hàm này là sự mở rộng của hàm plot_join, vì nó cho phép khảo sát bắt cặp tuần tự dữ liệu có từ 3 biến trở lên (ma trận tương quan).<jupyter_code>datadict = {
'X': np.random.normal(1,2,size = n),
'Y': np.random.normal(1,2,size = n)*2 + np.random.rand(1000),
'Z': np.random.normal(1,2,size = n)*(-2) + np.random.rand(1000),
}
az.plot_pair(datadict)
az.plot_pair(np_3D_dat,
figsize=(5.7,5),
coords = {'x_dim_0': [0, 1, 2]},
var_names = ['x'],
kind = 'kde',
divergences = True,
)
az.plot_pair(datadict,
figsize=(5.7,5),
colorbar=True,
kind ='hexbin')<jupyter_output><empty_output><jupyter_text>## Hàm plot_forest
Hàm plot_forest cho phép biểu diễn nội dung các posterior distribution của coeficients các mô hình Bayes; tuy nhiên ta có thể dùng nó để so sánh trực quan giữa nhiều phân nhóm hay nhiều biến có cùng thang đo (tương đương ridge_plot, forest_plot)<jupyter_code>datadict = {
'X': np.random.normal(1,2,size = n),
'Y': np.random.normal(1,2,size = n)*2 + np.random.rand(1000),
'Z': np.random.normal(1,2,size = n)*(-2) + np.random.rand(1000),
}
az.plot_forest(datadict,
kind="forestplot",
rope = (-5,5),
credible_interval = 0.95,
colors = "red")
az.plot_forest(datadict,
kind="ridgeplot",
credible_interval = 0.95,
ridgeplot_alpha = 0.5,
ridgeplot_overlap = 3,
colors = "red")<jupyter_output><empty_output>
|
no_license
|
/Arviz demo 1.ipynb
|
kinokoberuji/Statistics-Python-Tutorials
| 15 |
<jupyter_start><jupyter_text># Programming and Data Analysis
> Homework 0
Kuo, Yao-Jen from [DATAINPOINT](https://www.datainpoint.com)## Instructions
- We've imported necessary modules at the beginning of each exercise.
- We've put necessary files(if any) in the working directory of each exercise.
- We've defined the names of functions/inputs/parameters for you.
- Write down your solution between the comments `### BEGIN SOLUTION` and `### END SOLUTION`.
- It is NECESSARY to `return` the answer, tests will fail by just printing out the answer.
- Do not use `input()` function, it will halt the notebook while running tests.
- Running tests to see if your solutions are right: Kernel -> Restart & Run All -> Restart and Run All Cells.
- You can run tests after each question or after finishing all questions.<jupyter_code>import unittest<jupyter_output><empty_output><jupyter_text>## 01. Define a function named `convert_fahrenheit_to_celsius(x)` which converts Fahrenheit degrees to Celsius degrees.
\begin{equation}
Celsius^{\circ} C = (Fahrenheit^{\circ} F - 32) \times \frac{5}{9}
\end{equation}
- Expected inputs:a numeric `x`.
- Expected outputs:a numeric.<jupyter_code>def convert_fahrenheit_to_celsius(x):
"""
>>> convert_fahrenheit_to_celsius(212)
100.0
>>> convert_fahrenheit_to_celsius(32)
0.0
"""
### BEGIN SOLUTION
y = (x - 32) * 5/9
return y
### END SOLUTION<jupyter_output><empty_output><jupyter_text>## 02. Define a function named `calculate_bmi(height, weight)` which calculates BMI according to heights in meters and weights in kilograms.
\begin{equation}
BMI = \frac{weight_{kg}}{height_{m}^2}
\end{equation}
Source:
- Expected inputs:2 numerics `height` and `weight`.
- Expected outputs:a numeric.<jupyter_code>def calculate_bmi(height, weight):
"""
>>> calculate_bmi(216, 147) # Shaquille O'Neal in his prime
31.507201646090532
>>> calculate_bmi(206, 113) # LeBron James
26.628334433028563
>>> calculate_bmi(211, 110) # Giannis Antetokounmpo
24.70744143213315
"""
### BEGIN SOLUTION
BMI = weight / ((0.01 * height) * (0.01 * height))
return BMI
### END SOLUTION<jupyter_output><empty_output><jupyter_text>## 03. Define a function named `show_big_mac_index(country, currency, price)` which returns the Big Mac Index given a country, its currency, and the price of a Big Mac.
- Expected inputs:2 strings and a numeric.
- Expected outputs:a string.<jupyter_code>def show_big_mac_index(country, currency, price):
"""
>>> show_big_mac_index('US', 'USD', 5.65)
A Big Mac costs 5.65 USD in US.
>>> show_big_mac_index('South Korea', 'Won', 6520)
A Big Mac costs 6,520.00 Won in South Korea.
>>> show_big_mac_index('Taiwan', 'NTD', 72)
A Big Mac costs 72.00 NTD in Taiwan.
"""
### BEGIN SOLUTION
ans = 'A Big Mac costs ' + str('{:0,.2f}'.format(price)) + ' ' + currency + ' in ' + country + '.'
return ans
### END SOLUTION<jupyter_output><empty_output><jupyter_text>## 04. Define a function named `is_a_divisor(x, y)` which returns whether `x` is a is_a_divisor of `y` or not.
- Expected inputs:2 integers.
- Expected outputs:a boolean.<jupyter_code>def is_a_divisor(x, y):
"""
>>> is_a_divisor(1, 3)
True
>>> is_a_divisor(2, 3)
False
>>> is_a_divisor(3, 3)
True
>>> is_a_divisor(1, 4)
True
>>> is_a_divisor(2, 4)
True
>>> is_a_divisor(3, 4)
False
>>> is_a_divisor(4, 4)
True
"""
### BEGIN SOLUTION
if y % x == 0:
return True
else:
return False
### END SOLUTION<jupyter_output><empty_output><jupyter_text>## 05. Define a function named `contains_vowels(x)` which returns whether x contains one of the vowels: a, e, i, o, u or not.
- Expected inputs:a string.
- Expected outputs:a boolean.<jupyter_code>def contains_vowels(x):
"""
>>> contains_vowels('pythn')
False
>>> contains_vowels('ncnd')
False
>>> contains_vowels('rtclt')
False
>>> contains_vowels('python')
True
>>> contains_vowels('anaconda')
True
>>> contains_vowels('reticulate')
True
"""
### BEGIN SOLUTION
if ('a' in x) or ('e' in x) or ('i' in x) or ('o' in x) or ('u' in x):
return True
else:
return False
### END SOLUTION<jupyter_output><empty_output><jupyter_text>## Run tests!
Kernel -> Restart & Run All. -> Restart And Run All Cells.<jupyter_code>class TestHomeworkZero(unittest.TestCase):
def test_01_convert_fahrenheit_to_celsius(self):
self.assertAlmostEqual(convert_fahrenheit_to_celsius(212), 100.0)
self.assertAlmostEqual(convert_fahrenheit_to_celsius(32), 0.0)
def test_02_calculate_bmi(self):
self.assertTrue(calculate_bmi(216, 147) > 31)
self.assertTrue(calculate_bmi(216, 147) < 32)
self.assertTrue(calculate_bmi(206, 113) > 26)
self.assertTrue(calculate_bmi(206, 113) < 27)
self.assertTrue(calculate_bmi(211, 110) > 24)
self.assertTrue(calculate_bmi(211, 110) < 25)
def test_03_show_big_mac_index(self):
self.assertEqual(show_big_mac_index('US', 'USD', 5.65), 'A Big Mac costs 5.65 USD in US.')
self.assertEqual(show_big_mac_index('South Korea', 'Won', 6520), 'A Big Mac costs 6,520.00 Won in South Korea.')
self.assertEqual(show_big_mac_index('Taiwan', 'NTD', 72), 'A Big Mac costs 72.00 NTD in Taiwan.')
def test_04_is_a_divisor(self):
self.assertTrue(is_a_divisor(1, 2))
self.assertTrue(is_a_divisor(2, 2))
self.assertTrue(is_a_divisor(1, 3))
self.assertFalse(is_a_divisor(2, 3))
self.assertTrue(is_a_divisor(1, 4))
self.assertTrue(is_a_divisor(2, 4))
self.assertFalse(is_a_divisor(3, 4))
self.assertTrue(is_a_divisor(4, 4))
def test_05_contains_vowels(self):
self.assertFalse(contains_vowels('pythn'))
self.assertFalse(contains_vowels('ncnd'))
self.assertFalse(contains_vowels('rtclt'))
self.assertTrue(contains_vowels('python'))
self.assertTrue(contains_vowels('anaconda'))
self.assertTrue(contains_vowels('reticulate'))
suite = unittest.TestLoader().loadTestsFromTestCase(TestHomeworkZero)
runner = unittest.TextTestRunner(verbosity=2)
test_results = runner.run(suite)
number_of_failures = len(test_results.failures)
number_of_errors = len(test_results.errors)
number_of_test_runs = test_results.testsRun
number_of_successes = number_of_test_runs - (number_of_failures + number_of_errors)
print("You've got {} successes among {} questions.".format(number_of_successes, number_of_test_runs))<jupyter_output>You've got 5 successes among 5 questions.
|
no_license
|
/exercises.ipynb
|
rose020/homework0
| 7 |
<jupyter_start><jupyter_text>#### Plotting of gesture data<jupyter_code>print("Shape of X_train: ", X_train.shape)
print("shape of y_train/labels: ", y_train.shape)
print("Shape of X_test: ", X_test.shape)
print("shape of y_test/labels: ", y_test.shape)
samples = np.random.choice(len(X_train), 8)
def show_images(images, cols = 1, titles = None):
"""Display a list of images in a single figure with matplotlib.
Parameters
---------
images: List of np.arrays compatible with plt.imshow.
cols (Default = 1): Number of columns in figure (number of rows is
set to np.ceil(n_images/float(cols))).
titles: List of titles corresponding to each image. Must have
the same length as titles.
"""
assert((titles is None)or (len(images) == len(titles)))
n_images = len(images)
if titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)]
fig = plt.figure()
for n, (image, title) in enumerate(zip(images, titles)):
a = fig.add_subplot(cols, np.ceil(n_images/float(cols)), n + 1)
if image.ndim == 2:
plt.gray()
plt.imshow(image)
a.set_title(title, fontsize=50)
a.grid(False)
a.axis("off")
fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
plt.show()
sample_images = []
sample_labels = []
for sample in samples:
sample_images.append(X_train[sample])
for key, val in label_dict.items():
if np.argmax(y_train[sample]) == val:
sample_labels.append(key)
show_images(sample_images, 2, titles=sample_labels)<jupyter_output><empty_output><jupyter_text>### Model<jupyter_code>def create_model():
model = Sequential()
model.add(Conv2D(64, kernel_size = [3,3], padding = 'same', activation = 'relu', input_shape = (200,200,3)))
model.add(Conv2D(64, kernel_size = [3,3], padding = 'same', activation = 'relu'))
model.add(MaxPool2D(pool_size = [3,3]))
model.add(Conv2D(128, kernel_size = [5,5], padding = 'same', activation = 'relu'))
model.add(Conv2D(128, kernel_size = [5,5], padding = 'same', activation = 'relu'))
model.add(MaxPool2D(pool_size = [3,3]))
model.add(Conv2D(256, kernel_size = [3,3], padding = 'same', activation = 'relu'))
model.add(Conv2D(256, kernel_size = [3,3], padding = 'same', activation = 'relu'))
model.add(Conv2D(256, kernel_size = [3,3], padding = 'same', activation = 'relu'))
model.add(MaxPool2D(pool_size = [3,3]))
model.add(Conv2D(512, kernel_size = [3,3], padding = 'same', activation = 'relu'))
model.add(Conv2D(512, kernel_size = [3,3], padding = 'same', activation = 'relu'))
model.add(MaxPool2D(pool_size = [3,3]))
model.add(Conv2D(512, kernel_size = [3,3], padding = 'same', activation = 'relu'))
model.add(MaxPool2D(pool_size = [2,2]))
model.add(BatchNormalization())
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(1024, activation = 'relu', kernel_regularizer = regularizers.l2(0.001)))
model.add(Dense(512, activation = 'relu', kernel_regularizer = regularizers.l2(0.001)))
model.add(Dense(36, activation = 'softmax'))
print("MODEL CREATED")
return model
model = create_model()
model.summary()
model.compile(optimizer = 'adam', loss = keras.losses.categorical_crossentropy, metrics = ["accuracy"])
model_hist = model.fit(X_train, y_train, batch_size = 32, epochs = 15, validation_data=(X_test, y_test))<jupyter_output>WARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
Train on 24026 samples, validate on 1265 samples
Epoch 1/15
24026/24026 [==============================] - 84s 3ms/step - loss: 2.1800 - acc: 0.5566 - val_loss: 2.0808 - val_acc: 0.5407
Epoch 2/15
24026/24026 [==============================] - 81s 3ms/step - loss: 0.8187 - acc: 0.8212 - val_loss: 0.5425 - val_acc: 0.8838
Epoch 3/15
24026/24026 [==============================] - 81s 3ms/step - loss: 0.4958 - acc: 0.8852 - val_loss: 0.8439 - val_acc: 0.7739
Epoch 4/15
24026/24026 [==============================] - 81s 3ms/step - loss: 0.3759 - acc: 0.9093 - val_loss: 0.3088 - val_acc: 0.9241
Epoch 5/15
24026/24026 [==============================] - 81s 3ms/step - loss: 0.3117 - acc: 0.9276 - val_loss: 0.3129 - val_acc: 0.9273
Epoch 6/15
24[...]<jupyter_text>### Plotting training metrices<jupyter_code>def plot_accuracy(y):
if(y == True):
plt.plot(model_hist.history['acc'])
plt.plot(model_hist.history['val_acc'])
plt.legend(['train', 'test'], loc='lower right')
plt.title('accuracy plot - train vs test')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.show()
else:
pass
return
def plot_loss(y):
if(y == True):
plt.plot(model_hist.history['loss'])
plt.plot(model_hist.history['val_loss'])
plt.legend(['training loss', 'validation loss'], loc = 'upper right')
plt.title('loss plot - training vs vaidation')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()
else:
pass
return
plot_accuracy(True)
plot_loss(True)
model.save("asl_bestsofar.h5")
samples_test = np.random.choice(len(X_test), 8)
samples_test
sample_images = []
sample_labels = []
pred_labels = []
for sample in samples_test:
sample_images.append(X_test[sample])
img = X_test[sample].reshape((1,200,200,3))
pred = model.predict_classes(img)
for key, val in label_dict.items():
if pred[0] == int(val):
pred_labels.append(key)
for key, val in label_dict.items():
if np.argmax(y_test[sample]) == val:
sample_labels.append(key)
def show_test_images(images, cols = 1, true_label = None, pred_label=None):
n_images = len(images)
fig = plt.figure()
for n, (image, label, pred) in enumerate(zip(images, true_label, pred_label)):
a = fig.add_subplot(cols, np.ceil(n_images/float(cols)), n + 1)
if image.ndim == 2:
plt.gray()
plt.imshow(image)
a.set_title("{}\n{}".format(label, pred), fontsize=50)
a.grid(False)
a.axis("off")
fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
plt.show()
show_test_images(sample_images, 2, sample_labels, pred_labels)<jupyter_output><empty_output>
|
no_license
|
/asl-training.ipynb
|
ayulockin/ASL_Classifier
| 3 |
<jupyter_start><jupyter_text># Pandas basics
In this notebook we will **learn** how to work with the two main data types in `pandas`: `DataFrame` and `Series`.## Data structures (`pandas`)### `Series`
In `pandas`, series are the building blocks of dataframes.
Think of a series as a column in a table. A series collects *observations* about a given *variable*. <jupyter_code>from random import random
import pandas as pd
import numpy as np
from pandas import Series, DataFrame<jupyter_output><empty_output><jupyter_text>#### Numerical series<jupyter_code># let's create a series containing 100 random numbers
# ranging between 0 and 1
s = pd.Series([random() for n in range(0, 10)])<jupyter_output><empty_output><jupyter_text>Each observation in the series has an **index** as well as a set of **values**: they can be accessed via the omonymous properties:<jupyter_code>s.index
list(s.index)
s.values<jupyter_output><empty_output><jupyter_text>The `head()` and `tail()` methods allows for looking at the begininning and end of a series:<jupyter_code>s.head()
s.tail()<jupyter_output><empty_output><jupyter_text>The `value_counts()` method returns a count of distinct values within a series.Is there any number in `s` that occurs twice?<jupyter_code># a `Series` can be easily cast into a list
list(s.value_counts()).count(2)<jupyter_output><empty_output><jupyter_text>Another way of verifying this:<jupyter_code>s.is_unique
s.min()
s.max()
s.mean()
s.median()<jupyter_output><empty_output><jupyter_text>#### Datetime series<jupyter_code>from random import randint
from datetime import date
# let's generate a list of random dates
# in the range 1900-1950
dates = [
date(
year,
randint(1, 12),
randint(1, 28) # try replacing with 31 and see what happens
)
for year in range(1900,1950)
]
s1 = pd.Series(dates)
s1
type(s1[1])
s1 = Series(pd.to_datetime(dates))
type(s1[1])
s1[1].day_name()
s1.min()
s1.max()
s1.mean()<jupyter_output><empty_output><jupyter_text>### `DataFrame`
What is a `pandas.DataFrame`? Think of it as an in-memory spreadsheet that you can analyse and manipulate programmatically.
A `DataFrame` is a collection of `Series` having the same length and whose indexes are in sync. A *collection* means that each column of a dataframe is a seriesLet's create a toy `DataFrame` by hand. <jupyter_code>dates = [
date(
year,
randint(1, 12),
randint(1, 28) # try replacing with 31 and see what happens
)
for year in range(1980,1990)
]
counts = [
randint(0, 10000)
for i in range(0, 10)
]
event_types = ["fire", "flood", "car_crash", "plane_crash"]
events = [
np.random.choice(event_types)
for i in range(0, 10)
]
assert len(events) == len(counts) == len(dates)
toy_df = pd.DataFrame({
"date": dates,
"count": counts,
"event": events
})
toy_df<jupyter_output><empty_output><jupyter_text>**Try out**: what happens if you change the length of either of the two lists? Try e.g. passing 20 dates instead of 10.<jupyter_code># a df is a collection of series
# each column is a series
type(toy_df.date)<jupyter_output><empty_output><jupyter_text>## Data manipulation in `pandas`### Data types
String, datetimes (see above), categorical data.
In `pandas`, categories behave very much like string, yet they lead to better performances (faster operations, optimized storage).Bottom-up approach:<jupyter_code># transforms a Series with strings into categories
toy_df.event.astype('category')<jupyter_output><empty_output><jupyter_text>### Exploring a dataframe
Exploring a dataframe: df.head(), df.tail(), df.info().The method `info()` gives you information about a dataframe:
- how much space does it take in memory?
- what is the datatype of each column?
- how many records are there?
- how many `null` values does each column contain (!)?<jupyter_code>toy_df.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 date 10 non-null object
1 count 10 non-null int64
2 event 10 non-null object
dtypes: int64(1), object(2)
memory usage: 368.0+ bytes
<jupyter_text>Alternatively, if you need to know only the number of columns and rows you can use the `.shape` property.
It returns a tuple with 1) number of rows, 2) number of columns.<jupyter_code>toy_df.shape<jupyter_output><empty_output><jupyter_text>`head()` prints by first five rows of a dataframe:<jupyter_code>toy_df.head()<jupyter_output><empty_output><jupyter_text>But the number of lines displayed is a parameter that can be changed:<jupyter_code>toy_df.head(2)<jupyter_output><empty_output><jupyter_text>`tail()` does the opposite, i.e. prints the last n rows in the dataframe:<jupyter_code>toy_df.tail()<jupyter_output><empty_output><jupyter_text>#### Adding columnsLet's go back to our toy dataframe:<jupyter_code>toy_df.head()<jupyter_output><empty_output><jupyter_text>Using the column selector with the name of a column that does not exist yet will add the effect of setting the values of all rows in that column to the value specified.<jupyter_code>toy_df['country'] = "UK"
toy_df.head(3)<jupyter_output><empty_output><jupyter_text>But if the column already exists, its value is reset:<jupyter_code>toy_df['country'] = "USA"
toy_df.head(3)<jupyter_output><empty_output><jupyter_text>#### Removing columnsThe double square bracket notation ``[[...]]`` returns a dataframe having only the columns specified inside the inner brackets.This said, removing a column is done by unselecting it:<jupyter_code># here we removed the column country
toy_df2 = toy_df[['date', 'count', 'event']]
# it worked!
toy_df2.head()<jupyter_output><empty_output><jupyter_text>#### Setting a column as index<jupyter_code>toy_df.set_index('date')
toy_df.head(3)
toy_df.set_index('date', inplace=True)
toy_df.head(3)<jupyter_output><empty_output><jupyter_text>**Q**: can you explain the effect of the `inplace` parameter by looking at the cells above?### Accessing data
.loc, .iloc, slicing, iteration over rows<jupyter_code>toy_df.head(3)<jupyter_output><empty_output><jupyter_text>#### Label-based indexing<jupyter_code>toy_df.loc[date(1980,1,1):date(1982,1,1)]<jupyter_output><empty_output><jupyter_text>#### Integer-based indexing<jupyter_code># select a single row, the first one
toy_df.iloc[0]
# select a range of rows by index
toy_df.iloc[[1,3,-1]]
# select a range of rows with slicing
toy_df.iloc[0:5]
toy_df.index<jupyter_output><empty_output><jupyter_text>#### Iterating over rows<jupyter_code>for n, row in toy_df.iterrows():
print(n)
for n, row in toy_df.iterrows():
print(n, row.event)<jupyter_output>1980-01-23 plane_crash
1981-04-15 plane_crash
1982-11-12 flood
1983-11-22 plane_crash
1984-11-04 fire
1985-06-19 flood
1986-09-14 plane_crash
1987-01-05 fire
1988-03-11 flood
1989-10-10 car_crash
|
permissive
|
/notebooks/3_PandasBasics.ipynb
|
Giovanni1085/UvA_CDH_2020
| 24 |
<jupyter_start><jupyter_text><jupyter_code>import numpy as np # useful for many scientific computing in Python
import pandas as pd # primary data structure library
!conda install -c anaconda xlrd --yes
df_can = pd.read_excel('https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/Data_Files/Canada.xlsx',
sheet_name='Canada by Citizenship',
skiprows=range(20),
skipfooter=2)
print ('Data read into a pandas dataframe!')
#Dataset of immigration into canada from other countries - 1980 to 2013 (each year and each country)
df_can.head(10)
df_can.shape
df_can.tail()
df_can.info()
#simplify and remove unnecessary columns
df_can.drop(['AREA','REG','DEV','Type','Coverage'], inplace=True, axis='columns')
df_can.head()
#rename columns to sensible names
df_can.rename(columns={'OdName':'Country', 'AreaName':'Continent', 'RegName':'Continent-Region'}, inplace=True)
df_can.head()
#count total immigration by country for all years
df_can['total_immigration'] = df_can.sum(axis='columns')
df_can.head()
df_can.describe()
df_can.isnull().sum()
df_can.dtypes
#Select immigration of years 1980-1985 from the dataset, for all countries?
#get the list of columns in the dataframe
df_can.columns
df_can[['Country',1980,1981,1982,1983,1984,1985]]
#simplify the dataset by changing the index from numbers to country names
df_can.index.values
df_can.set_index('Country', inplace=True)
df_can.head()
print(df_can.loc['India'])
df_can.iloc[8]
print(df_can.loc['Japan',2000])
print(df_can.iloc[12,12])
#convert columns names to string
#map - syntax(function, collection)
#apply function to each element of the collection - equivalent apply, mapply,sapply,lapply functions of R
df_can.columns = list(map(str,df_can.columns))
df_can.columns
#filtering on dataframe
#Q. find all countries in Asia
condition = df_can['Continent'] == 'Asia'
df_can[condition]
#Q. multiple conditions
df_can[(df_can['Continent']=='Asia')]
df_can[(df_can['1980'] > 1000)]
#syntax - df[(condition)]
df_can[(df_can['Continent']=='Asia')&(df_can['2013']>10000)]
df_can.where(df_can['Continent']=='Asia')
#conditions
#basic stats
import matplotlib.pyplot as plt
import matplotlib as mpl
import plotly as px
mpl.__version__
df_can.columns
years = list(map(str,range(1980,2014)))
years
india = df_can.loc['India',years]
india
india.plot()
india.index
#change the index to integer
india.index = india.index.map(int)
india.plot(kind='line')
plt.title('Immigration from India')
plt.ylabel('Number of immigrants')
plt.xlabel('Years')
#update the plot
plt.show()
india.plot(kind='line')
plt.title('Immigration from India')
plt.ylabel('Number of immigrants')
plt.xlabel('Years')
plt.text(2000, 32000, 'Y2K Revolution')
plt.text(1990,15000,'Recession')
plt.text(1985,10000,'Economic boom')
#update the plot
plt.show()
years = list(map(str,range(1980,2014)))
china = df_can.loc['China', years]
china.plot()
china.index = china.index.map(int)
china.plot(kind='line')
plt.title('Immigration of China')
plt.xlabel('Years')
plt.ylabel('Immigrants')
plt.text(1990,10000,'Marker')
plt.show()
years = list(map(str,range(1980,2014)))
chinaindia = df_can.loc[['China','India'], years]
new_chinaindia = chinaindia.transpose()
new_chinaindia.plot()
new_chinaindia.index = new_chinaindia.index.map(int)
new_chinaindia.plot(kind='line')
plt.title('Immigration of China and India')
plt.xlabel('Years')
plt.ylabel('Immigrants')
#plt.text(1990,10000,'Marker')
plt.show()
#Q. Which two countries have similar immigration trends over the years 1980-2013?
#Q. France and Germany
#top 5 countries that send immigrants to canada
df_can.sort_values(by='total_immigration', ascending=False, axis='index', inplace=True)
top5 = df_can.head(5)
top5
years = list(map(str,range(1980,2014)))
top5_clean = top5[years]
top5_clean = top5_clean.transpose()
top5_clean.plot()<jupyter_output><empty_output><jupyter_text>#Part 2<jupyter_code>#Area plots - Stacked line plot
top5_clean
top5_clean.index = top5_clean.index.map(int)
top5_clean.plot(kind="area", stacked=False, figsize=(20,10))
plt.title('Immigration trends in top five countries (1980-2013)')
plt.xlabel('Years')
plt.ylabel('Immigrants count')
plt.show()
top5_clean.index = top5_clean.index.map(int)
top5_clean.plot(kind="area", stacked=True, figsize=(20,10))
plt.title('Immigration trends in top five countries (1980-2013)')
plt.xlabel('Years')
plt.ylabel('Immigrants count')
plt.show()
top5_clean.index = top5_clean.index.map(int)
#alpha parameter for transparency - default = 0.5 (range is 0 to 1)
top5_clean.plot(kind="area", stacked=False, figsize=(20,10), alpha=0.25)
plt.title('Immigration trends in top five countries (1980-2013)')
plt.xlabel('Years')
plt.ylabel('Immigrants count')
plt.show()
#Bottom five countries - stacked and unstacked area plot
#histogram - at a particular time period / snapshot of the data
df_can['2000']
df_can['2000'].plot(kind='hist', figsize=(20,10))
plt.title('Immigration trends in 195 countries in 2000')
plt.xlabel('Number of Immigrants')
plt.ylabel('Number of Countries')
plt.show()
#histogram
years = list(map(str,range(1980,2014)))
df_can.loc[['India','China','Denmark','Norway','France','Germany'], years].transpose().plot.hist()
df_can.loc[['India','China','Denmark','Norway','France','Germany'], years].transpose().plot.hist()
plt.title('Immigration trends in 6 countries in 1980-2013')
plt.xlabel('Number of Immigrants')
plt.ylabel('Number of Countries')
plt.show()<jupyter_output><empty_output><jupyter_text>#Vertical bar plot<jupyter_code>india = df_can.loc['India', years]
india.plot(kind='bar', figsize=(20,10))
plt.title('Immigration trends India immigrants from 1980 to 2013')
plt.xlabel('Years')
plt.ylabel('India immigrants from 1980 to 2013')
plt.show()
india = df_can.loc['India', years]
india.index = india.index.map(int)
india.plot(kind='bar', figsize=(10,6))
plt.title('Immigration trends India immigrants from 1980 to 2013')
plt.xlabel('Years')
plt.ylabel('India immigrants from 1980 to 2013')
plt.annotate('Increasing trends', xy=(32, 70), xycoords='data',
xytext=(28, 20),
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='left', verticalalignment='top',
)
plt.show()
india = df_can.loc['India', years]
india.plot(kind='barh', figsize=(20,10))
plt.title('Immigration trends India immigrants from 1980 to 2013')
plt.xlabel('India immigrants from 1980 to 2013')
plt.ylabel('Years')
plt.show()<jupyter_output><empty_output>
|
permissive
|
/Lab Experiments/Experiment_3_200720.ipynb
|
rohitsmittal7/J045-ML-Sem-V
| 3 |
<jupyter_start><jupyter_text>**MATH 3332 **
**Section 52 **
# In Who-is-Normal.xslx there are 7 columns representing variables x1-x7, one of which is sample from the normal distribution. Find which one of the variables is normal?
## Reading in Values
The program starts by reading in the values from the Excel spreadsheet after they have been exported to a CSV format.<jupyter_code>import csv
f = open('input.csv', 'r')
reader = csv.reader(f)
values = []
for row in reader:
values.append(row)<jupyter_output><empty_output><jupyter_text>## Manipulating the Values
The program then transposes the matrix that was created when reading in the values from the CSV. The result is an array, where the rows consist of the name of the data (e.g., x1, x2) and the values for that distribution. <jupyter_code>import numpy as np
matrix = np.transpose(np.array(values))<jupyter_output><empty_output><jupyter_text>## Creating the Probability Plot
The program then creates a plot for each distribution using the **scipy.stats** library. The plot contains the **plotted values**, the $R^2$ value, the **mean**, and the **standard deviation **.<jupyter_code>import scipy.stats
import matplotlib.pyplot as plt
import matplotlib.gridspec as grid
%matplotlib inline
# Iterate over each dataset (x1, x2, etc)
for x_column in xrange(len(matrix)):
# Create array of float-type values from the dataset
values = np.array(matrix[x_column][1:])
values = [float(value) for value in values]
# Create a seperate figure to create the probability plot
fig = plt.figure()
fig.text(0, 0, 'Mean %s' % np.mean(values))
fig.text(1, 0, 'Std %s' % np.std(values))
fig.suptitle('x%s' % (x_column + 1))
# Produce the probability plot
scipy.stats.probplot(values, plot=plt)
# Create a separate figure to create the histogram
fig2 = plt.figure()
fig2.suptitle('x%s Histogram' % (x_column + 1))
# Produce the histogram using normalized values
plt.hist(values, normed=True)
# Add the normal distribution curve to the plot
mu, std = scipy.stats.norm.fit(values)
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = scipy.stats.norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
plt.show()<jupyter_output><empty_output>
|
no_license
|
/Probability/Normal.ipynb
|
rlacherksu/notebooks
| 3 |
<jupyter_start><jupyter_text># 株価の関係<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib
import numpy
import sqlite3
import pandas as pd
import os
fmdate="2015-01-01"
todate="2016-12-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = os.environ["HOME"]+'/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/board/board.db")
sql="""select date as tm,close from histDaily where code=? and date between ? and ? order by tm"""
res=pd.read_sql_query(sql,con,params=(code,fmdate,todate,))
dt=pd.to_datetime(res["tm"].values)
plt.scatter(dt,res["close"].values)
plt.xticks(rotation=90)
plt.title("株価ヒストリカル", fontproperties=fp)
plt.xlabel("date")
plt.ylabel("price")
plt.show()<jupyter_output><empty_output><jupyter_text>## 出来高との関係
出来高が増える。注目度が高くなる。なので<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import numpy
import sqlite3
import pandas as pd
import matplotlib
fmdate="2015-01-01"
todate="2017-07-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = r'/Users/admin/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/stock/daily.db")
sql="""select strftime('%Y%m%d',date) as tm,volume from histDaily where code=? and date between ? and ? order by tm"""
res=pd.read_sql_query(sql,con,params=(code,fmdate,todate,))
dt=pd.to_datetime(res["tm"].values)
plt.scatter(dt,res["volume"].values)
plt.xticks(rotation=90)
plt.title("出来高のヒストリカル", fontproperties=fp)
plt.xlabel("date")
plt.ylabel("volume")
plt.show()<jupyter_output><empty_output><jupyter_text>## 投稿文字スコアの推移
1or-1に修正し合算する,悲観的な投稿が多いか少ないかを見る<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import sqlite3
import pandas as pd
fmdate="2015-01-01"
todate="2017-07-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = r'/Users/admin/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/board/board.db")
# https://stackoverflow.com/questions/41324503/pandas-sqlite-query-using-variable
sql="""select strftime('%Y%m%d',b.date) as tm,sum(case when e.score >=0 then 1 else -1 end) as score from board b ,board_score e where b.code=e.code and b.tno=e.tno and b.mno=e.mno and b.code=? and b.date between ? and ? group by tm order by tm"""
res=pd.read_sql_query(sql,con,params=(code,fmdate,todate,))
#https://qiita.com/ColdFreak/items/1028927c81fdfa5f3ac2
dt=pd.to_datetime(res["tm"].values)
plt.scatter(dt,res["score"].values)
plt.xticks(rotation=90)
plt.title("投稿スコアの推移", fontproperties=fp)
plt.xlabel("tm")
plt.ylabel("log10(avg(score))")
plt.show()<jupyter_output><empty_output><jupyter_text>## ここまでの予想
- 出来高が上がると注目度が高くなる
- そうすると人が増える
- 怪しい情報も増えてくる
### 絵文字は置いといて
-時系列で集まる人数をカウントする。## 書き込み人数を時系列で出力
<jupyter_code># emoji kind
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy
import sqlite3
import os
import pandas as pd
fmdate="2015-01-01"
todate="2017-07-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = r'/Users/admin/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/board/board.db")
cur=con.cursor()
res=pd.read_sql_query("select tm,count(*) as user_count from (select strftime('%Y%m%d',date) as tm,user from board"+
" where date between ? and ? and code=? group by tm,user) group by tm",con,params=(fmdate,todate,code,))
dt=pd.to_datetime(res["tm"].values)
plt.scatter(dt,res["user_count"].values)
plt.xticks(rotation=90)
plt.title("投稿者数と時系列", fontproperties=fp)
plt.xlabel("tm")
plt.ylabel("user_count")
plt.show()
<jupyter_output><empty_output><jupyter_text>## 相関を見る
- 投稿者数と出来高の相関係数
- 営業日以外の場合もあるし,投稿のない場合もあるのでInnerJoin<jupyter_code># emoji kind
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sqlite3
import os
import pandas as pd
from sklearn import linear_model
fmdate="2015-01-01"
todate="2017-07-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = r'/Users/admin/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/board/board.db")
cur=con.cursor()
user=pd.read_sql_query("select tm,count(*) as user_count from (select strftime('%Y%m%d',date) as tm,user from board"+
" where date between ? and ? and code=? group by tm,user) group by tm",con,params=(fmdate,todate,code,))
user["tm"]=pd.to_datetime(user["tm"])
#user=user.set_index("tm")
#cur.close()
#con.close()
print(user.head())
#con=sqlite3.connect("../../../../data/stock/daily.db")
#cur=con.cursor()
volume=pd.read_sql_query("select strftime('%Y%m%d',date) as tm,volume/10000 as volume from histDaily where code=? and date between ? and ? order by tm",con,params=(code,fmdate,todate,))
volume["tm"]=pd.to_datetime(volume["tm"])
#volume=volume.set_index("tm")
cur.close()
con.close()
print(volume.head())
data=pd.merge(volume,user,how="inner",left_on="tm",right_on="tm")
print(data.head())
# https://qiita.com/m-hayashi/items/ee379c86e3e18f0ddc6d
# http://pythondatascience.plavox.info/scikit-learn/線形回帰
x=pd.DataFrame(data["volume"]).values
y=pd.DataFrame(data["user_count"]).values
model=linear_model.LinearRegression()
model.fit(x,y)
# 回帰係数
print(model.coef_)
# 切片 (誤差)
print(model.intercept_)
# 決定係数
print(model.score(x, y))
plt.scatter(x,y,color="red")
plt.plot(x,model.predict(x))
plt.title("出来高と投稿者数の関係", fontproperties=fp)
plt.xlabel("volume")
plt.ylabel("user_count")
plt.show()<jupyter_output> tm user_count
0 2015-01-01 1
1 2015-01-02 2
2 2015-01-03 1
3 2015-01-04 1
4 2015-01-05 1
tm volume
0 2015-01-05 2110.3
1 2015-01-06 3103.5
2 2015-01-07 2395.0
3 2015-01-08 1928.2
4 2015-01-09 3816.0
tm volume user_count
0 2015-01-05 2110.3 1
1 2015-01-06 3103.5 2
2 2015-01-07 2395.0 6
3 2015-01-08 1928.2 1
4 2015-01-09 3816.0 11
[[ 0.02094571]]
[-17.38032316]
0.709948491945
<jupyter_text>- 出来高が増えると投稿者数も増える
- 要は出来高が増えると目立つので参加者が増えるということ## 投稿スコアと出来高の関係
どうやら出来高で説明ができるのか?<jupyter_code># emoji kind
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sqlite3
import os
import pandas as pd
from sklearn import linear_model
fmdate="2015-01-01"
todate="2017-07-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = r'/Users/admin/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/board/board.db")
cur=con.cursor()
sql="""select strftime('%Y%m%d',b.date) as tm,sum(case when e.score >=0 then 1 else -1 end) as score,avg(e.score/e.wordnum) as ascore from board b ,board_score e where b.code=e.code and b.tno=e.tno and b.mno=e.mno and b.code=? and b.date between ? and ? group by tm order by tm"""
score=pd.read_sql_query(sql,con,params=(code,fmdate,todate,))
#https://qiita.com/ColdFreak/items/1028927c81fdfa5f3ac2
score["tm"]=pd.to_datetime(score["tm"])
#cur.close()
#con.close()
print(score.head())
#con=sqlite3.connect("../../../../data/stock/daily.db")
#cur=con.cursor()
volume=pd.read_sql_query("select strftime('%Y%m%d',date) as tm,volume/10000 as volume from histDaily where code=? and date between ? and ? order by tm",con,params=(code,fmdate,todate,))
volume["tm"]=pd.to_datetime(volume["tm"])
#volume=volume.set_index("tm")
cur.close()
con.close()
print(volume.head())
data=pd.merge(volume,score,how="inner",left_on="tm",right_on="tm")
print(data.head())
# https://qiita.com/m-hayashi/items/ee379c86e3e18f0ddc6d
# http://pythondatascience.plavox.info/scikit-learn/線形回帰
x=pd.DataFrame(data["volume"]).values
y=pd.DataFrame(data["score"]).values
model=linear_model.LinearRegression()
model.fit(x,y)
# 回帰係数
print(model.coef_)
# 切片 (誤差)
print(model.intercept_)
# 決定係数
print(model.score(x, y))
plt.scatter(x,y,color="red")
plt.plot(x,model.predict(x))
plt.title("出来高と投稿スコアの関係,スコアは-1to1に修正", fontproperties=fp)
plt.xlabel("volume")
plt.ylabel("score")
plt.show()
## 平均化
x=pd.DataFrame(data["volume"]).values
y=pd.DataFrame(data["ascore"]).values
model=linear_model.LinearRegression()
model.fit(x,y)
# 回帰係数
print(model.coef_)
# 切片 (誤差)
print(model.intercept_)
# 決定係数
print(model.score(x, y))
plt.scatter(x,y,color="red")
plt.plot(x,model.predict(x))
plt.title("出来高と投稿スコアの関係,スコアはscore/wordnumに修正", fontproperties=fp)
plt.xlabel("volume")
plt.ylabel("score")
plt.show()
<jupyter_output> tm score ascore
0 2015-01-01 1 0.043008
1 2015-01-02 -3 -0.463773
2 2015-01-03 -1 -0.399109
3 2015-01-04 -1 -0.455821
4 2015-01-05 -1 -0.555359
tm volume
0 2015-01-05 2110.3
1 2015-01-06 3103.5
2 2015-01-07 2395.0
3 2015-01-08 1928.2
4 2015-01-09 3816.0
tm volume score ascore
0 2015-01-05 2110.3 -1 -0.555359
1 2015-01-06 3103.5 -2 -0.728097
2 2015-01-07 2395.0 -7 -0.479000
3 2015-01-08 1928.2 -1 -0.605556
4 2015-01-09 3816.0 -13 -0.503629
[[-0.09497118]]
[ 101.33264451]
0.650158690959
<jupyter_text>出来高と投稿スコアにも相関関係がある## 投稿スコアと参加者数の関係
となるとこれも相関があるのか?<jupyter_code># emoji kind
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sqlite3
import os
import pandas as pd
from sklearn import linear_model
fmdate="2015-01-01"
todate="2017-07-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = os.environ["HOME"]+'/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/board/board.db")
cur=con.cursor()
sql="""select strftime('%Y%m%d',b.date) as tm,sum(case when e.score >=0 then 1 else -1 end) as score,avg(e.score/e.wordnum) as ascore from board b ,board_score e where b.code=e.code and b.tno=e.tno and b.mno=e.mno and b.code=? and b.date between ? and ? group by tm order by tm"""
score=pd.read_sql_query(sql,con,params=(code,fmdate,todate,))
#https://qiita.com/ColdFreak/items/1028927c81fdfa5f3ac2
score["tm"]=pd.to_datetime(score["tm"])
user=pd.read_sql_query("select tm,count(*) as user_count from (select strftime('%Y%m%d',date) as tm,user from board"+
" where date between ? and ? and code=? group by tm,user) group by tm",con,params=(fmdate,todate,code,))
user["tm"]=pd.to_datetime(user["tm"])
#user=user.set_index("tm")
cur.close()
con.close()
print(user.head())
print(score.head())
data=pd.merge(user,score,how="inner",left_on="tm",right_on="tm")
print(data.head())
# https://qiita.com/m-hayashi/items/ee379c86e3e18f0ddc6d
# http://pythondatascience.plavox.info/scikit-learn/線形回帰
x=pd.DataFrame(data["user_count"]).values
y=pd.DataFrame(data["score"]).values
model=linear_model.LinearRegression()
model.fit(x,y)
# 回帰係数
print(model.coef_)
# 切片 (誤差)
print(model.intercept_)
# 決定係数
print(model.score(x, y))
plt.scatter(x,y,color="red")
plt.plot(x,model.predict(x))
plt.title("参加者数と投稿スコアの関係,スコア-1to1修正", fontproperties=fp)
plt.xlabel("user_count")
plt.ylabel("score")
plt.show()
####
x=pd.DataFrame(data["user_count"]).values
y=pd.DataFrame(data["ascore"]).values
model=linear_model.LinearRegression()
model.fit(x,y)
# 回帰係数
print(model.coef_)
# 切片 (誤差)
print(model.intercept_)
# 決定係数
print(model.score(x, y))
plt.scatter(x,y,color="red")
plt.plot(x,model.predict(x))
plt.title("参加者数と投稿スコアの関係,スコアscore/wordnum", fontproperties=fp)
plt.xlabel("user_count")
plt.ylabel("score")
plt.show()<jupyter_output> tm user_count
0 2015-01-01 1
1 2015-01-02 2
2 2015-01-03 1
3 2015-01-04 1
4 2015-01-05 1
tm score ascore
0 2015-01-01 1 0.043008
1 2015-01-02 -3 -0.463773
2 2015-01-03 -1 -0.399109
3 2015-01-04 -1 -0.455821
4 2015-01-05 -1 -0.555359
tm user_count score ascore
0 2015-01-01 1 1 0.043008
1 2015-01-02 2 -3 -0.463773
2 2015-01-03 1 -1 -0.399109
3 2015-01-04 1 -1 -0.455821
4 2015-01-05 1 -1 -0.555359
[[-4.60171765]]
[ 28.35209875]
0.948489885375
<jupyter_text>どうやら人が増えるとスコアが下がる。下げたい人間が多いようだ## 参加者が多い時,少ない時の絵文字の特徴
- 参加者が多い時は下げようとする傾向が高いので絵文字がスコア低くなる?
- 1日ごとの絵文字別投稿数と参加者数,もしくは出来高との相関
- 使われている絵文字の上位10個
これはそのまま出して,一投稿1絵文字種類に修正する。(同じ絵文字を繰り返し使う投稿の影響削除)<jupyter_code>%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sqlite3
import os
import pandas as pd
from sklearn import linear_model
fmdate="2015-01-01"
todate="2017-07-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = os.environ["HOME"]+'/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/board/board.db")
# top 10
sql="select c.emoji,sum(c.num),s.score from board_emoji_count c,emoji_score s,board b where b.code=c.code and b.tno=c.tno and b.mno=c.mno and c.emoji=s.emoji and c.code=? and b.date between ? and ? group by c.emoji order by sum(c.num) desc limit 10"
emoji_list=pd.read_sql_query(sql,con,params=(code,fmdate,todate,))
print(emoji_list)
for em in emoji_list["emoji"]:
print(em)
user=pd.read_sql_query("select tm,count(*) as user_count from (select strftime('%Y%m%d',date) as tm,user from board"+
" where date between ? and ? and code=? group by tm,user) group by tm",con,params=(fmdate,todate,code,))
user["tm"]=pd.to_datetime(user["tm"])
emoji=pd.read_sql_query("select strftime('%Y%m%d',date) as tm,sum(c.num) as emoji_count from board b ,board_emoji_count c"+
" where b.code=c.code and b.tno=c.tno and b.mno=c.mno and b.date between ? and ? and b.code=? and c.emoji=? group by tm",con,params=(fmdate,todate,code,em,))
emoji["tm"]=pd.to_datetime(emoji["tm"])
data=pd.merge(user,emoji,how="inner")
data.drop("tm",axis=1)
x=pd.DataFrame(data["user_count"]).values
y=pd.DataFrame(data["emoji_count"]).values
model=linear_model.LinearRegression()
model.fit(x,y)
# 回帰係数
print(model.coef_)
# 切片 (誤差)
print(model.intercept_)
# 決定係数
print(model.score(x, y))
plt.scatter(x,y,color="red")
plt.plot(x,model.predict(x))
plt.title("絵文字"+em+"数とユーザ数の関係", fontproperties=fp)
plt.xlabel("user_count")
plt.ylabel("emoji_score")
plt.show()
con.close()
<jupyter_output> emoji sum(c.num) score
0 🙌 3329 1.00
1 😱 908 -0.75
2 💛 549 0.75
3 💀 514 -0.50
4 💩 450 -0.75
5 😁 383 0.50
6 😅 381 0.50
7 👍 180 0.50
8 😊 165 0.50
9 😃 134 0.50
🙌
[[ 0.06752109]]
[ 33.30399642]
0.0204427406372
<jupyter_text>## 一投稿人絵文字にDistinctする<jupyter_code>%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sqlite3
import os
import pandas as pd
from sklearn import linear_model
fmdate="2015-01-01"
todate="2017-07-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = os.environ["HOME"]+'/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/board/board.db")
# top 10
sql="select c.emoji,sum(c.num),s.score from board_emoji_count c,emoji_score s,board b where b.code=c.code and b.tno=c.tno and b.mno=c.mno and c.emoji=s.emoji and c.code=? and b.date between ? and ? group by c.emoji order by sum(c.num) desc limit 10"
emoji_list=pd.read_sql_query(sql,con,params=(code,fmdate,todate,))
print(emoji_list)
for em in emoji_list["emoji"]:
print(em)
user=pd.read_sql_query("select tm,count(*) as user_count from "+
"(select strftime('%Y%m%d',date) as tm,user from board "+
" where date between ? and ? and code=? group by tm,user) "+
"group by tm",con,params=(fmdate,todate,code,))
user["tm"]=pd.to_datetime(user["tm"])
emoji=pd.read_sql_query("select strftime('%Y%m%d',date) as tm,count(*) as emoji_count "+
" from board b ,board_emoji_count c"+
" where b.code=c.code and b.tno=c.tno and b.mno=c.mno and "+
" b.date between ? and ? and b.code=? and c.emoji=? group by tm",con,params=(fmdate,todate,code,em,))
emoji["tm"]=pd.to_datetime(emoji["tm"])
data=pd.merge(user,emoji,how="inner")
data.drop("tm",axis=1)
x=pd.DataFrame(data["user_count"]).values
y=pd.DataFrame(data["emoji_count"]).values
model=linear_model.LinearRegression()
model.fit(x,y)
# 回帰係数
print(model.coef_)
# 切片 (誤差)
print(model.intercept_)
# 決定係数
print(model.score(x, y))
plt.scatter(x,y,color="red")
plt.plot(x,model.predict(x))
plt.title("絵文字"+em+"数とユーザ数の関係", fontproperties=fp)
plt.xlabel("user_count")
plt.ylabel("emoji_score")
plt.show()
con.close()
<jupyter_output> emoji sum(c.num) score
0 🙌 3329 1.00
1 😱 908 -0.75
2 💛 549 0.75
3 💀 514 -0.50
4 💩 450 -0.75
5 😁 383 0.50
6 😅 381 0.50
7 👍 180 0.50
8 😊 165 0.50
9 😃 134 0.50
🙌
[[ 0.00145165]]
[ 0.92381301]
0.23822882925
<jupyter_text># 絵文字投稿率と出来高
絵文字の投稿率と出来高は関係があるか?出来高が増えると人が増える,絵文字率が増えるか。1日あたりの投稿率で<jupyter_code>%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sqlite3
import os
import pandas as pd
from sklearn import linear_model
fmdate="2015-01-01"
todate="2017-07-31"
code="6502"
if os.name == "nt": fname=r'C:\WINDOWS\Fonts\ipaexg.ttf'
else: fname = os.environ["HOME"]+'/Library/Fonts/ipaexg.ttf'
fp = matplotlib.font_manager.FontProperties(fname=fname, size=14)
con=sqlite3.connect(os.environ["DATA"]+"/board/board.db")
# emoji post
sql="select strftime('%Y%m%d',b.date) as tm,count(*) emoji_post_count from board b,board_emoji_count e where b.code=e.code and b.mno=e.mno and b.tno=e.mno and e.code=? and b.date between ? and ? group by tm order by tm "
emoji_list=pd.read_sql_query(sql,con,params=(code,fmdate,todate,))
# all post
sql="select strftime('%Y%m%d',date) as tm,count(*) all_post_count from board where code=? and date between ? and ? group by tm"
allpost_list=pd.read_sql_query(sql,con,params=(code,fmdate,todate,))
data=pd.merge(emoji_list,allpost_list,how="inner",left_on="tm",right_on="tm")
data["emoji_post_ratio"]=data["emoji_post_count"]/data["all_post_count"]
con.close()
# 出来高
con=sqlite3.connect("../../../../data/stock/daily.db")
cur=con.cursor()
volume=pd.read_sql_query("select strftime('%Y%m%d',date) as tm,volume/10000 as volume from histDaily where code=? and date between ? and ? order by tm",con,params=(code,fmdate,todate,))
#volume["tm"]=pd.to_datetime(volume["tm"])
#volume=volume.set_index("tm")
cur.close()
con.close()
data=pd.merge(data,volume,how="inner",left_on="tm",right_on="tm")
x=pd.DataFrame(data["volume"]).values
y=pd.DataFrame(data["emoji_post_ratio"]).values
model=linear_model.LinearRegression()
model.fit(x,y)
# 回帰係数
print(model.coef_)
# 切片 (誤差)
print(model.intercept_)
# 決定係数
print(model.score(x, y))
plt.scatter(x,y,color="red")
plt.plot(x,model.predict(x))
plt.title("絵文字投稿率と出来高", fontproperties=fp)
plt.xlabel("volume")
plt.ylabel("emoji_post_ratio")
plt.show()<jupyter_output>[[ -4.82129903e-07]]
[ 0.01603249]
0.12813828662
|
no_license
|
/theme/notebook/22_toshiba_stock.ipynb
|
k-utsubo/xc40
| 10 |
<jupyter_start><jupyter_text>## Online Factorization Machine
Online factorization models take single data as an input, make a prediction, and train with the data.### 1. Setup
The from models imports the package for use. We have also imported a few other packages for plotting.<jupyter_code>import sys
sys.path.append('./../')
from utils import data_preprocess, plot
import os
import pickle
import numpy as np
import torch
from time import time
from models.models_online.FM_FTRL import FM_FTRL
from models.models_online.SFTRL_CCFM import SFTRL_CCFM
from models.models_online.SFTRL_Vanila import SFTRL_Vanila
from models.models_online.RRF_Online import RRF_Online
from utils.data_manager import *
from utils.metric_manager import *
Tensor_type = torch.DoubleTensor
import seaborn as sns
import os
sns.set()
sns.set_style('white')
import matplotlib
plt.rcParams["axes.grid"] = True
plt.rc('font', family='serif')
current_palette = sns.color_palette(sns.hls_palette(5, l=.6, s=1.0))
sns.palplot(current_palette)
current_palette = np.asarray(current_palette)<jupyter_output><empty_output><jupyter_text>### 2. Create a dataset depending on task
We prepare movielens100-k for regression and cod-ran dataset for classification<jupyter_code>task = 'cls'
if task == 'reg':
nbUsers = 943
nbMovies = 1682
nbFeatures = nbUsers + nbMovies
nbRatingsTrain = 90570
nbRatingsTest = 9430
data_dir = os.getcwd() + '/../dataset/ml-100k/'
#filename1, filename2 = 'ub.base', 'ub.test'
filename1, filename2 = 'ua.base', 'ua.test'
_, x_train, y_train, rate_train, timestamp_train = load_dataset_movielens(data_dir + filename1,nbRatingsTrain,nbFeatures,nbUsers)
x_train_s, rate_train_s, _ = sort_dataset_movielens(x_train, rate_train, timestamp_train)
want_permute = True
if want_permute :
idx = np.random.permutation(x_train_s.shape[0])
x_train_s = x_train_s[idx]
rate_train_s = rate_train_s[idx]
else:
pass
x_train_s = x_train_s.todense()
elif task == 'cls':
data_dir = './../dataset/cod-rna2/'
filename = "cod-rna2.scale"
X, y = load_svmlight_file(data_dir + filename, n_features=8)
X = X.toarray()
want_permute = False
if want_permute :
idx = np.random.permutation(X.shape[0])
x_train_s = np.asarray(X[idx])
rate_train_s = np.asarray(y[idx])
else:
x_train_s = np.asarray(X)
rate_train_s = np.asarray(y)
else:
raise ValueError<jupyter_output><empty_output><jupyter_text>### 3. Create factorization machines and conduct online task
There are four models in this notebook; 'FTRL','SFTRL_C','SFTRL_V','Online_RFF'<jupyter_code>model_option_list = ['FTRL','SFTRL_C','SFTRL_V','Online_RFF']
model_option = 'SFTRL_C'
#model_option = 'Online_RFF'
m = 40
lr_FM = 0.005
assert(model_option in model_option_list)
if model_option is 'FTRL':
Model_FM_FTRL = FM_FTRL(Tensor_type(x_train_s),Tensor_type(rate_train_s) , task,lr_FM, m )
pred_y, label_y , time = Model_FM_FTRL.online_learning()
elif model_option is 'SFTRL_C':
Model_SFTRL_C = SFTRL_CCFM(Tensor_type(x_train_s),Tensor_type(rate_train_s) , task,lr_FM,m )
pred_y, label_y , time = Model_SFTRL_C.online_learning()
elif model_option is 'SFTRL_V':
Model_SFTRL_V = SFTRL_Vanila(Tensor_type(x_train_s),Tensor_type(rate_train_s) , task,lr_FM,m )
pred_y, label_y , time = Model_SFTRL_V.online_learning()
elif model_option in 'Online_RFF':
inputs_matrix, outputs = Tensor_type(x_train_s), Tensor_type(rate_train_s)
Online_RRF = RRF_Online(inputs_matrix,outputs,task)
pred_y, label_y , time = Online_RRF.online_learning()
#print(type(x_train_s))
<jupyter_output>========================================
SFTRL_CCFM_0.005_40_start
0 th : pred 1.000000 , real -1.000000
1000 th : pred -1.000000 , real -1.000000
2000 th : pred -1.000000 , real 1.000000
3000 th : pred -1.000000 , real -1.000000
4000 th : pred -1.000000 , real -1.000000
5000 th : pred -1.000000 , real -1.000000
6000 th : pred -1.000000 , real -1.000000
7000 th : pred -1.000000 , real -1.000000
8000 th : pred -1.000000 , real -1.000000
9000 th : pred -1.000000 , real -1.000000
10000 th : pred -1.000000 , real -1.000000
11000 th : pred -1.000000 , real -1.000000
12000 th : pred -1.000000 , real -1.000000
13000 th : pred -1.000000 , real -1.000000
14000 th : pred -1.000000 , real -1.000000
15000 th : pred -1.000000 , real -1.000000
16000 th : pred -1.000000 , real -1.000000
17000 th : pred -1.000000 , real -1.000000
18000 th : pred -1.000000 , real -1.000000
19000 th : pred -1.000000 , real -1.000000
20000 th : pred -1.000000 , real -1.000000
21[...]<jupyter_text>### 4. Cacluate Metric
We prepare the each metric for regression (average root mean squre) and classification (average accuracy )<jupyter_code>if task == 'reg':
metric = regression_metric(pred_y,label_y)
elif task == 'cls':
_,metric = classfication_metric(pred_y,label_y)<jupyter_output><empty_output><jupyter_text>### 5. Results figures
We shows the resutls of prediction and accuracy for regression and classification<jupyter_code>fontsiz = 15
fig = plt.figure(figsize=(8*2,5.5))
fig.add_subplot(1,2,1)
plt.plot(pred_y,'b.', label = 'pred',alpha = 0.8)
plt.plot(label_y,'r.' , label = 'label',alpha = 0.8)
plt.xlabel('iteration' , fontsize = fontsiz)
plt.ylabel('y' , fontsize = fontsiz)
plt.title('pred vs real' ,fontsize = fontsiz)
plt.tick_params(axis='both', labelsize=fontsiz)
#plt.legend(loc='upper center', bbox_to_anchor=(0, 1. + 0.075 ,1-0.05,0.1), ncol = 2 , fontsize = fontsiz)
plt.legend( fontsize = fontsiz)
fig.add_subplot(1,2,2)
plt.plot(metric,'b', label = 'metric',alpha = 0.8 ,linewidth = 2.0)
plt.xlabel('iteration' , fontsize = fontsiz)
plt.ylabel('accumulated metric' , fontsize = fontsiz)
plt.title('accumulated metric over iteration' ,fontsize = fontsiz)
plt.tick_params(axis='both', labelsize=fontsiz)
#plt.legend(ncol = 2 , fontsize = 12)
#plt.legend(loc='upper center', bbox_to_anchor=(0, 1. + 0.075 ,1-0.05,0.1), ncol = 2 , fontsize = fontsiz)
plt.legend( fontsize = fontsiz)
fig.tight_layout()
<jupyter_output><empty_output>
|
no_license
|
/jupyters/online_models_example.ipynb
|
yejihan-dev/fm-for-online-recommendation
| 5 |
<jupyter_start><jupyter_text>### 运行一次来获得cookie
- 注意填充自己的帐号密码<jupyter_code>import requests
import time
from selenium import webdriver
def get_pixiv_cookie(pixiv_id,pixiv_pw):
driver = webdriver.Chrome() # Optional argument, if not specified will search pat
driver.get('https://accounts.pixiv.net/login');
time.sleep(0.5)
account = driver.find_element_by_css_selector('input[autocomplete="username"]')
account.send_keys(pixiv_id)
time.sleep(10)
password = driver.find_element_by_css_selector('input[autocomplete="current-password"]')
password.send_keys(pixiv_pw)
time.sleep(1)
password.submit()
time.sleep(10)
cookie=driver.get_cookies()
driver.close()
return cookie
f=open("account.txt")
p_id = f.readline().rstrip()
p_pw = f.readline().rstrip()
f.close()
cookies_list=get_pixiv_cookie(p_id,p_pw)
f=open("cookie.txt","w")
f.write(str(cookies_list))
f.close()<jupyter_output><empty_output><jupyter_text>### 下面的直接运行可以就可以根据id爬图了- 从保存的文件获取cookie<jupyter_code>f=open("cookie.txt","r")
cookie_list=eval(f.readline())
f.close()
s = requests.Session()
for cookie in cookie_list:
s.cookies.set(cookie['name'], cookie['value'])<jupyter_output><empty_output><jupyter_text>- 获取预载信息<jupyter_code>pid='86685722'
delay=0.5
url="https://www.pixiv.net/artworks/"+pid
hder1={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36 Edg/84.0.522.63',
}
r=s.get(url,headers=hder1)
soup=BeautifulSoup(r.text, 'html.parser')
meta=soup.find('meta',id="meta-preload-data")# 格式化后可清晰看到这里是预载信息
js=json.loads(meta['content'])
# print(json.dumps(js,indent=2))<jupyter_output><empty_output><jupyter_text>使用`print(soup.prettify())`打印输出之后,可以清楚的发现预载信息在一个叫`meta-preload-data`的`meta`中
之后将内容提取之后也格式化
这是json文件,使用`json.dumps(js,indent=2)`进行格式化输出

js本身是列表,通过列表的形式获取需要的信息,这里需要的主要是url和页数信息- 获取图片<jupyter_code>def get_image(_url,_hder,_filename=None,_folder='img'):
if _filename==None:
img_path=urllib.parse.urlparse(_url).path
_filename=img_path.split('/')[-1]#路径的最后一项是文件名
f=open(_folder+'/'+_filename,"wb")
re=requests.get(_url,headers=_hder)
f.write(re.content)
f.close()
hder2 = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36 Edg/84.0.522.63',
"referer":"https://www.pixiv.net/"
}
ori=js["illust"][pid]['urls']['original']
pagecount=js['illust'][pid]['pageCount']
for i in range(pagecount):
url=ori.replace("p0","p"+str(i))
# print(url)
get_image(url,hder2)
time.sleep(delay)<jupyter_output><empty_output><jupyter_text>这里注意只有`pixiv.net`发出的原图请求`pximg.net`才会受理,这个需要在原图界面观察Network后筛选得到
### 整合了以上代码<jupyter_code>import requests
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
from PIL import Image
import sys
import time
import json
def get_image(_url,_hder,_filename=None,_folder='img'):
if _filename==None:
img_path=urllib.parse.urlparse(_url).path
_filename=img_path.split('/')[-1]#路径的最后一项是文件名
f=open(_folder+'/'+_filename,"wb")
re=requests.get(_url,headers=_hder)
f.write(re.content)
f.close()
def download_id(pid):
f=open("cookie.txt","r")
cookie_list=eval(f.readline())
f.close()
s = requests.Session()
for cookie in cookie_list:
s.cookies.set(cookie['name'], cookie['value'])
if(type(pid)==int):
pid=str(pid)
delay=0.5
url="https://www.pixiv.net/artworks/"+pid
hder1={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36 Edg/84.0.522.63',
}
r=s.get(url,headers=hder1)
soup=BeautifulSoup(r.text, 'html.parser')
meta=soup.find('meta',id="meta-preload-data")
js=json.loads(meta['content'])
hder2 = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36 Edg/84.0.522.63',
"referer":"https://www.pixiv.net/"
}
ori=js["illust"][pid]['urls']['original']
pagecount=js['illust'][pid]['pageCount']
for i in range(pagecount):
url=ori.replace("p0","p"+str(i))
get_image(url,hder2)
time.sleep(delay)
download_id(90479236)<jupyter_output><empty_output><jupyter_text>### 尝试通过作者爬取作品id<jupyter_code>author_id='27691'
url='https://www.pixiv.net/ajax/user/'+author_id+'/profile/all'
hder={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36 Edg/84.0.522.63',
}
js=json.loads(s.get(url,headers=hder).text)
print(js["body"]["illusts"].keys())<jupyter_output><empty_output><jupyter_text>首先通过
```
url='https://www.pixiv.net/users/'+author_id+'/artworks'
soup=BeautifulSoup(s.get(url,headers=hder).text)
print(soup.prettify())
```
直接爬取该页面信息,但是分析后发现没有id信息,然后打开浏览器加载这个页面,在Network下的XHR里可以找到传来id信息的页面,是https://www.pixiv.net/ajax/user/27691/profile/all 
直接点击可以访问,说明不需要cookie,只需要浏览器UA即可.
得到所有插画的id就等同于得到所有图片了<jupyter_code>for id in list(js["body"]["illusts"].keys()):
download_id(id)<jupyter_output><empty_output>
|
no_license
|
/pixiv.ipynb
|
Unknown-Chinese-User/pixiv-spider
| 7 |
<jupyter_start><jupyter_text>**This notebook is an exercise in the [Intro to Deep Learning](https://www.kaggle.com/learn/intro-to-deep-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/ryanholbrook/deep-neural-networks).**
---
# Introduction #
In the tutorial, we saw how to build deep neural networks by stacking layers inside a `Sequential` model. By adding an *activation function* after the hidden layers, we gave the network the ability to learn more complex (non-linear) relationships in the data.
In these exercises, you'll build a neural network with several hidden layers and then explore some activation functions beyond ReLU. Run this next cell to set everything up!<jupyter_code>import tensorflow as tf
# Setup plotting
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
# Set Matplotlib defaults
plt.rc('figure', autolayout=True)
plt.rc('axes', labelweight='bold', labelsize='large',
titleweight='bold', titlesize=18, titlepad=10)
# Setup feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.deep_learning_intro.ex2 import *<jupyter_output><empty_output><jupyter_text>In the *Concrete* dataset, your task is to predict the compressive strength of concrete manufactured according to various recipes.
Run the next code cell without changes to load the dataset.<jupyter_code>import pandas as pd
concrete = pd.read_csv('../input/dl-course-data/concrete.csv')
concrete.head()<jupyter_output><empty_output><jupyter_text># 1) Input Shape #
The target for this task is the column `'CompressiveStrength'`. The remaining columns are the features we'll use as inputs.
What would be the input shape for this dataset?<jupyter_code>concrete.shape
# YOUR CODE HERE
input_shape = [8]
# Check your answer
q_1.check()
# Lines below will give you a hint or solution code
#q_1.hint()
#q_1.solution()<jupyter_output><empty_output><jupyter_text># 2) Define a Model with Hidden Layers #
Now create a model with three hidden layers, each having 512 units and the ReLU activation. Be sure to include an output layer of one unit and no activation, and also `input_shape` as an argument to the first layer.<jupyter_code>from tensorflow import keras
from tensorflow.keras import layers
# YOUR CODE HERE
model = keras.Sequential([
layers.Dense(units= 512, activation= 'relu',input_shape= [8]),
layers.Dense(units= 512, activation= 'relu'),
layers.Dense(units= 512, activation= 'relu'),
layers.Dense(units= 1)
])
# Check your answer
q_2.check()
# Lines below will give you a hint or solution code
#q_2.hint()
#q_2.solution()<jupyter_output><empty_output><jupyter_text># 3) Activation Layers #
Let's explore activations functions some.
The usual way of attaching an activation function to a `Dense` layer is to include it as part of the definition with the `activation` argument. Sometimes though you'll want to put some other layer between the `Dense` layer and its activation function. (We'll see an example of this in Lesson 5 with *batch normalization*.) In this case, we can define the activation in its own `Activation` layer, like so:
```
layers.Dense(units=8),
layers.Activation('relu')
```
This is completely equivalent to the ordinary way: `layers.Dense(units=8, activation='relu')`.
Rewrite the following model so that each activation is in its own `Activation` layer.<jupyter_code>### YOUR CODE HERE: rewrite this to use activation layers
model = keras.Sequential([
layers.Dense(32, activation='relu', input_shape=[8]),
layers.Dense(32, activation='relu'),
layers.Dense(1),
])
model = keras.Sequential([
layers.Dense(units= 32, input_shape=[8]),
layers.Activation('relu'),
layers.Dense(units= 32),
layers.Activation('relu'),
layers.Dense(units= 1),
])
# Check your answer
q_3.check()
# Lines below will give you a hint or solution code
#q_3.hint()
#q_3.solution()<jupyter_output><empty_output><jupyter_text># Optional: Alternatives to ReLU #
There is a whole family of variants of the `'relu'` activation -- `'elu'`, `'selu'`, and `'swish'`, among others -- all of which you can use in Keras. Sometimes one activation will perform better than another on a given task, so you could consider experimenting with activations as you develop a model. The ReLU activation tends to do well on most problems, so it's a good one to start with.
Let's look at the graphs of some of these. Change the activation from `'relu'` to one of the others named above. Then run the cell to see the graph. (Check out the [documentation](https://www.tensorflow.org/api_docs/python/tf/keras/activations) for more ideas.)<jupyter_code># YOUR CODE HERE: Change 'relu' to 'elu', 'selu', 'swish'... or something else
activation_layer = layers.Activation('swish')
x = tf.linspace(-3.0, 3.0, 100)
y = activation_layer(x) # once created, a layer is callable just like a function
plt.figure(dpi=100)
plt.plot(x, y)
plt.xlim(-3, 3)
plt.xlabel("Input")
plt.ylabel("Output")
plt.show()<jupyter_output><empty_output>
|
no_license
|
/Intro to Deep Learning/2 - Deep Neural Networks/exercise-deep-neural-networks.ipynb
|
mtamjidhossain/Kaggle-courses
| 6 |
<jupyter_start><jupyter_text># Answering Questions for the Chinook Record StoreThe Chinook record store has just signed a deal with a new record label, and you've been tasked with selecting the first three albums that will be added to the store, from a list of four. All four albums are by artists that don't have any tracks in the store right now - we have the artist names, and the genre of music they produce:
Artist Name - Genre
- Regal - Hip-Hop
- Red Tone - Punk
- Meteor and the Girls - Pop
- Slim Jim Bites - Blues
The record label specializes in artists from the USA, and they have given Chinook some money to advertise the new albums in the USA, so we're interested in finding out which genres sell the best in the USA.<jupyter_code>%%capture
%load_ext sql
%sql sqlite:///chinook.db<jupyter_output><empty_output><jupyter_text># Overview of the Data
Query the database to get a list of all tables and views in our database:<jupyter_code>%%sql
SELECT
name,
type
FROM sqlite_master
WHERE type IN ("table","view");<jupyter_output>Done.
<jupyter_text># Selecting Albums to PurchaseWrite a query that returns each genre, with the number of tracks sold in the USA:
- in absolute numbers
- in percentages<jupyter_code>%%sql
SELECT il.* FROM invoice_line il
INNER JOIN invoice i ON i.invoice_id = il.invoice_id
INNER JOIN customer c on c.customer_id = i.customer_id
WHERE c.country = 'USA'
LIMIT 10;
%%sql
WITH usa_sold AS(SELECT il.* FROM invoice_line il
INNER JOIN invoice i ON i.invoice_id = il.invoice_id
INNER JOIN customer c on c.customer_id = i.customer_id
WHERE c.country = 'USA'
)
SELECT g.name genre,
count(us.invoice_line_id) tracks_sold
FROM usa_sold us
INNER JOIN track t ON t.track_id = us.track_id
INNER JOIN genre g ON g.genre_id = t.genre_id
GROUP BY 1
ORDER BY 2;
%%sql
WITH usa_sold AS(SELECT il.* FROM invoice_line il
INNER JOIN invoice i ON i.invoice_id = il.invoice_id
INNER JOIN customer c on c.customer_id = i.customer_id
WHERE c.country = 'USA'
)
SELECT g.name genre,
count(us.invoice_line_id) tracks_sold,
cast(count(us.invoice_line_id) AS FLOAT) / (
SELECT COUNT(*) from usa_sold
) percentage_sold
FROM usa_sold us
INNER JOIN track t ON t.track_id = us.track_id
INNER JOIN genre g ON g.genre_id = t.genre_id
GROUP BY 1
ORDER BY 2 DESC
LIMIT 10;
<jupyter_output>Done.
<jupyter_text>Based on the table above and the four options mentioned at the beginning, the albums to choose would be from should be:
- Red Tone - Punk
- Slim Jim Bites - Blues
- Meteor and the Girls - Pop<jupyter_code>%%sql
WITH usa_sold AS(SELECT il.* FROM invoice_line il
INNER JOIN invoice i ON i.invoice_id = il.invoice_id
INNER JOIN customer c on c.customer_id = i.customer_id
WHERE c.country = 'USA'
)
SELECT DISTINCT t.composer artist_name,
g.name genre,
count(us.invoice_line_id) tracks_sold,
cast(count(us.invoice_line_id) AS FLOAT) / (
SELECT COUNT(*) from usa_sold
) percentage_sold
FROM usa_sold us
INNER JOIN track t ON t.track_id = us.track_id
INNER JOIN genre g ON g.genre_id = t.genre_id
WHERE g.name = 'Rock'
GROUP BY 1
ORDER BY 3 DESC
LIMIT 5;
<jupyter_output>Done.
<jupyter_text>Rock, Alternative & Punk, and Metal have the most tracks sold. Adding more artists along the lines of The Rolling Stones and Nirvana would be beneficial after adding the three albums from above.# Analyzing Employee Sales PerformanceWrite a query that finds the total dollar amount of sales assigned to each sales support agent within the company. Add any extra attributes for that employee that you find are relevant to the analysis.<jupyter_code>%%sql
SELECT SUM(i.total) total_sales,
c.support_rep_id
FROM invoice i
INNER JOIN customer c ON c.customer_id = i.customer_id
GROUP BY 2<jupyter_output>Done.
<jupyter_text>There is data on three sales agents.<jupyter_code>%%sql
SELECT e.first_name ||' '|| e.last_name employee_name,
e.title
FROM employee e<jupyter_output>Done.
<jupyter_text>Confirming the three sales agents.<jupyter_code>%%sql
WITH total_sales_report AS
(
SELECT SUM(i.total) total,
c.support_rep_id
FROM invoice i
INNER JOIN customer c ON c.customer_id = i.customer_id
GROUP BY 2
)
SELECT e.first_name ||' '|| e.last_name employee_name,
e.hire_date,
SUM(tsr.total) total_sales
FROM total_sales_report tsr
INNER JOIN employee e ON e.employee_id = tsr.support_rep_id
GROUP BY 1;<jupyter_output>Done.
<jupyter_text>Steve started six months later, so that's why his numbers are a bit behind.# Analyzing Sales by Country<jupyter_code>%%sql
WITH country_or_other AS
(
SELECT
CASE
WHEN (
SELECT count(*)
FROM customer
where country = c.country
) = 1 THEN "Other"
ELSE c.country
END AS country,
c.customer_id,
il.*
FROM invoice_line il
INNER JOIN invoice i ON i.invoice_id = il.invoice_id
INNER JOIN customer c ON c.customer_id = i.customer_id
)
SELECT
country,
customers,
total_sales,
average_order,
customer_lifetime_value
FROM
(
SELECT
country,
count(distinct customer_id) customers,
SUM(unit_price) total_sales,
SUM(unit_price) / count(distinct customer_id) customer_lifetime_value,
SUM(unit_price) / count(distinct invoice_id) average_order,
CASE
WHEN country = "Other" THEN 1
ELSE 0
END AS sort
FROM country_or_other
GROUP BY country
ORDER BY sort ASC, total_sales DESC
);<jupyter_output>Done.
|
no_license
|
/chinook_store_sql.ipynb
|
EdsTyping/chinook_record_store_sql
| 8 |
<jupyter_start><jupyter_text>## Surrogate Models & Helper Functions<jupyter_code>ValueRange = namedtuple('ValueRange', ['min', 'max'])
def determinerange(values):
"""Determine the range of values in each dimension"""
return ValueRange(np.min(values, axis=0), np.max(values, axis=0))
def linearscaletransform(values, *, range_in=None, range_out=ValueRange(0, 1), scale_only=False):
"""Perform a scale transformation of `values`: [range_in] --> [range_out]"""
if range_in is None:
range_in = determinerange(values)
elif not isinstance(range_in, ValueRange):
range_in = ValueRange(*range_in)
if not isinstance(range_out, ValueRange):
range_out = ValueRange(*range_out)
scale_out = range_out.max - range_out.min
scale_in = range_in.max - range_in.min
if scale_only:
scaled_values = (values / scale_in) * scale_out
else:
scaled_values = (values - range_in.min) / scale_in
scaled_values = (scaled_values * scale_out) + range_out.min
return scaled_values
''' F16 '''
def F16(X):
f = bn.F16()
X = np.array(X)
return f(X)
''' Latin HyperCube Sampling Design of Experiment '''
def DOE(n_obs, dim):
np.random.seed(0)
lhd = pyDOE.lhs(n=dim, samples=n_obs, criterion='m')
X = [lhd[:,idx] for idx in range(dim)]
return X
def create_basis_function(data):
true = np.array(data['Y'])
data = pd.DataFrame(np.atleast_2d(PolynomialFeatures(degree=2).fit_transform(data.iloc[:,:-1])))
data['Y'] = pd.Series(true)
return data
''' Create Basis Functions '''
def create_function_basis(x):
return np.atleast_2d(PolynomialFeatures(degree=2).fit_transform(x.reshape(1,-1)))
''' Elastic Net Regression '''
def elastic_net(train_data,test_data):
scaler = MinMaxScaler().fit(np.r_[train_data.iloc[:,:-1].values])
regr = ElasticNet(alpha= 0.12 ,random_state=0 , l1_ratio=0.81, fit_intercept =True, max_iter=3000,selection='random').fit(scaler.transform ( np.array(train_data.iloc[:,:-1])) , np.array(train_data.iloc[:,-1]))
pred = regr.predict(scaler.transform(test_data))
def predict(scaler, regr):
def __predict__(x):
x = create_function_basis(x)
return regr.predict(scaler.transform(x))
return __predict__
return regr,pred, predict(scaler, regr)
''' Kriging'''
def kriging(train_data,test_data):
kernel = RBF()
scaler = MinMaxScaler().fit(np.r_[train_data.iloc[:,:-1].values])
gpr = GaussianProcessRegressor(kernel=kernel,n_restarts_optimizer= 15,random_state=0,
normalize_y=True ).fit(scaler.transform(train_data.iloc[:,:-1]), train_data.iloc[:,-1])
pred = gpr.predict(scaler.transform(test_data))
def predict(scaler, gpr):
def __predict__(x):
x = np.atleast_2d(x)
return gpr.predict(scaler.transform(x))
return __predict__
return gpr,pred, predict(scaler,gpr)
''' Support Vector Regression'''
def _SVR(train_data,test_data):
scaler = MinMaxScaler().fit(np.r_[train_data.iloc[:,:-1].values])
gpr = sklearn.svm.SVR(kernel='rbf', gamma = 37.213462 , C = 1000.000000 ,max_iter=1500).fit( scaler.transform(train_data.iloc[:,:-1]), train_data.iloc[:,-1])
pred = gpr.predict(scaler.transform(test_data))
def predict(scaler, gpr):
def __predict__(x):
x = np.atleast_2d(x)
return gpr.predict(scaler.transform(x))
return __predict__
return gpr,pred, predict(scaler,gpr)<jupyter_output><empty_output><jupyter_text>## Load Training and Test Data Set initially Generated<jupyter_code>path = "train_16_4000Samples.csv"
train = pd.read_csv(path).iloc[:,1:]
test = pd.read_csv('test_16_800Samples.csv').iloc[:,1:]
true = np.array(test['Y'])<jupyter_output><empty_output><jupyter_text>## Surrogate Models<jupyter_code>model_kri , pred_kri , predict_kri = kriging(train,test.iloc[:,:-1])
model_svr , pred_svr , predict_svr = _SVR(train,test.iloc[:,:-1])
train = create_basis_function(train)
test = create_basis_function(test)
model_eln , pred_eln , predict_eln = elastic_net(train,test.iloc[:,:-1])<jupyter_output>/usr/local/lib/python3.6/dist-packages/sklearn/svm/_base.py:231: ConvergenceWarning: Solver terminated early (max_iter=1500). Consider pre-processing your data with StandardScaler or MinMaxScaler.
% self.max_iter, ConvergenceWarning)
<jupyter_text>## CMA-ES<jupyter_code>Columns = ['Kri' , 'SVR' , 'ELN' ]
Cols = []
for j in range(len(Columns)):
for i in range(1,201):
Cols.append(Columns[j]+'_X'+str(i))
const = [ [-5] * 200, [5] * 200 ]
opt = cma.CMAOptions()
opt.set("bounds", const)
opt.set ("seed" , 0)
opt.set ("maxfevals" , 200000)
n_obs , dim = 30, 200
G = DOE(n_obs, dim)
G = [ linearscaletransform(G[idx] , range_out=(-5,5)) for idx in range(dim) ]
G = [ G[idx].reshape(n_obs,1) for idx in range(len(G)) ]
X_Values = np.zeros([10,600])
for i in range(10, 20):
print ('Run : '+ str(i))
min_kri = cma.fmin(predict_kri , np.concatenate(G, 1)[i] , 2.5 , options=opt) [0]
min_svr = cma.fmin(predict_svr , np.concatenate(G, 1)[i] , 2.5 , options=opt) [0]
min_eln = cma.fmin(predict_eln , np.concatenate(G, 1)[i] , 2.5 , options=opt) [0]
X_Values [i-10,:] = list(min_kri)+list(min_svr)+list(min_eln)
X_Values = pd.DataFrame(X_Values)
X_Values.columns = Cols
X_Values.to_csv('sample_data\\F16_X_Values_first.csv')
Krig_Fun = np.zeros(10)
SVM_Fun = np.zeros(10)
ELN_Fun = np.zeros(10)
for i in range(X_Values.shape[0]):
Krig_Fun [i] = F16(X_Values.iloc[i,:200])
SVM_Fun [i] = F16(X_Values.iloc[i,200:400])
ELN_Fun [i] = F16(X_Values.iloc[i,400:600])
print ('Kriging')
print (stats.mode(Krig_Fun) , np.std(Krig_Fun))
print ('SVM')
print (stats.mode(SVM_Fun) , np.std(SVM_Fun))
print ('ELN')
print (stats.mode(ELN_Fun) , np.std(ELN_Fun))
<jupyter_output><empty_output>
|
no_license
|
/Original - Optimality/200D/second/F16_200_original.ipynb
|
SibghatUllah13/Deep-Latent_Variable_Models-for-dimensionality-reduction-in-surrogate-assisted-optimization
| 4 |
<jupyter_start><jupyter_text>## Download rnn_merged.zip & rnn_embed.zip from https://drive.google.com/drive/folders/1yO_W-m0fF_PludrnScdgyTGsPFoDsA6_?usp=sharing and unzip to the same folder of this file
## Also download train_jpg.zip & test_jpg.zip from competition website<jupyter_code>import pandas as pd
import tensorflow as tf
from keras.preprocessing import text, sequence
import numpy as np
from keras.layers import Input, SpatialDropout1D,Dropout, GlobalAveragePooling1D, GlobalMaxPooling1D, \
CuDNNGRU, GRU, Bidirectional, LSTM, Dense, Embedding, concatenate, Embedding, \
Flatten, Activation, BatchNormalization, regularizers, Conv1D, Conv2D, MaxPooling2D
from keras.constraints import max_norm
from keras.initializers import Orthogonal
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LambdaCallback, Callback, LearningRateScheduler
import keras.backend as K
import numpy as np
from sklearn import metrics
from sklearn.model_selection import train_test_split
import os
import pickle
import gc; gc.enable()
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
import string
import nltk
from nltk.corpus import stopwords
from nltk.stem.snowball import RussianStemmer
from scipy.stats import boxcox
import re
#from tqdm import tqdm<jupyter_output>E:\Anaconda3\envs\tensorflow\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
Using TensorFlow backend.
<jupyter_text>### Check GPU Availability<jupyter_code>sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
K.tensorflow_backend._get_available_gpus()<jupyter_output>[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 339512226104842527
, name: "/device:GPU:0"
device_type: "GPU"
memory_limit: 3174131302
locality {
bus_id: 1
links {
}
}
incarnation: 17746058336949755705
physical_device_desc: "device: 0, name: GeForce GTX 1050 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1"
]
<jupyter_text>### Preprocess Training and Testing Data<jupyter_code>seed = 411
rnn_train_epochs = 10
batch_size=128 # 32 or 64 is good (too huge for my PC), 128 is worse in the past experiments
cpu_count=4
features = pickle.load(open('rnn_merged.pkl', 'rb'))
features.keys()
train = features['train']
test = features['test']
renamed_cols = []
count = 0
for col in train.columns:
if 'cat_features_user_id_category_name' in col:
col = 'cat_features_user_id_category_name_'+str(count)
count += 1
renamed_cols.append(col)
train.columns = renamed_cols
test.columns = renamed_cols
train_len = train.shape[0]
train_y = features['y_train']
categorical = features['categorical']
numerical = [f for f in train.columns if f not in categorical]
features = numerical + categorical
train.columns.tolist()
# remove features: text, image, other embeddings\feature engineerings
remove_cols = [
'cat_features_user_id_category_name_0',
'cat_features_user_id_category_name_1',
'cat_features_user_id_category_name_2',
'cat_features_user_id_category_name_3',
'cat_features_user_id_category_name_4',
'cat_features_user_id_category_name_5',
'cat_features_user_id_category_name_6',
'cat_features_user_id_category_name_7',
'cat_features_user_id_category_name_8',
'cat_features_user_id_category_name_9',
'cat_features_user_id_category_name_10',
'cat_features_user_id_category_name_11',
'cat_features_user_id_category_name_12',
'cat_features_user_id_category_name_13',
'cat_features_user_id_category_name_14',
'cat_features_user_id_category_name_15',
'cat_features_user_id_category_name_16',
'cat_features_user_id_category_name_17',
'cat_features_user_id_category_name_18',
'cat_features_user_id_category_name_19',
'cat_features_user_id_category_name_20',
'cat_features_user_id_category_name_21',
'cat_features_user_id_category_name_22',
'cat_features_user_id_category_name_23',
'cat_features_user_id_category_name_24',
'cat_features_user_id_category_name_25',
'cat_features_user_id_category_name_26',
'cat_features_user_id_category_name_27',
'cat_features_user_id_category_name_28',
'cat_features_user_id_category_name_29',
'cat_features_user_id_category_name_30',
'cat_features_user_id_category_name_31',
'cat_features_user_id_category_name_32',
'cat_features_user_id_category_name_33',
'cat_features_user_id_category_name_34',
'cat_features_user_id_category_name_35',
'cat_features_user_id_category_name_36',
'cat_features_user_id_category_name_37',
'cat_features_user_id_category_name_38',
'cat_features_user_id_category_name_39',
'cat_features_user_id_category_name_40',
'cat_features_user_id_category_name_41',
'cat_features_user_id_category_name_42',
'cat_features_user_id_category_name_43',
'cat_features_user_id_category_name_44',
'cat_features_user_id_category_name_45',
'cat_features_user_id_category_name_46',
'title_tfidf_svd_1',
'title_tfidf_svd_2',
'title_tfidf_svd_3',
'title_tfidf_svd_4',
'title_tfidf_svd_5',
'description_tfidf_svd_1',
'description_tfidf_svd_2',
'description_tfidf_svd_3',
'description_tfidf_svd_4',
'description_tfidf_svd_5',
'region_mean_price',
'region_mean_image_top_1',
'region_mean_item_seq_number',
'region_mean_price_pred',
'region_mean_price_pred_all',
'region_mean_ridge_preds',
'city_mean_price',
'city_mean_image_top_1',
'city_mean_item_seq_number',
'city_mean_price_pred',
'city_mean_price_pred_all',
'city_mean_ridge_preds',
'parent_category_name_mean_price',
'parent_category_name_mean_image_top_1',
'parent_category_name_mean_item_seq_number',
'parent_category_name_mean_price_pred',
'parent_category_name_mean_price_pred_all',
'parent_category_name_mean_ridge_preds',
'category_name_mean_price',
'category_name_mean_image_top_1',
'category_name_mean_item_seq_number',
'category_name_mean_price_pred',
'category_name_mean_price_pred_all',
'category_name_mean_ridge_preds',
'user_type_mean_price',
'user_type_mean_image_top_1',
'user_type_mean_item_seq_number',
'user_type_mean_price_pred',
'user_type_mean_price_pred_all',
'user_type_mean_ridge_preds',
'param_1_mean_price',
'param_1_mean_image_top_1',
'param_1_mean_item_seq_number',
'param_1_mean_price_pred',
'param_1_mean_price_pred_all',
'param_1_mean_ridge_preds',
'param_2_mean_price',
'param_2_mean_image_top_1',
'param_2_mean_item_seq_number',
'param_2_mean_price_pred',
'param_2_mean_price_pred_all',
'param_2_mean_ridge_preds',
'param_3_mean_price',
'param_3_mean_image_top_1',
'param_3_mean_item_seq_number',
'param_3_mean_price_pred',
'param_3_mean_price_pred_all',
'param_3_mean_ridge_preds',
'user_id_nunique_parent_category_name',
'user_id_nunique_category_name',
'user_id_nunique_param_1',
'user_id_nunique_param_2',
'user_id_nunique_param_3',
'user_id_nunique_activation_date',
'user_id_activation_date_count_item_id',
'image_top_1_nunique_item_id',
'image_top_1_nunique_user_id',
'image_top_1_nunique_category_name',
'image_top_1_nunique_param_1',
'image_top_1_nunique_item_seq_number',
'image_top_1_mean_price_pred',
'image_top_1_std_price_pred',
'image_top_1_mean_item_seq_number',
'user_id_mean_ridge_preds',
'user_id_category_name_mean_ridge_preds',
'user_id_image_top_1_mean_ridge_preds',
'user_id_category_name_sum_ridge_preds',
'cityxcatxusertypeitem_num',
'cityxcatxusertypecity_fm_factor_0',
'cityxcatxusertypecity_fm_factor_1',
'cityxcatxusertypecategory_name_fm_factor_0',
'cityxcatxusertypecategory_name_fm_factor_1',
'cityxcatxusertypeuser_type_fm_factor_0',
'cityxcatxusertypeuser_type_fm_factor_1',
'cityxcatxusertypecity_fm_bias',
'cityxcatxusertypecategory_name_fm_bias',
'cityxcatxusertypeuser_type_fm_bias',
'imgxcityxcatitem_num',
'imgxcityxcatimage_top_1_fm_factor_0',
'imgxcityxcatimage_top_1_fm_factor_1',
'imgxcityxcatcity_fm_factor_0',
'imgxcityxcatcity_fm_factor_1',
'imgxcityxcatcategory_name_fm_factor_0',
'imgxcityxcatcategory_name_fm_factor_1',
'imgxcityxcatimage_top_1_fm_bias',
'imgxcityxcatcity_fm_bias',
'imgxcityxcatcategory_name_fm_bias',
'imgxisqnxusertypeitem_num',
'imgxisqnxusertypeimage_top_1_fm_factor_0',
'imgxisqnxusertypeimage_top_1_fm_factor_1',
'imgxisqnxusertypeitem_seq_number_fm_factor_0',
'imgxisqnxusertypeitem_seq_number_fm_factor_1',
'imgxisqnxusertypeuser_type_fm_factor_0',
'imgxisqnxusertypeimage_top_1_fm_bias',
'imgxisqnxusertypeitem_seq_number_fm_bias',
'b_intensity_mean',
'b_intensity_median',
'b_intensity_std',
'g_intensity_mean',
'g_intensity_median',
'g_intensity_std',
'gray_intensity_mean',
'gray_intensity_median',
'gray_intensity_std',
'r_intensity_mean',
'r_intensity_median',
'r_intensity_std',
'nasnet_nima_med',
'nasnet_nima_std',
'nasnet_nima_max',
'nasnet_nima_min',
'nasnet_nima_1_quartile',
'nasnet_nima_3_quartile',
'nasnet_nima_13_quartile_diff',
'nasnet_nima_max_min_diff',
'nasnet_nima_non_max_mean',
'nasnet_nima_max_non_max_mean_diff',
]
train.drop(remove_cols, axis=1, inplace=True)
test.drop(remove_cols, axis=1, inplace=True)
for col in remove_cols:
if col in categorical:
categorical.remove(col)
if col in numerical:
numerical.remove(col)
features = numerical + categorical
train.loc[:, 'image'] = pd.read_csv('train.csv', usecols=['activation_date', 'image'], parse_dates=['activation_date']) \
.sort_values('activation_date').reset_index(drop=True)['image'].fillna('no-image')
test.loc[:, 'image'] = pd.read_csv('test.csv', usecols=['image'])['image'].fillna('no-image')
max_features = 500000
maxlen = 150
embed_size = 300
title_max_features = 200000
title_maxlen = 80
title_embed_size = 100
embed_info = pickle.load(open('rnn_embed.pkl', 'rb'))
embed_info.keys()
desc_embed_info = embed_info['desc_embed_info']
title_embed_info = embed_info['title_embed_info']
print('setup max info for embedding in categorical variables')
max_info = dict((col, train[col].max()+1) for col in categorical)<jupyter_output>setup max info for embedding in categorical variables
<jupyter_text>### Build RNN Model<jupyter_code>def root_mean_squared_error(y_true, y_pred):
return K.sqrt(K.mean(K.square(y_true - y_pred)))
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints
class Attention(Layer):
def __init__(self, step_dim,
W_regularizer=None, b_regularizer=None,
W_constraint=None, b_constraint=None,
bias=True, **kwargs):
self.supports_masking = True
self.init = initializers.get('glorot_uniform')
self.W_regularizer = regularizers.get(W_regularizer)
self.b_regularizer = regularizers.get(b_regularizer)
self.W_constraint = constraints.get(W_constraint)
self.b_constraint = constraints.get(b_constraint)
self.bias = bias
self.step_dim = step_dim
self.features_dim = 0
super(Attention, self).__init__(**kwargs)
def build(self, input_shape):
print(input_shape)
assert len(input_shape) == 3
self.W = self.add_weight((input_shape[-1],),
initializer=self.init,
name='{}_W'.format(self.name),
regularizer=self.W_regularizer,
constraint=self.W_constraint)
self.features_dim = input_shape[-1]
if self.bias:
self.b = self.add_weight((input_shape[1],),
initializer='zero',
name='{}_b'.format(self.name),
regularizer=self.b_regularizer,
constraint=self.b_constraint)
else:
self.b = None
self.built = True
def compute_mask(self, input, input_mask=None):
return None
def call(self, x, mask=None):
features_dim = self.features_dim
step_dim = self.step_dim
eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),
K.reshape(self.W, (features_dim, 1))), (-1, step_dim))
if self.bias:
eij += self.b
eij = K.tanh(eij)
a = K.exp(eij)
if mask is not None:
a *= K.cast(mask, K.floatx())
a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())
a = K.expand_dims(a)
weighted_input = x * a
return K.sum(weighted_input, axis=1)
def compute_output_shape(self, input_shape):
return input_shape[0], self.features_dim
def clip_rmse(true, prediction):
return np.sqrt(metrics.mean_squared_error(true, np.clip(prediction, 0., 1.)))
class NBatchEvalLogger(Callback):
def __init__(self, display, val_X, val_y, save_path=None, save_start=1000):
self.step = 0
self.display = display
self.val_X = val_X
self.val_y = val_y
self.best_loss = None
self.save_path = save_path
self.save_start = save_start
self.record_count = 0
def on_batch_end(self, batch, logs={}):
self.step += 1
if self.step % self.display == 0 and self.step >= self.save_start:
#loss, metric = self.model.evaluate(self.val_X, self.val_y, batch_size=128, verbose=1)
prediction = self.model.predict(self.val_X, batch_size=128, verbose=0)
loss = clip_rmse(self.val_y, prediction)
if self.best_loss is None:
self.best_loss = loss
else:
if loss < self.best_loss:
self.best_loss = loss
if self.save_path is not None:
self.model.save(self.save_path, overwrite=True)
self.record_count += 1
print('\rstep: {} val loss={:.5f}, best loss={:.5f}'.format(self.step, loss, self.best_loss))
import keras
from copy import deepcopy as cp
import os
from zipfile import ZipFile
import cv2
import numpy as np
import pandas as pd
from dask import bag, threaded
from dask.diagnostics import ProgressBar
import matplotlib.pyplot as plt
from keras.preprocessing.image import load_img, img_to_array
from keras.applications.resnet50 import preprocess_input
import concurrent.futures
from multiprocessing.pool import ThreadPool
class DataGenerator(keras.utils.Sequence):
#'Generates data for Keras'
def __init__(self, list_IDs, X, y, img_arch, img_path, batch_size=32, shuffle=True, is_train=True):
#'Initialization'
self.batch_size = batch_size
self.X = X
self.y = y
self.list_IDs = list_IDs
self.shuffle = shuffle
self.img_path = img_path
self.is_train = is_train
self.on_epoch_end()
self.zipped = ZipFile(img_arch)
#print('file names:\n', self.zipped.namelist()[1:10], '\n...')
self.img_path = img_path
global cpu_count
self.pool = ThreadPool(cpu_count)
def __getstate__(self):
""" This is called before pickling. """
state = self.__dict__.copy()
del state['zipped']
return state
def __setstate__(self, state):
""" This is called while unpickling. """
self.__dict__.update(state)
def __len__(self):
#'Denotes the number of batches per epoch'
return int(np.ceil(len(self.list_IDs) / self.batch_size))
def __getitem__(self, index):
#'Generate one batch of data'
# Generate indexes of the batch
start = index*self.batch_size
end = min((index+1)*self.batch_size, len(self.indexes))
indexes = self.indexes[start: end]
# Generate data
return self.__data_generation(indexes)
def on_epoch_end(self):
#'Updates indexes after each epoch'
self.indexes = cp(list(self.list_IDs))
if self.shuffle == True:
np.random.shuffle(self.indexes)
def load_img_from_zipped(self, img_id, i, imgs_holder):
invalid_img_ids = ['4f029e2a00e892aa2cac27d98b52ef8b13d91471f613c8d3c38e3f29d4da0b0c',
'8513a91e55670c709069b5f85e12a59095b802877715903abef16b7a6f306e58',
'60d310a42e87cdf799afcd89dc1b11ae3fdc3d0233747ec7ef78d82c87002e83',
'b98b291bd04c3d92165ca515e00468fd9756af9a8f1df42505deed1dcfb5d7ae']
try:
if img_id in invalid_img_ids or img_id == 'no-image':
pass
else:
exfile = self.zipped.read(self.img_path+img_id+'.jpg')
arr = np.frombuffer(exfile, np.uint8)
imz = cv2.imdecode(arr, flags=cv2.IMREAD_UNCHANGED)
imz = cv2.resize(imz, (224,224), interpolation=cv2.INTER_AREA)
imgs_holder[i] = img_to_array(imz)
except:
print(img_id, ' is invalid')
pass
return None
def parallel_load_imgs(self, img_ids, wait=True):
imgs_holder = np.zeros((len(img_ids), 224, 224, 3))
'''
for i, im_id in enumerate(img_ids):
self.load_img_from_zipped(im_id, i, imgs_holder)
'''
self.res = [self.pool.apply_async(self.load_img_from_zipped, (im_id, i, imgs_holder)) for i, im_id in enumerate(img_ids)]
if wait:
for r in self.res:
r.get()
#print(imgs_holder)
imgs_holder = preprocess_input(imgs_holder) # adjust to mean of rgb to some value
return imgs_holder
def __data_generation(self, list_IDs_temp):
#'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
# Generate data
X = dict((col, self.X.loc[list_IDs_temp, col].values) for col in features)
X['desc'] = desc_embed_info['text'][list_IDs_temp,:]
X['title'] = title_embed_info['text'][list_IDs_temp,:]
X['imgs'] = self.parallel_load_imgs(self.X.loc[list_IDs_temp, 'image'].values)
if self.is_train:
y = cp(self.y[list_IDs_temp])
return X, y
else:
return X
# 'train_jpg.zip', 'data/competition_files/train_jpg/',
# debug use
'''
zipped = ZipFile('train_jpg.zip')
print(zipped.namelist()[1:10])
img_id = '2809fd6afd6d3cae4dd4ad93a7f905a0db32292f4df4b3f19fa5492e08cbfd90'
target_size=(224,224)
try:
exfile = zipped.read('data/competition_files/train_jpg/'+img_id+'.jpg')
arr = np.frombuffer(exfile, np.uint8)
imz = cv2.imdecode(arr, flags=cv2.IMREAD_UNCHANGED)
imz = cv2.resize(imz, target_size, interpolation=cv2.INTER_AREA)
except:
print(img_id, ' is invalid')
imz = None
imz
'''
def build_model(categorical_features, numerical_features):
# non-cat features
non_cat_inputs = []
for col in numerical_features:
f = Input(shape=[1], name=col)
non_cat_inputs.append(f)
# cat features
cat_inputs = []
cat_embeds = []
for col in categorical_features:
f = Input(shape=[1], name=col)
embed_dim = max_info[col].max()
if max_info[col] > 10:
reduced_dim = 10
else:
reduced_dim = 1
embed_f = Embedding(embed_dim, reduced_dim)(f)
flatten_f = Flatten()(embed_f)
cat_inputs.append(f)
cat_embeds.append(flatten_f)
# text features: architecture of text to try here!!!
# description
text_inp = Input(shape = (maxlen, ), name='desc')
text_emb = Embedding(desc_embed_info['nb_words'], embed_size, weights = [desc_embed_info['emb_matrix']],
input_length = maxlen, trainable = False)(text_inp)
text_emb = SpatialDropout1D(0.3)(text_emb)
text_gru = Bidirectional(CuDNNGRU(128, return_sequences = True))(text_emb)
text_gru = Conv1D(64, kernel_size = 3, padding = "valid", kernel_initializer = "glorot_uniform")(text_gru)
text_gru_avg = GlobalAveragePooling1D()(text_gru)
text_gru_max = GlobalMaxPooling1D()(text_gru)
text_gru = concatenate([text_gru_avg, text_gru_max])
text_gru = Dropout(0.1)(text_gru)
# title
title_inp = Input(shape = (title_maxlen, ), name='title')
title_emb = Embedding(title_embed_info['nb_words'], title_embed_size, weights = [title_embed_info['emb_matrix']],
input_length = title_maxlen, trainable = False)(title_inp)
title_emb = SpatialDropout1D(0.1)(title_emb)
title_gru = Bidirectional(CuDNNGRU(32, return_sequences = True))(title_emb)
title_gru = Conv1D(16, kernel_size = 3, padding = "valid", kernel_initializer = "glorot_uniform")(title_gru)
title_gru_avg = GlobalAveragePooling1D()(title_gru)
title_gru_max = GlobalMaxPooling1D()(title_gru)
title_gru = concatenate([title_gru_avg, title_gru_max])
title_gru = Dropout(0.1)(title_gru)
# add image architecture
# reference: https://keras.io/getting-started/functional-api-guide/#more-examples, Visual question answering model
'''
img_inp = Input(shape = (224, 224, 3 ), name='imgs')
img_ch = Conv2D(64, (3, 3), activation='relu', padding='same', W_constraint=max_norm(3))(img_inp)
img_ch = Conv2D(64, (3, 3), activation='relu')(img_ch)
img_ch = MaxPooling2D((2, 2))(img_ch)
#img_ch = Conv2D(128, (3, 3), activation='relu', padding='same', W_constraint=max_norm(3))(img_ch)
#img_ch = Conv2D(128, (3, 3), activation='relu')(img_ch)
#img_ch = MaxPooling2D((2, 2))(img_ch)
#img_ch = Conv2D(256, (3, 3), activation='relu', padding='same', W_constraint=max_norm(3))(img_ch)
#img_ch = Conv2D(256, (3, 3), activation='relu')(img_ch)
#img_ch = Conv2D(256, (3, 3), activation='relu')(img_ch)
#img_ch = MaxPooling2D((2, 2))(img_ch)
img_ch = Flatten()(img_ch)
img_ch = Dense(64, activation='relu')(img_ch)
'''
# merge each branch: non-cat, cat, text, img
concat_main = non_cat_inputs+cat_embeds+[text_gru, title_gru]
main = concatenate(concat_main)
main = BatchNormalization()(main)
main = Dropout(0.1)(main)
main = BatchNormalization()(Dense(256, activation='relu')(main))
main = Dropout(0.1)(main)
main = BatchNormalization()(Dense(64, activation='relu')(main))
out = Dense(1, activation = "sigmoid")(main)
concat_input = non_cat_inputs+cat_inputs+[text_inp, title_inp]
model = Model(concat_input, out)
model.regularizers = [regularizers.l2(0.0001)]
model.compile(optimizer = Adam(lr=0.001), loss = root_mean_squared_error,
metrics =[root_mean_squared_error])
model.summary()
return model<jupyter_output><empty_output><jupyter_text>### Training<jupyter_code>from sklearn.model_selection import KFold
import warnings; warnings.filterwarnings('ignore')
train_indices = np.arange(0, train_len)
test_indices = np.arange(0, test.shape[0])
from keras_tqdm import TQDMNotebookCallback
from ipywidgets import IntProgress
start_fold = 0 # <= 0 for invalid, train from fold 1, > 0: used to train from fold=start_fold
resume_file_prefix = '0619_rnn' # whatever we like
if start_fold > 0:
import pickle
ret = pickle.load(open(resume_file_prefix+'_oof_val_pred', 'rb'))
ret_test = pickle.load(open(resume_file_prefix+'_oof_test_pred', 'rb'))
print(ret)
print(ret_test)
else:
ret = np.zeros((train.shape[0],))
ret_test = np.zeros((test.shape[0],))
fold = 0
for tr_ix, val_ix in KFold(5, shuffle=True, random_state=seed).split(train_indices):
fold += 1
if start_fold > 0 and fold < start_fold:
continue
else:
pass
model = build_model(categorical, numerical)
file_path = "rnn_weights/model_final_fold_{}.hdf5".format(fold)
# customized batch loader
training_generator = DataGenerator(tr_ix, train, train_y,
'train_jpg.zip', 'data/competition_files/train_jpg/',
batch_size=batch_size, shuffle=True)
validation_generator = DataGenerator(val_ix, train, train_y,
'train_jpg.zip', 'data/competition_files/train_jpg/',
batch_size=batch_size, shuffle=False)
lr_schd = LearningRateScheduler(lambda epoch: 0.001*(0.2**(epoch//6)), verbose=1)
check_point = ModelCheckpoint(file_path, monitor = "val_loss", mode = "min", save_best_only = True, verbose = 1)
history = model.fit_generator(generator=training_generator,
validation_data=validation_generator,
use_multiprocessing=False,
workers=1,
epochs=rnn_train_epochs,
verbose = 0,
callbacks = [lr_schd, check_point, TQDMNotebookCallback(leave_inner=True, leave_outer=True)])
# Predict val + test oofs
model.load_weights(file_path) # load weight with best validation score
del validation_generator
validation_generator = DataGenerator(val_ix, train, None,
'train_jpg.zip', 'data/competition_files/train_jpg/',
batch_size=batch_size, shuffle=False, is_train=False)
test_generator = DataGenerator(test_indices, test, None,
'test_jpg.zip', 'data/competition_files/test_jpg/',
batch_size=batch_size, shuffle=False, is_train=False)
ret[val_ix] = model.predict_generator(validation_generator, use_multiprocessing=False, workers=1).reshape((len(val_ix),))
ret_test += model.predict_generator(test_generator, use_multiprocessing=False, workers=1).reshape((ret_test.shape[0],))
del model, history, training_generator, validation_generator, test_generator; gc.collect()
ret_test /= 5
# uncomment these to dump files if OOM (out-of-mem) happens
import pickle
pickle.dump(ret, open(resume_file_prefix+'_oof_val_pred', 'wb'))
pickle.dump(ret_test, open(resume_file_prefix+'_oof_test_pred', 'wb'))
# public kernel: cv = .2220, lb = .2247
# bigru-conv1d: cv =.2185 , lb = .2235
# bigru-attention: cv =.2186 , lb = .2235
# 2gru: lb: .2239
# self-trained wordvec: cv .217232, lb: .2229
# +partial new features: cv .216326, lb: <jupyter_output><empty_output><jupyter_text>### Generate OOFs and Submissions<jupyter_code>prefix = 'selftrained_bigru_conv1d_merged'
pd.DataFrame(data=ret, columns=[prefix+'_rnn_pred']).to_csv(prefix+'_rnn_oof_val_pred.csv', index=False)
pd.DataFrame(data=ret_test, columns=[prefix+'_rnn_pred']).to_csv(prefix+'_rnn_oof_test_pred.csv', index=False)
subm = pd.read_csv('sample_submission.csv')
subm['deal_probability'] = np.clip(ret_test, 0, 1)
subm.to_csv(prefix+'_rnn_submission.csv', index=False)<jupyter_output><empty_output>
|
no_license
|
/RNN Self-Trained WordVec + Image + Merge Features (with Fast Loading)-Copy1.ipynb
|
tnmichael309/kaggle-avito-demand-challenge
| 6 |
<jupyter_start><jupyter_text># Consume deployed webservice via REST
Demonstrates the usage of a deployed model via plain REST.
REST is language-agnostic, so you should be able to query from any REST-capable programming language.## Configuration<jupyter_code>from environs import Env
env = Env()
env.read_env("foundation.env")
env.read_env("service-principals.env")
# image to test
IMAGE_TO_TEST = "mnist_fashion/04_consumption/random_test_images/random-test-image-1601.png"
# endpoint of the scoring webservice
SCORING_URI = "<...use your own..., eg. https://....westeurope.cloudapp.azure.com:443/api/v1/service/mnist-fashion-service/score>"
# auth method, either "Token", "Keys" or "None".
# also specify additional values depending on auth method
AUTH_METHOD = "Token"
if AUTH_METHOD == "Keys":
AUTH_KEY = "<add your key here>"
elif AUTH_METHOD == "Token":
REGION = "eastus"
SUBSCRIPTION_ID = env("SUBSCRIPTION_ID")
RESOURCE_GROUP = env("RESOURCE_GROUP")
WORKSPACE_NAME = env("WORKSPACE_NAME")
SERVICE_NAME = "mnist-fashion-service"
CONSUME_MODEL_SP_TENANT_ID = env("CONSUME_MODEL_SP_TENANT_ID")
CONSUME_MODEL_SP_CLIENT_ID = env("CONSUME_MODEL_SP_CLIENT_ID")
CONSUME_MODEL_SP_CLIENT_SECRET = env("CONSUME_MODEL_SP_CLIENT_SECRET")
elif AUTH_METHOD == "None":
pass<jupyter_output><empty_output><jupyter_text>## Load a random image and plot it<jupyter_code>import matplotlib.pyplot as plt
from PIL import Image
image = Image.open(IMAGE_TO_TEST)
plt.figure()
plt.imshow(image)
plt.colorbar()
plt.grid(False)
plt.show()<jupyter_output><empty_output><jupyter_text>## Invoke the webservice and show result<jupyter_code>import requests
import json
# --- get input data
input_data = open(IMAGE_TO_TEST, "rb").read()
# alternatively for JSON input
#input_data = json.dumps({"x": 4711})
# --- get headers
# Content-Type
# for binary data
headers = {"Content-Type": "application/octet-stream"}
# alternatively for JSON data
#headers = {"Content-Type": "application/json"}
# Authorization
if AUTH_METHOD == "Token":
# get an access token for the service principal to access Azure
azure_access_token = requests.post(
f"https://login.microsoftonline.com/{CONSUME_MODEL_SP_TENANT_ID}/oauth2/token",
headers={"Content-Type": "application/x-www-form-urlencoded"},
data="grant_type=client_credentials"
+ "&resource=https%3A%2F%2Fmanagement.azure.com%2F"
+ f"&client_id={CONSUME_MODEL_SP_CLIENT_ID}"
+ f"&client_secret={CONSUME_MODEL_SP_CLIENT_SECRET}",
).json()["access_token"]
# use that token to get another token for accessing the webservice
# note: the token is only valid for a certain period of time.
# after that time, a new token has to be used. the logic
# to do this, is not implemented here yet. you can check
# the current time against the refresh after time to know
# if a new token is required. refreshAfter and expiryOn
# are UNIX timestamps. use time.time() to get the current
# timestamp.
token_response = requests.post(
f"https://{REGION}.modelmanagement.azureml.net/modelmanagement/v1.0/subscriptions/{SUBSCRIPTION_ID}/resourceGroups/{RESOURCE_GROUP}/providers/Microsoft.MachineLearningServices/workspaces/{WORKSPACE_NAME}/services/{SERVICE_NAME}/token",
headers={"Authorization": f"Bearer {azure_access_token}"}
).json()
access_token = token_response["accessToken"]
access_token_refresh_after = int(token_response["refreshAfter"])
access_token_expiry_on = int(token_response["expiryOn"])
# finally, use that token to access the webservice
headers["Authorization"] = f"Bearer {access_token}"
if AUTH_METHOD == "Keys":
headers["Authorization"] = f"Bearer {AUTH_KEY}"
if AUTH_METHOD == "None":
# do nothing
pass
# --- make request and display response
response = requests.post(SCORING_URI, input_data, headers=headers, verify=True)
print(response.json())<jupyter_output>{'predicted_label': 'Bag', 'confidence': '1.0'}
|
permissive
|
/mnist_fashion/04_consumption/consume-webservice.ipynb
|
anderl80/aml-template
| 3 |
<jupyter_start><jupyter_text># Problem : Print all ancestors of binary tree.
Algorithm:
1. Check if root or node is None, if yes, return False
2. Append the ancestor list with the root
3. If the root equals node return True to the calling function
4. Check the left and right subtree for node recursively
5. If found return true else pop the node from the list and return False.\
Time Complexity: O(n)
Space Complexity: O(n^2)<jupyter_code>def findAllAncestors(root, node, ancestors):
if root is None or node is None:
return False
ancestors.append(root.getData())
if root.getData() == node:
return True
if (findAllAncestors(root.getLeft(), node, ancestors)
or findAllAncestors(root.getRight(), node, ancestors)):
return True
ancestors.pop()
return False
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def getData(self):
return self.data
def setData(self, data):
self.data = data
def getLeft(self):
return self.left
def getRight(self):
return self.right
def setLeft(self, left):
self.left = left
def setRight(self, right):
self.right = right
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
a.setLeft(b)
a.setRight(c)
d = TreeNode(4)
e = TreeNode(5)
x = TreeNode(8)
y = TreeNode(9)
e.setLeft(x)
b.setLeft(d)
b.setRight(e)
f = TreeNode(6)
g = TreeNode(7)
f.setRight(y)
c.setLeft(f)
c.setRight(g)
ans = []
findAllAncestors(a, 9, ans)
print(ans)<jupyter_output>[1, 3, 6, 9]
<jupyter_text># Alternative way of solving the problem<jupyter_code>def printAllAncestors(root, node):
if root is None or node is None:
return False
if ((root.getData() == node)
or printAllAncestors(root.getLeft(), node)
or printAllAncestors(root.getRight(), node)):
print(root.getData())
return True
return False
printAllAncestors(a,9)<jupyter_output>9
6
3
1
<jupyter_text># Solution without recursion.
Use postorder traversal to solve this problem.
<jupyter_code>def findAncestorsIteratively(root, target):
if root is None or target is None:
return False
stack = []
node = root
prev_right = None
while node or stack:
if node:
stack.append(node)
node = node.getLeft()
else:
element = stack[-1]
if element.getData() == target:
break
if element.getRight() and prev_right!=element.getRight():
prev_right= node = element.getRight()
else:
stack.pop()
for i in stack:
print(i.getData())
findAncestorsIteratively(a,9)<jupyter_output>1
3
6
9
|
no_license
|
/Trees/Binary Trees/Problems/.ipynb_checkpoints/AncestorsOfBinaryTree-checkpoint.ipynb
|
sumeet13/Algorithms-and-Data-Structures
| 3 |
<jupyter_start><jupyter_text>Table of Contents
1 HISTOGRAM2 QQPLOT3 AGGREGATION PLOT (part4)## HISTOGRAM<jupyter_code>library(MASS)
# Create a histogram of counts with hist()
hist(Cars93$Horsepower, main = "hist() plot")
# Create a normalized histogram with truehist()
hist(Cars93$Horsepower, main = "truehist() plot", freq = FALSE)
# Add the density curve to the histogram
lines(density(Cars93$Horsepower))<jupyter_output><empty_output><jupyter_text>## QQPLOT<jupyter_code># Load the car package to make qqPlot() available
library(car)
# Create index16, pointing to 16-week chicks
index16 <- which(ChickWeight$Time == 16)
# Get the 16-week chick weights
weights <- ChickWeight[index16,"weight"]
# Show the normal QQ-plot of the chick weights
qqPlot(weights)
hist(weights, freq = FALSE)
# Show the normal QQ-plot of the Boston$tax data
qqPlot(Boston$tax)
hist(Boston$tax)<jupyter_output>Warning message:
"package 'car' was built under R version 3.5.2"<jupyter_text>## AGGREGATION PLOT (part4)<jupyter_code># Set up a two-by-two plot array
par(mfrow = c(2,2))
# Plot the raw duration data
plot(geyser$duration, main = "Raw data")
# Plot the normalized histogram of the duration data
truehist(geyser$duration, main = "Histogram")
# Plot the density of the duration data
plot(density(geyser$duration), main = "Density")
# Construct the normal QQ-plot of the duration data
qqPlot(geyser$duration, main = "QQ-plot")<jupyter_output><empty_output>
|
no_license
|
/Data visualization - base R/.ipynb_checkpoints/2.1. One variable-checkpoint.ipynb
|
yoogun143/Datacamp_R
| 3 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 3