markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
BusThis bus has a passenger entry and exit control system to monitor the number of occupants it carries and thus detect when there are too many.At each stop, the entry and exit of passengers is represented by a tuple consisting of two integer numbers.```bus_stop = (in, out)```The succession of stops is represented by... | # Variables
stops = [(10, 0), (4, 1), (3, 5), (3, 4), (5, 1), (1, 5), (5, 8), (4, 6), (2, 3)] | _____no_output_____ | Unlicense | bus/bus-checkpoint.ipynb | oscarledesma16/bcn-feb-2019-prework |
1. Calculate the number of stops. | stops = [(10, 0), (4, 1), (3, 5), (3, 4), (5, 1), (1, 5), (5, 8), (4, 6), (2, 3)]
print(len(stops)) | 9
| Unlicense | bus/bus-checkpoint.ipynb | oscarledesma16/bcn-feb-2019-prework |
2. Assign to a variable a list whose elements are the number of passengers at each stop (in-out).Each item depends on the previous item in the list + in - out. | stops = [(10, 0), (4, 1), (3, 5), (3, 4), (5, 1), (1, 5), (5, 8), (4, 6), (2, 3)]
for_stop = [(stops[0][0]) - (stops[0][1]), (stops[1][0]) - (stops[1][1]), (stops[2][0]) - (stops[2][1]), (stops[3][0]) - (stops[3][1]), (stops[4][0]) - (stops[4][1]), (stops[5][0]) - (stops[5][1]), (stops[6][0]) - (stops[6][1]), (stops[7... | Total passengers for stop 10
Total passengers for stop 13
Total passengers for stop 11
Total passengers for stop 10
Total passengers for stop 14
Total passengers for stop 10
Total passengers for stop 7
Total passengers for stop 5
Total passengers for stop 4
| Unlicense | bus/bus-checkpoint.ipynb | oscarledesma16/bcn-feb-2019-prework |
3. Find the maximum occupation of the bus. | from itertools import accumulate
accumulate_for_stops = (list(accumulate(for_stop)))
print(accumulate_for_stops)
print("Maximum occupation of the bus is:", (max(accumulate_for_stops))) | [10, 13, 11, 10, 14, 10, 7, 5, 4]
Maximum occupation of the bus is: 14
| Unlicense | bus/bus-checkpoint.ipynb | oscarledesma16/bcn-feb-2019-prework |
4. Calculate the average occupation. And the standard deviation. | average_occupation = sum(accumulate_for_stops)/len(accumulate_for_stops)
print("Average occupation:", average_occupation)
from math import sqrt
suma = 0
for i in for_stop:
suma += (i - average_occupation) ** 2
radicando = suma / (len(for_stop) - 1)
standard_deviation = sqrt(radicando... | Average occupation: 9.333333333333334
Standard deviation: 10.424330514074594
| Unlicense | bus/bus-checkpoint.ipynb | oscarledesma16/bcn-feb-2019-prework |
Lambda School Data Science - Recurrent Neural Networks and LSTM> "Yesterday's just a memory - tomorrow is never what it's supposed to be." -- Bob Dylan LectureWish you could save [Time In A Bottle](https://www.youtube.com/watch?v=AnWWj6xOleY)? With statistics you can do the next best thing - understand how data varie... | import numpy as np
from random import random
days = np.array((range(28)))
stock_quotes = np.array([random() + day * random() for day in days])
stock_quotes | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Let's take a look with a scatter plot: | from matplotlib.pyplot import scatter
scatter(days, stock_quotes) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Looks pretty linear, let's try a simple OLS regression.First, these need to be NumPy arrays: | days = days.reshape(-1, 1) # X needs to be column vectors | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Now let's use good old `scikit-learn` and linear regression: | from sklearn.linear_model import LinearRegression
ols_stocks = LinearRegression()
ols_stocks.fit(days, stock_quotes)
ols_stocks.score(days, stock_quotes) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
That seems to work pretty well, but real stocks don't work like this.Let's make *slightly* more realistic data that depends on more than just time: | # Not everything is best as a comprehension
stock_data = np.empty([len(days), 4])
for day in days:
asset = random()
liability = random()
quote = random() + ((day * random()) + (20 * asset) - (15 * liability))
quote = max(quote, 0.01) # Want positive quotes
stock_data[day] = np.array([quote, day, asset, liabi... | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Let's look again: | stock_quotes = stock_data[:,0]
scatter(days, stock_quotes) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
How does our old model do? | days = np.array(days).reshape(-1, 1)
ols_stocks.fit(days, stock_quotes)
ols_stocks.score(days, stock_quotes) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Not bad, but can we do better? | ols_stocks.fit(stock_data[:,1:], stock_quotes)
ols_stocks.score(stock_data[:,1:], stock_quotes) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Yep - unsurprisingly, the other covariates (assets and liabilities) have info.But, they do worse without the day data. | ols_stocks.fit(stock_data[:,2:], stock_quotes)
ols_stocks.score(stock_data[:,2:], stock_quotes) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Time series jargonThere's a lot of semi-standard language and tricks to talk about this sort of data. [NIST](https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc4.htm) has an excellent guidebook, but here are some highlights: Moving averageMoving average aka rolling average aka running average.Convert a series o... | stock_quotes_rolling = [sum(stock_quotes[i:i+3]) / 3
for i in range(len(stock_quotes - 2))]
stock_quotes_rolling | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Pandas has nice series related functions: | import pandas as pd
df = pd.DataFrame(stock_quotes)
df.rolling(3).mean() | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
ForecastingForecasting - at it's simplest, it just means "predict the future": | ols_stocks.fit(stock_data[:,1:], stock_quotes)
ols_stocks.predict([[29, 0.5, 0.5]]) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
One way to predict if you just have the series data is to use the prior observation. This can be pretty good (if you had to pick one feature to model the temperature for tomorrow, the temperature today is a good choice). | temperature = np.array([30 + random() * day
for day in np.array(range(365)).reshape(-1, 1)])
temperature_next = temperature[1:].reshape(-1, 1)
temperature_ols = LinearRegression()
temperature_ols.fit(temperature[:-1], temperature_next)
temperature_ols.score(temperature[:-1], temperature_next) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
But you can often make it better by considering more than one prior observation. | temperature_next_next = temperature[2:].reshape(-1, 1)
temperature_two_past = np.concatenate([temperature[:-2], temperature_next[:-1]],
axis=1)
temperature_ols.fit(temperature_two_past, temperature_next_next)
temperature_ols.score(temperature_two_past, temperature_next_next) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Exponential smoothingExponential smoothing means using exponentially decreasing past weights to predict the future.You could roll your own, but let's use Pandas. | temperature_df = pd.DataFrame(temperature)
temperature_df.ewm(halflife=7).mean() | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Halflife is among the parameters we can play with: | sse_1 = ((temperature_df - temperature_df.ewm(halflife=7).mean())**2).sum()
sse_2 = ((temperature_df - temperature_df.ewm(halflife=3).mean())**2).sum()
print(sse_1)
print(sse_2) | 0 1.212862e+06
dtype: float64
0 987212.470691
dtype: float64
| MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Note - the first error being higher doesn't mean it's necessarily *worse*. It's *smoother* as expected, and if that's what we care about - great! SeasonalitySeasonality - "day of week"-effects, and more. In a lot of real world data, certain time periods are systemically different, e.g. holidays for retailers, weekends... | sales = np.array([random() + (day % 7) * random() for day in days])
scatter(days, sales) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
How does linear regression do at fitting this? | sales_ols = LinearRegression()
sales_ols.fit(days, sales)
sales_ols.score(days, sales) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
That's not great - and the fix depends on the domain. Here, we know it'd be best to actually use "day of week" as a feature. | day_of_week = days % 7
sales_ols.fit(day_of_week, sales)
sales_ols.score(day_of_week, sales) | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Note that it's also important to have representative data across whatever seasonal feature(s) you use - don't predict retailers based only on Christmas, as that won't generalize well. Recurrent Neural NetworksThere's plenty more to "traditional" time series, but the latest and greatest technique for sequence data is r... | '''
#Trains an LSTM model on the IMDB sentiment classification task.
The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster methods such as TF-IDF + LogReg.
**Notes**
- RNNs are tricky. Choice of batch size is important,
choice of loss and optimizer is critical, etc.
Some con... | Using TensorFlow backend.
| MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
RNN Text generation with NumPyWhat else can we do with RNN? Since we're analyzing the *sequence*, we can do more than classify - we can *generate* text. We'll pull some news stories using [newspaper](https://github.com/codelucas/newspaper/). Initialization | !pip install newspaper3k
import newspaper
ap = newspaper.build('https://www.apnews.com')
len(ap.articles)
article_text = ''
for article in ap.articles[:1]:
try:
article.download()
article.parse()
article_text += '\n\n' + article.text
except:
print('Failed: ' + article.url)
article_text = article... | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Forward propagation | def forwardprop(inputs, targets, h_prev):
# Since the RNN receives the sequence, the weights are not updated during one sequence.
xs, hs, ys, ps = {}, {}, {}, {} # dictionary
hs[-1] = np.copy(h_prev) # Copy previous hidden state vector to -1 key value.
loss = 0 # loss initialization
fo... | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Backward propagation | def backprop(ps, inputs, hs, xs):
dWxh, dWhh, dWhy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) # make all zero matrices.
dbh, dby = np.zeros_like(b_h), np.zeros_like(b_y)
dhnext = np.zeros_like(hs[0]) # (hidden_size,1)
# reversed
for t in reversed(range(len(inputs))):
... | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Training | %%time
data_pointer = 0
# memory variables for Adagrad
mWxh, mWhh, mWhy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy)
mbh, mby = np.zeros_like(b_h), np.zeros_like(b_y)
for i in range(iteration):
h_prev = np.zeros((hidden_size,1)) # reset RNN memory
data_pointer = 0 # go from start of data
... | iter 0, loss: 1.921729
iter 100, loss: 0.000758
iter 200, loss: 0.000377
iter 300, loss: 0.000219
iter 400, loss: 0.000141
iter 500, loss: 0.000096
iter 600, loss: 0.000062
iter 700, loss: 0.000043
iter 800, loss: 0.000031
iter 900, loss: 0.000024
CPU times: user 5min 53s, sys: 3min 26s, total: 9min 20s
Wall time: 4min... | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Prediction | def predict(test_char, length):
x = np.zeros((num_chars, 1))
x[char_to_int[test_char]] = 1
ixes = []
h = np.zeros((hidden_size,1))
for t in range(length):
h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h)
y = np.dot(W_hy, h) + b_y
p = np.exp(y) / np.sum(np.exp(y))
... | ----
Califor Gooffic te nofft ove yke Gocr’sdlliamoffico
----
| MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Well... that's *vaguely* language-looking. Can you do better? AssignmentIt is said that [infinite monkeys typing for an infinite amount of time](https://en.w... | # TODO - Words, words, mere words, no matter from the heart. | _____no_output_____ | MIT | module1-rnn-and-lstm/.ipynb_checkpoints/LS_DS_441_RNN_and_LSTM-checkpoint.ipynb | rick1270/DS-Unit-4-Spring-4-Deep-Learning |
Label GenerationUses code written by visoft and posted on kaggle to generate four different resolutions of labels | grid_sizes = pd.read_csv(os.path.join(global_vars.DATA_DIR,'grid_sizes.csv'), index_col=0)
train_labels = pd.read_csv(os.path.join(global_vars.DATA_DIR,'train_wkt_v4.csv'), index_col=0)
train_names = list(train_labels.index.unique())
base_size= 835
label_sizes = [base_size, base_size*2, base_size*4]
for im_name in tra... | _____no_output_____ | MIT | step1_generate_labels.ipynb | danzelmo/dstl-competition |
Assignment 1. Formalia:Please read the [assignment overview page](https://github.com/suneman/socialdata2021/wiki/Assignment-1-and-2) carefully before proceeding. This page contains information about formatting (including formats etc), group sizes, and many other aspects of handing in the assignment. _If you fail to fo... | focuscrimes = set(['WEAPON LAWS', 'PROSTITUTION', 'DRIVING UNDER THE INFLUENCE', 'ROBBERY', 'BURGLARY', 'ASSAULT', 'DRUNKENNESS', 'DRUG/NARCOTIC', 'TRESPASS', 'LARCENY/THEFT', 'VANDALISM', 'VEHICLE THEFT', 'STOLEN PROPERTY', 'DISORDERLY CONDUCT']) | _____no_output_____ | MIT | assignments/Assignment1.ipynb | christianpoulsen/socialdata2021 |
*Exercise*: More temporal patterns. During week 1, we plotted some crime development over time (how each of the focus-crimes changed over time, year-by-year). In this exercise, please generate the visualizations described below. Use the same date-ranges as in Week 1. For each set of plots, describe the plots (as you w... | import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("../incidents.csv")
df = df[df["Category"].isin(focuscrimes)]
df["Date_Time"] = pd.to_datetime(df["Date"] + " " + df["Time"])
df.sort_values(by=["Date_Time"], inplace=True, ascending=True)
df.head()
weeks = ["Monday", "Tuesday", "Wednesday", "Thursda... | _____no_output_____ | MIT | assignments/Assignment1.ipynb | christianpoulsen/socialdata2021 |
Part 2: Thinking about data and visualization *Excercise:* Questions for the [second video lecture](https://www.youtube.com/watch?v=yiU56codNlI).* As mentioned earlier, visualization is not the only way to test for correlation. We can (for example) calculate the Pearson correlation. Explain in your own words how the P... | import numpy as np # linear algebra
import folium
import datetime as dt
SF = folium.Map([37.773972, -122.431297], zoom_start=13, tiles="Stamen Toner")
folium.Marker([37.77919, -122.41914], popup='City Hall').add_to(SF)
# Address, location, X, Y
ndf = df[df["Category"] == "DRUG/NARCOTIC"]
start = ndf["Date_Time"].s... | _____no_output_____ | MIT | assignments/Assignment1.ipynb | christianpoulsen/socialdata2021 |
AU Fundamentals of Python Programming-W10X Topic 1(主題1)-字串和print()的參數 Step 1: Hello World with 其他參數sep = "..." 列印分隔 end="" 列印結尾* sep: string inserted between values, default a space.* end: string appended after the last value, default a newline. | print('Hello World!') #'Hello World!' is the same as "Hello World!"
help(print) #註解是不會執行的
print('Hello '+'World!')
print("Hello","World", sep="+")
print("Hello"); print("World!")
print("Hello", end=' ');print("World")
| _____no_output_____ | MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Step 2: Escape Sequence (逸出序列)* \newline Ignored* \\ Backslash (\)* \' Single quote (')* \" Double quote (")* \a ASCII Bell (BEL)* \b ASCII Backspace (BS)* \n ASCII Linefeed (LF)* \r ASCII Carriage Return (CR)* \t ASCII Horizontal Tab (TAB)* \ooo ASCII character with octal value ooo* \xhh... ASCII character with hex v... | print("Hello\nWorld!")
print("Hello","World!", sep="\n")
txt = "We are the so-called \"Vikings\" from the north."
print(txt) | _____no_output_____ | MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Step 3: 使用 字串尾部的\來建立長字串 | iPhone11='iPhone 11是由蘋果公司設計和銷售的智能手機,為第13代iPhone系列智能手機之一,亦是iPhone XR的後繼機種。\
其在2019年9月10日於蘋果園區史蒂夫·喬布斯劇院由CEO蒂姆·庫克隨iPhone 11 Pro及iPhone 11 Pro Max一起發佈,\
並於2019年9月20日在世界大部分地區正式發售。其採用類似iPhone XR的玻璃配鋁金屬設計;\
具有6.1英吋Liquid Retina HD顯示器,配有Face ID;並採用由蘋果自家設計的A13仿生晶片,\
帶有第三代神經網絡引擎。機器能夠防濺、耐水及防塵,在最深2米的水下停留時間最長可達30分鐘。'
print(iPhone11... | _____no_output_____ | MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Step 4: 使用六個雙引號來建立長字串 ''' ... ''' 或 """ ... """ | iPhone11='''
iPhone 11是由蘋果公司設計和銷售的智能手機,為第13代iPhone系列智能手機之一,亦是iPhone XR的後繼機種。
其在2019年9月10日於蘋果園區史蒂夫·喬布斯劇院由CEO蒂姆·庫克隨iPhone 11 Pro及iPhone 11 Pro Max一起發佈,
並於2019年9月20日在世界大部分地區正式發售。其採用類似iPhone XR的玻璃配鋁金屬設計;
具有6.1英吋Liquid Retina HD顯示器,配有Face ID;並採用由蘋果自家設計的A13仿生晶片,
帶有第三代神經網絡引擎。機器能夠防濺、耐水及防塵,在最深2米的水下停留時間最長可達30分鐘。'''
print(iPhone1... | _____no_output_____ | MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Topic 2(主題2)-型別轉換函數 Step 5: 輸入變數的值 | name = input('Please input your name:')
print('Hello, ', name)
print(type(name)) #列印變數的型別 | _____no_output_____ | MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Step 6: Python 型別轉換函數* int() 變整數* float() 變浮點數* str() 變字串* 變數名稱=int(字串變數)* 變數名稱=str(數值變數 | #變數宣告
varA = 66 #宣告一個整數變數
varB = 1.68 #宣告一個有小數的變數(電腦叫浮點數)
varC = 'GoPython' #宣告一個字串變數
varD = str(varA) #將整數88轉成字串的88
varE = str(varB) #將浮點數1.68轉成字串的1.68
varF = int('2019') #將字串2019轉作整數數值的2019
varG = float('3.14') #將字串3.14轉作浮點數數值的3.14
score = input('Please input your score:')
score = int(score)
print(type(score)) #列印... | _____no_output_____ | MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Topic 3(主題3)-索引和切片```a = "Hello, World!"print(a[1]) Indexingprint(a[2:5]) Slicing``` Step 8: 索引(Indexing) | a = "Hello Wang"
d = "0123456789"
print(a[3]) #Indexing
a = "Hello Wang"
d = "0123456789"
print(a[-3]) #Negative Indexing | _____no_output_____ | MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Step 9: 切片(Slicing) | a = "Hello Wang"
d = "0123456789"
print(a[2:5]) #Slicing
a = "Hello Wang"
d = "0123456789"
print(a[2:]) #Slicing
a = "Hello Wang"
d = "0123456789"
print(a[:5]) #Slicing
a = "Hello Wang"
d = "0123456789"
print(a[-6:-2]) #Slicing
a = "Hello Wang"
d = "0123456789"
print(a[-4:]) #Slicing | _____no_output_____ | MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Topic 4(主題4)-格式化輸出```A = 435; B = 59.058print('Art: %5d, Price per Unit: %8.2f' % (A, B)) %-formatting 格式化列印print("Art: {0:5d}, Price per Unit: {1:8.2f}".format(A,B)) str-format(Python 2.6+)print(f"Art:{A:5d}, Price per Unit: {B:8.2f}") f-string (Python 3.6+)``` Step 10: %-formatting 格式化列印透過% 運算符... | A = 435; B = 59.058
print('Art: %5d, Price per Unit: %8.2f' % (A, B))
FirstName = "Mary"; LastName= "Lin"
print("She is %s %s" %(FirstName, LastName)) | She is Mary Lin
| MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Step 11: str-format(Python 2.6+)格式化列印 | A = 435; B = 59.058
print("Art: {0:5d}, Price per Unit: {1:8.2f}".format(435, 59.058))
FirstName = "Mary"; LastName= "Lin"
print("She is {} {}".format(FirstName, LastName)) | She is Mary Lin
| MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Step 12: f-string (Python 3.6+)格式化列印 | A = 435; B = 59.058
print(f"Art:{A:5d}, Price per Unit: {B:8.2f}")
FirstName = "Mary"; LastName= "Lin"
print(f"She is {FirstName} {LastName}") | She is Mary Lin
| MIT | notebooks/AUP110_W11_Notebook.ipynb | htchu/AU110Programming |
Topic Modelling (joint plots by quality band)Shorter notebook just for Figures 9 and 10 in the paper. | %matplotlib inline
import matplotlib.pyplot as plt
# magics and warnings
%load_ext autoreload
%autoreload 2
import warnings; warnings.simplefilter('ignore')
import os, random
from tqdm import tqdm
import pandas as pd
import numpy as np
seed = 43
random.seed(seed)
np.random.seed(seed)
import nltk, gensim, sklearn, s... | _____no_output_____ | CC-BY-4.0 | topic_modelling_secondary.ipynb | Living-with-machines/lwm_ARTIDIGH_2020_OCR_impact_downstream_NLP_tasks |
Load the datasetCreated with the main Topic Modelling notebook. | bands_data = {x:dict() for x in range(1,5)}
import pickle, os
for band in range(1,5):
with open("trove_overproof/models/hum_band_%d.pkl"%band, 'rb') as handle:
bands_data[band]["model_human"] = pickle.load(handle)
with open("trove_overproof/models/corpus_hum_band_%d.pkl"%band, 'rb') as handle:
... | _____no_output_____ | CC-BY-4.0 | topic_modelling_secondary.ipynb | Living-with-machines/lwm_ARTIDIGH_2020_OCR_impact_downstream_NLP_tasks |
Evaluation Intrinsic evalSee http://qpleple.com/topic-coherence-to-evaluate-topic-models. | for band in range(1,5):
print("Quality band",band)
# Human
# Compute Perplexity
print('\nPerplexity (Human): ', bands_data[band]["model_human"].log_perplexity(bands_data[band]["corpus_human"])) # a measure of how good the model is. The lower the better.
# Compute Coherence Score
coherence... | Quality band 1
Perplexity (Human): -8.103261158627364
Coherence Score (Human): -1.636788533548382
Perplexity (OCR): -8.602782438888957
Coherence Score (OCR): -1.744833949213988
==========
Quality band 2
Perplexity (Human): -8.210335723784008
Coherence Score (Human): -1.717423902243484
Perplexity (OCR): -... | CC-BY-4.0 | topic_modelling_secondary.ipynb | Living-with-machines/lwm_ARTIDIGH_2020_OCR_impact_downstream_NLP_tasks |
Match of topicsWe match every topic in the OCR model with a topic in the human model (by best matching), and assess the overall distance between the two using the weighted total distance over a set of N top words (from the human model to the ocr model). The higher this value, the closest two topics are.Note that to fi... | import networkx as nx
from scipy.stats import entropy
from collections import defaultdict
# analyse matches
distances = {x:list() for x in range(1,5)}
n_words_in_common = {x:list() for x in range(1,5)}
matches = {x:defaultdict(int) for x in range(1,5)}
top_n = 500
for band in range(1,5):
G = nx.Graph()
... | _____no_output_____ | CC-BY-4.0 | topic_modelling_secondary.ipynb | Living-with-machines/lwm_ARTIDIGH_2020_OCR_impact_downstream_NLP_tasks |
Inspect Nucleus Training DataInspect and visualize data loading and pre-processing code.https://www.kaggle.com/c/data-science-bowl-2018 | import os
import sys
import itertools
import math
import logging
import json
import re
import random
import time
import concurrent.futures
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.lines as lines
from matplotlib.patches import Polygon
imp... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Configurations | # Dataset directory
DATASET_DIR = os.path.join(ROOT_DIR, "datasets/nucleus")
# Use configuation from nucleus.py, but override
# image resizing so we see the real sizes here
class NoResizeConfig(nucleus.NucleusConfig):
IMAGE_RESIZE_MODE = "none"
config = NoResizeConfig() | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Notebook Preferences | def get_ax(rows=1, cols=1, size=16):
"""Return a Matplotlib Axes array to be used in
all visualizations in the notebook. Provide a
central point to control graph sizes.
Adjust the size attribute to control how big to render images
"""
_, ax = plt.subplots(rows, cols, figsize=(size*cols, siz... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
DatasetDownload the dataset from the competition Website. Unzip it and save it in `mask_rcnn/datasets/nucleus`. If you prefer a different directory then change the `DATASET_DIR` variable above.https://www.kaggle.com/c/data-science-bowl-2018/data | # Load dataset
dataset = nucleus.NucleusDataset()
# The subset is the name of the sub-directory, such as stage1_train,
# stage1_test, ...etc. You can also use these special values:
# train: loads stage1_train but excludes validation images
# val: loads validation images from stage1_train. For a list
# ... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Display Samples | # Load and display random samples
image_ids = np.random.choice(dataset.image_ids, 4)
for image_id in image_ids:
image = dataset.load_image(image_id)
mask, class_ids = dataset.load_mask(image_id)
visualize.display_top_masks(image, mask, class_ids, dataset.class_names, limit=1)
# Example of loading a specific... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Dataset StatsLoop through all images in the dataset and collect aggregate stats. | def image_stats(image_id):
"""Returns a dict of stats for one image."""
image = dataset.load_image(image_id)
mask, _ = dataset.load_mask(image_id)
bbox = utils.extract_bboxes(mask)
# Sanity check
assert mask.shape[:2] == image.shape[:2]
# Return stats dict
return {
"id": image_id... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Image Size Stats | # Image stats
image_shape = np.array([s['shape'] for s in stats])
image_color = np.array([s['color'] for s in stats])
print("Image Count: ", image_shape.shape[0])
print("Height mean: {:.2f} median: {:.2f} min: {:.2f} max: {:.2f}".format(
np.mean(image_shape[:, 0]), np.median(image_shape[:, 0]),
np.min(image... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Nuclei per Image Stats | # Segment by image area
image_area_bins = [256**2, 600**2, 1300**2]
print("Nuclei/Image")
fig, ax = plt.subplots(1, len(image_area_bins), figsize=(16, 4))
area_threshold = 0
for i, image_area in enumerate(image_area_bins):
nuclei_per_image = np.array([len(s['bbox'])
for s in stats... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Nuclei Size Stats | # Nuclei size stats
fig, ax = plt.subplots(1, len(image_area_bins), figsize=(16, 4))
area_threshold = 0
for i, image_area in enumerate(image_area_bins):
nucleus_shape = np.array([
b
for s in stats if area_threshold < (s['shape'][0] * s['shape'][1]) <= image_area
for b in s['bbox']])
nuc... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Image AugmentationTest out different augmentation methods | # List of augmentations
# http://imgaug.readthedocs.io/en/latest/source/augmenters.html
augmentation = iaa.Sometimes(0.9, [
iaa.Fliplr(0.5),
iaa.Flipud(0.5),
iaa.Multiply((0.8, 1.2)),
iaa.GaussianBlur(sigma=(0.0, 5.0))
])
# Load the image multiple times to show augmentations
limit = 4
ax = get_ax(rows=2... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Image CropsMicroscoy images tend to be large, but nuclei are small. So it's more efficient to train on random crops from large images. This is handled by `config.IMAGE_RESIZE_MODE = "crop"`. | class RandomCropConfig(nucleus.NucleusConfig):
IMAGE_RESIZE_MODE = "crop"
IMAGE_MIN_DIM = 256
IMAGE_MAX_DIM = 256
crop_config = RandomCropConfig()
# Load the image multiple times to show augmentations
limit = 4
image_id = np.random.choice(dataset.image_ids, 1)[0]
ax = get_ax(rows=2, cols=limit//2)
for i in... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Mini MasksInstance binary masks can get large when training with high resolution images. For example, if training with 1024x1024 image then the mask of a single instance requires 1MB of memory (Numpy uses bytes for boolean values). If an image has 100 instances then that's 100MB for the masks alone. To improve trainin... | # Load random image and mask.
image_id = np.random.choice(dataset.image_ids, 1)[0]
image = dataset.load_image(image_id)
mask, class_ids = dataset.load_mask(image_id)
original_shape = image.shape
# Resize
image, window, scale, padding, _ = utils.resize_image(
image,
min_dim=config.IMAGE_MIN_DIM,
max_dim=co... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
AnchorsFor an FPN network, the anchors must be ordered in a way that makes it easy to match anchors to the output of the convolution layers that predict anchor scores and shifts. * Sort by pyramid level first. All anchors of the first level, then all of the second and so on. This makes it easier to separate anchors by... | ## Visualize anchors of one cell at the center of the feature map
# Load and display random image
image_id = np.random.choice(dataset.image_ids, 1)[0]
image, image_meta, _, _, _ = modellib.load_image_gt(dataset, crop_config, image_id)
# Generate Anchors
backbone_shapes = modellib.compute_backbone_shapes(config, image... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Data Generator | # Create data generator
random_rois = 2000
g = modellib.data_generator(
dataset, crop_config, shuffle=True, random_rois=random_rois,
batch_size=4,
detection_targets=True)
# Uncomment to run the generator through a lot of images
# to catch rare errors
# for i in range(1000):
# print(i)
# _, _ = next... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
ROIsTypically, the RPN network generates region proposals (a.k.a. Regions of Interest, or ROIs). The data generator has the ability to generate proposals as well for illustration and testing purposes. These are controlled by the `random_rois` parameter. | if random_rois:
# Class aware bboxes
bbox_specific = mrcnn_bbox[b, np.arange(mrcnn_bbox.shape[1]), mrcnn_class_ids[b], :]
# Refined ROIs
refined_rois = utils.apply_box_deltas(rois[b].astype(np.float32), bbox_specific[:,:4] * config.BBOX_STD_DEV)
# Class aware masks
mask_specific = mrcnn_mask[b... | _____no_output_____ | MIT | samples/nucleus/inspect_nucleus_data.ipynb | zgle-fork/Mask_RCNN |
Positional Encoding | import math
import numpy as np
%matplotlib inline
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.dpi']=130
def get_positional_watermark(max_sequence_length, embedding_dimensions):
pe_matrix = np.zeros((max_sequence_length, embedding_dimensions), dtype=np.float32)
for ... | _____no_output_____ | MIT | ipynb/positional_encoding_0x01.ipynb | mindscan-de/FluentGenesis-Classifier |
+ This notebook is part of lecture 7 *Solving Ax=0, pivot variables, and special solutions* in the OCW MIT course 18.06 by Prof Gilbert Strang [1]+ Created by me, Dr Juan H Klopper + Head of Acute Care Surgery + Groote Schuur Hospital + University Cape Town + Email me with your thoughts, comments, suggestio... | from IPython.core.display import HTML, Image
css_file = 'style.css'
HTML(open(css_file, 'r').read())
#import numpy as np
from sympy import init_printing, Matrix, symbols
#import matplotlib.pyplot as plt
#import seaborn as sns
#from IPython.display import Image
from warnings import filterwarnings
init_printing(use_late... | _____no_output_____ | MIT | _math/MIT_OCW_18_06_Linear_algebra/I_08_Solving_homogeneous_systems_Pivot_variables_Special_solutions.ipynb | aixpact/data-science |
Solving homogeneous systems Pivot variables Special solutions * We are trying to solve a system of linear equations* For homogeneous systems the right-hand side is the zero vector* Consider the example below | A = Matrix([[1, 2, 2, 2], [2, 4, 6, 8], [3, 6, 8, 10]])
A # A 3x4 matrix
x1, x2, x3, x4 = symbols('x1, x2, x3, x4')
x_vect = Matrix([x1, x2, x3, x4]) # A 4x1 matrix
x_vect
b = Matrix([0, 0, 0])
b # A 3x1 matrix | _____no_output_____ | MIT | _math/MIT_OCW_18_06_Linear_algebra/I_08_Solving_homogeneous_systems_Pivot_variables_Special_solutions.ipynb | aixpact/data-science |
* The **x** column vector is a set of all the solutions to this homogeneous equation* It forms the nullspace* Note that the column vectors in A are not linearly independent * Performing elementary row operations leaves us with the matrix below* It has two pivots, which is termed **rank** 2 | A.rref() # rref being reduced row echelon form | _____no_output_____ | MIT | _math/MIT_OCW_18_06_Linear_algebra/I_08_Solving_homogeneous_systems_Pivot_variables_Special_solutions.ipynb | aixpact/data-science |
* Which represents the following$$ { x }_{ 1 }\begin{bmatrix} 1 \\ 0 \\ 0 \end{bmatrix}+{ x }_{ 2 }\begin{bmatrix} 2 \\ 0 \\ 0 \end{bmatrix}+{ x }_{ 3 }\begin{bmatrix} 0 \\ 1 \\ 0 \end{bmatrix}+{ x }_{ 4 }\begin{bmatrix} -2 \\ 2 \\ 0 \end{bmatrix}=\begin{bmatrix} 0 \\ 0 \\ 0 \end{bmatrix}\\ { x }_{ 1 }+2{ x }_{ 2 }+0{ ... | A_trans = A.transpose() # Creating a new matrix called A_trans and giving it the value of the inverse of A
A_trans
A_trans.rref() # In reduced row echelon form this would be the following matrix | _____no_output_____ | MIT | _math/MIT_OCW_18_06_Linear_algebra/I_08_Solving_homogeneous_systems_Pivot_variables_Special_solutions.ipynb | aixpact/data-science |
Load image metadata | imageDedup = [m for m in imagemeta.find()]
imageDedup.sort(key=lambda x: x['image_id'])
phash_to_idx_mapping = {}
for i in range(len(imageDedup)):
phash = imageDedup[i]['phash']
l = phash_to_idx_mapping.get(phash, [])
l.append(i)
phash_to_idx_mapping[phash] = l
def phash_to_idx (phash):
return phash... | _____no_output_____ | CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Calculate distance Hash distance | image_hashes = [make_hashes(m) for m in imageDedup]
# distance = calculate_distance(image_hashes)
distance = calculate_distance(image_hashes, hash_type='phash')
# distance2 = np.ndarray([len(image_hashes), len(image_hashes)])
# for i in tqdm(range(len(image_hashes))):
# for j in range(i+1):
# diff = hashes_... | _____no_output_____ | CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Find duplicated pairs from distance matrix | def set_distance (hashes, value, mat=distance):
phash_x = hashes[0]
phash_y = phash_x if len(hashes) == 1 else hashes[1]
idx_x = phash_to_idx(phash_x)
idx_y = phash_to_idx(phash_y)
if idx_x == None or idx_y == None:
return
for s in itertools.product(idx_x, idx_y):
i, j = s
... | _____no_output_____ | CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Apply information from meta data | duplicated_post_image_phash_pairs = PersistentSet()
duplicated_post_image_phash_pairs.set_file(handmade_dir/'duplicated_post_image_phash_pairs.json')
for p in tqdm(posts.find()):
if len(p.get('duplicated_posts', [])) == 0:
continue
dp_phashes = {i['phash']
for dp in p['duplicated_p... | _____no_output_____ | CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Apply manual labeled data | duplicated_image_phash_pairs = PersistentSet.load_set(handmade_dir/'duplicated_image_phash_pairs.json')
not_duplicated_image_phash_pairs = PersistentSet.load_set(handmade_dir/'not_duplicated_image_phash_pairs.json')
related_image_phash_pairs = PersistentSet.load_set(handmade_dir/'related_image_phash_pairs.json')
invali... | _____no_output_____ | CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Human in the Loop | def make_dedup_box (idx_x, idx_y, default=None):
image_x = imageDedup[idx_x]
phash_x = image_x['phash']
image_y = imageDedup[idx_y]
phash_y = image_y['phash']
hash_pair = frozenset([phash_x, phash_y])
yes_btn = widgets.Button(description="Duplicated", button_style='success')
no_btn = widget... | StopIteration
| CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Visually check images Images with high variability | # interested_phashes = set()
# def potential_duplicates_high (threshold):
# for i in range(distance.shape[0]):
# for j in range(i):
# if distance[i, j] >= threshold:
# phash_pair = frozenset([imageDedup[i]['phash'], imageDedup[j]['phash']])
# if (phash_pair in dup... | _____no_output_____ | CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Invalid images | # invalids = []
# for h in invalid_image_phashes:
# invalid_images = [f for f in imagefiles.find({'phash': h})]
# if len(invalid_images) > 0:
# invalids.append(invalid_images[0])
# display(Box([widgets.Image(value=open(i['file_path'], 'rb').read(), width=100, height=100) for i in invalids],
# ... | _____no_output_____ | CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Consolidate Related images | related_images = [[imageDedup[idx]['image_id'] for idx in c]
for c in nx.components.connected_components(nx.Graph(related_distance <= 1))
if len(c) > 1]
len(related_images)
for ids in related_images:
for i in ids:
imageMeta = imageDedup[image_id_to_idx(i)]
r... | _____no_output_____ | CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Duplicated images | excluding_image_phashes = PersistentSet.load_set(handmade_dir/'excluding_image_phashes.json')
excluding_image_phashes.persist_add('c13e3ae10e70fd86')
excluding_image_phashes.persist_add('fe81837a94e3807e')
excluding_image_phashes.persist_add('af9da24292fae149')
excluding_image_phashes.persist_add('ad87d2696738ca4c')
ex... | _____no_output_____ | CC-BY-4.0 | notebooks/images_dedup.ipynb | leoyuholo/bad-vis-images |
Using enterprise_extensions to analyze PTA dataIn this notebook you will learn:* How to use `enterprise_extensions` to create `enterprise` models,* How to search in PTA data for a isotropic stochastic gravitational wave background using multiple pulsars,* How to implement a HyperModel object to sample a `model_2a` mod... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
%load_ext autoreload
%autoreload 2
import os, glob, json, pickle
import matplotlib.pyplot as plt
import numpy as np
from enterprise.pulsar import Pulsar
from enterprise_extensions import models, hypermodel
import sys
sys.path.append("..")
from setting... | WARNING: AstropyDeprecationWarning: The private astropy._erfa module has been made into its own package, pyerfa, which is a dependency of astropy and can be imported directly using "import erfa" [astropy._erfa]
| MIT | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis |
Get par, tim, and noise files | psrlist = None # define a list of pulsar name strings that can be used to filter.
# set the data directory
datadir = '../data'
if not os.path.isdir(datadir):
datadir = '../../data'
print('datadir =', datadir)
# for the entire pta
parfiles = sorted(glob.glob(datadir + '/par/*par'))
timfiles = sorted(glob.glob(datadi... | _____no_output_____ | MIT | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis |
Read par and tim files into `enterprise` `Pulsar` objects | # check for file and load pickle if it exists:
pickle_loc = datadir + '/psrs.pkl'
if os.path.exists(pickle_loc):
with open(pickle_loc, 'rb') as f:
psrs = pickle.load(f)
# else: load them in slowly:
else:
psrs = []
ephemeris = 'DE438'
for p, t in zip(parfiles, timfiles):
psr = Pulsar(p, ... | _____no_output_____ | MIT | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis |
Set up PTA model* This model_2a includes everything from the verbose version in these tutorials: * fixed white noise parameters based on noisedict `params`, * common red noise signal (no correlation function) with 5 frequencies, * and a spectral index of 13/3 | pta = models.model_2a(psrs,
psd='powerlaw',
noisedict=params,
n_gwbfreqs=5, # modify the number of common red noise frequencies used here
gamma_common=13/3) # remove this line for a varying spectral index | _____no_output_____ | MIT | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis |
Setup an instance of a HyperModel.* This doesn't mean we are doing model selection (yet!), but the hypermodel module gives access to some nifty sampling schemes. | super_model = hypermodel.HyperModel({0: pta}) | _____no_output_____ | MIT | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis |
Setup PTMCMCSampler | outDir = '../../chains/extensions_chains'
sampler = super_model.setup_sampler(resume=True,
outdir=outDir,
sample_nmodel=False,)
# sampler for N steps
N = int(5e6)
x0 = super_model.initial_sample()
# Sampling this will take a very long time. If you... | _____no_output_____ | MIT | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis |
Plot Output | # Uncomment this one to load the chain if you have sampled with PTMCMCSampler:
# chain = np.loadtxt(os.path.join(outDir, 'chain_1.txt'))
# This will load the chain that we have provided:
chain = np.load(os.path.join(outDir, 'chain_1.npz'))['arr_0']
burn = int(0.25 * chain.shape[0]) # remove burn in segment of samplin... | our_max = -14.707808651660155
| MIT | tutorials/full_pta_gwb/pe_extensions.ipynb | AaronDJohnson/12p5yr_stochastic_analysis |
This Notebook is done for Pixelated Data for 1 Compton, 2 PhotoElectric with 2 more Ambiguity! I got 89% Accuracy on Test set! I am getting X from Blurred Dataset, y as labels from Ground Truth | import pandas as pd
import numpy as np
from keras.utils import to_categorical
import math
df = {'Label':[],
'Theta_P1':[], 'Theta_E1':[], 'Theta_P2':[], 'Theta_E2':[], 'Theta_P3':[], 'Theta_E3':[], 'Theta_P4':[], 'Theta_E4':[],
'Theta_P5':[], 'Theta_E5':[], 'Theta_P6':[], 'Theta_E6':[], 'Theta_P7':[], 'The... | [0. 1. 0. 0.]
| MIT | ML_Files/Cross_Strip_8Fam/.ipynb_checkpoints/Pixelated_32Features_DNN_Time_Label-checkpoint.ipynb | nananasiri/Multiple-Interaction-Photon-Events |
Define the Model | # Define the keras model
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(128, input_dim=X.shape[1], activation='relu')) #8, 8: 58 12, 8:64 32,16: 66 16,16: 67
model.add(Dense(64, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(... | 226/226 [==============================] - 0s 540us/step - loss: 0.3584 - accuracy: 0.8997
Accuracy: 89.97
| MIT | ML_Files/Cross_Strip_8Fam/.ipynb_checkpoints/Pixelated_32Features_DNN_Time_Label-checkpoint.ipynb | nananasiri/Multiple-Interaction-Photon-Events |
HyperParameterOptimization | def create_model(hyperParams):
hidden_layers = hyperParams['hidden_layers']
activation = hyperParams['activation']
dropout = hyperParams['dropout']
output_activation = hyperParams['output_activation']
loss = hyperParams['loss']
input_size = hyperParams['input_size']
output_size = hyperP... | 10-fold cross validation on these hyperparameters: {'input_size': 4, 'output_size': 2, 'batch_size': 32, 'epochs': 100, 'hidden_layers': [4, 4], 'activation': 'relu', 'dropout': 0.5, 'output_activation': 'softmax', 'loss': 'categorical_crossentropy'}
-------------------------------------------
CV mean: 0.6174, CV ... | MIT | ML_Files/Cross_Strip_8Fam/.ipynb_checkpoints/Pixelated_32Features_DNN_Time_Label-checkpoint.ipynb | nananasiri/Multiple-Interaction-Photon-Events |
LassoLars Regression with Scale This Code template is for the regression analysis using a simple LassoLars Regression. It is a lasso model implemented using the LARS algorithm and feature scaling. Required Packages | import warnings
import numpy as np
import pandas as pd
import seaborn as se
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn import preprocessing
from sklearn.metrics import r2_score, mean_absolute_error, mean_squar... | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
InitializationFilepath of CSV file | #filepath
file_path= "" | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
List of features which are required for model training . | #x_values
features=[] | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Target feature for prediction. | #y_value
target='' | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. | df=pd.read_csv(file_path)
df.head() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to... | X=df[features]
Y=df[target] | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_du... | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Calling preprocessing functions on the feature and target set. | x=X.columns.to_list()
for i in x:
X[i]=NullClearner(X[i])
X=EncodeX(X)
Y=NullClearner(Y)
X.head() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | f,ax = plt.subplots(figsize=(18, 18))
matrix = np.triu(X.corr())
se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.