markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Using SPP models (signatures from different sizes)
For the SPP models, we can use images of any size as input, to obtain a feature vector of a fixed size. Note that in the paper we obtained better results by padding small images to a fixed canvas size, and processed larger images in their original size. More informatio... | from preprocess.normalize import remove_background
# To illustrate that images from any size can be used, let's process the signatures just
# by removing the background and inverting the image
normalized_spp = 255 - remove_background(original)
plt.imshow(normalized_spp)
# Note that now we need to use lists instead... | interactive_example.ipynb | luizgh/sigver_wiwd | bsd-2-clause |
if/else, for, while, pass, break, continue | p=[]
for i in xrange(2,100):
isprime=1
for j in p:
if(i%j==0):
isprime=0
break
if isprime:
p.append(i)
print p
for i in xrange(10):
pass
i=10
while i>0:
i=i-1
print i
x=['text',"str",''' Hello World\\n ''']
print x | notebook/Somkiat's Basic Python.ipynb | wasit7/PythonDay | bsd-3-clause |
List: access, update, del, len(), + , in, for, slicing, append(), insert(), pop(), remove() | x=['a','b','c']
#access
print x[0]
#update
x[0]='d'
print x
print "size of x%d is"%len(x)
y=['x','y','z']
z=x+y
gamma=y+x
print z
print gamma
print 'a' in x
print y
y.remove('y')# remove by vavlue
print y
print y
y.pop(0)# remove by index
print y
y.insert(0,'x')
y.insert(1,'y')
print y
x=[i*i for i in xrange(10)]... | notebook/Somkiat's Basic Python.ipynb | wasit7/PythonDay | bsd-3-clause |
Dictionary: access, update, del, in | x={}
x={'key':'value'}
x['foo']='bar'
x
x['foo']='Hello'
x
x['m']=123
x['foo','key']
keys=['foo','key']
[x[k] for k in keys]
print x
del x
print x | notebook/Somkiat's Basic Python.ipynb | wasit7/PythonDay | bsd-3-clause |
Function: function definition, pass by reference, keyword argument, default argument, lambda
a built-in immutable type: str, int, long, bool, float, tuple | def foo(x):
x=x+1
y=2*x
return y
print foo(3)
x=3
print foo(x)
print x
def bar(x=[]):
x.append(7)
print "in loop: {}".format(x)
x=[1,2,3]
print x
bar(x)
print x
def func(x=0,y=0,z=0):#defualt input argument
return x*100+y*10+z
func(1,2)
func(y=2,z=3,x=1)#keyword input argument
f=func
f(... | notebook/Somkiat's Basic Python.ipynb | wasit7/PythonDay | bsd-3-clause |
Module: class, from, import, reload(), package and init | class Obj:
def __init__(self, _x, _y):
self.x = _x
self.y = _y
def update(self, _x, _y):
self.x += _x
self.y += _y
def __str__(self):
return "x:%d, y:%d"%(self.x,self.y)
a=Obj(5,7)#call __init__
print a#call __str__
a.update(1,2)#call update
print a
... | notebook/Somkiat's Basic Python.ipynb | wasit7/PythonDay | bsd-3-clause |
The code is inside the box (known as a code cell), and the computer's response (called the output of the code) is shown below the box. As you can see, the computer printed the message that we wanted.
Arithmetic
We can also print the value of some arithmetic operation (such as addition, subtraction, multiplication, or ... | print(1 + 2) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
We can also do subtraction in python. The next code cell subtracts 5 from 9 and prints the result, which is 4. | print(9 - 5) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
You can actually do a lot of calculations with python! See the table below for some examples.
<table style="width: 100%;">
<tbody>
<tr><th><b>Operation</b></th><th><b>Symbol</b></th><th><b>Example</b></th></tr>
<tr>
<td>Addition</td>
<td>+</td>
<td>1 + 2 = 3</td>
</tr>
<tr>
<td>Subtraction</td>
<td>-</td>
<td>5 - 4 = ... | print(((1 + 3) * (9 - 2) / 2) ** 2) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
In general, Python follows the PEMDAS rule when deciding the order of operations.
Comments
We use comments to annotate what code is doing. They help other people to understand your code, and they can also be helpful if you haven't looked at your own code in a while. So far, the code that we have written is very short... | # Multiply 3 by 2
print(3 * 2) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
To indicate to Python that a line is comment (and not Python code), you need to write a pound sign (#) as the very first character.
Once Python sees the pound sign and recognizes that the line is a comment, it is completely ignored by the computer. This is important, because just like English or Hindi (or any other ... | Multiply 3 by 2 | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
Variables
So far, you have used code to make a calculation and print the result, and the result isn't saved anywhere. However, you can imagine that you might want to save the result to work with it later. For this, you'll need to use variables.
Creating variables
The next code cell creates a variable named test_var a... | # Create a variable called test_var and give it a value of 4+5
test_var = 4 + 5
# Print the value of test_var
print(test_var) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
In general, to work with a variable, you need to begin by selecting the name you want to use. Variable names are ideally short and descriptive. They also need to satisfy several requirements:
- They can't have spaces (e.g., test var is not allowed)
- They can only include letters, numbers, and underscores (e.g., test... | # Set the value of a new variable to 3
my_var = 3
# Print the value assigned to my_var
print(my_var)
# Change the value of the variable to 100
my_var = 100
# Print the new value assigned to my_var
print(my_var) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
Note that in general, whenever you define a variable in a code cell, all of the code cells that follow also have access to the variable. For instance, we use the next code cell to access the values of my_var (from the code cell above) and test_var (from earlier in this tutorial). | print(my_var)
print(test_var) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
The next code cell tells Python to increase the current value of my_var by 3.
To do this, we still need to use my_var = like before. And also just like before, the new value we want to assign to the variable is to the right of the = sign. | # Increase the value by 3
my_var = my_var + 3
# Print the value assigned to my_var
print(my_var) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
Using multiple variables
It's common for code to use multiple variables. This is especially useful when we have to do a long calculation with multiple inputs.
In the next code cell, we calculate the number of seconds in four years. This calculation uses five inputs. | # Create variables
num_years = 4
days_per_year = 365
hours_per_day = 24
mins_per_hour = 60
secs_per_min = 60
# Calculate number of seconds in four years
total_secs = secs_per_min * mins_per_hour * hours_per_day * days_per_year * num_years
print(total_secs) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
As calculated above, there are 126144000 seconds in four years.
Note it is possible to do this calculation without variables as just 60 * 60 * 24 * 365 * 4, but it is much harder to check that the calculation without variables does not have some error, because it is not as readable. When we use variables (such as nu... | # Update to include leap years
days_per_year = 365.25
# Calculate number of seconds in four years
total_secs = secs_per_min * mins_per_hour * hours_per_day * days_per_year * num_years
print(total_secs) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
Note: You might have noticed the .0 added at the end of the number, which might look unnecessary. This is caused by the fact that in the second calculation, we used a number with a fractional part (365.25), whereas the first calculation multipled just numbers with no fractional part. You'll learn more about this in L... | print(hours_per_dy) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
When you see NameError like this, it's an indication that you should check how you have spelled the variable that it references as "not defined". Then, to fix the error, you need only correct the spelling. | print(hours_per_day) | notebooks/intro_to_programming/raw/tut1.ipynb | Kaggle/learntools | apache-2.0 |
Now we have the weatherData object with its data variable containing four extra columns, i.e. Month, _LastYearsAvg, _LastYearsStd, and _ThisYear. The columns _LastYearsAvg and _LastYearsStd contain the average and standard deviation of all previous years of month Month respectively. Columns _ThisYear contains the avera... | weatherData.data.head() | notebooks/Load climate data.ipynb | nberliner/delveData | gpl-2.0 |
First let's remove the early years in which we are not interested in. Note also that there might be months containing -9999. This can happen if they constitute the first months in which the measurement was available (and no last years are available). In addition create a new column containing the difference of the meas... | data = weatherData.data[ weatherData.data["Year"] >= 1980 ]
data = data[ np.isclose(data["_LastYearsStd"], -9999.0) == False ]
data["avg_diff"] = data["_LastYearsAvg"] - data["_ThisYear"] | notebooks/Load climate data.ipynb | nberliner/delveData | gpl-2.0 |
In order get a feel for a good classification for extreme climate events we can look at the distribution of the difference between the average values and the distribution of the standard deviations. I will take the maximum temperature reading as an example. | data_tmax = data[ data["Element"] == "TMAX" ]
hist_avg, bin_edges_avg = np.histogram( np.abs(np.abs(np.asarray( data_tmax["avg_diff"] ))), bins=100 )
hist_std, bin_edges_std = np.histogram( np.abs(np.asarray( data_tmax["_LastYearsStd"] )), bins=100 )
fig = plt.figure(figsize=(10, 8), dpi=200)
ax = fig.add_subplot(111... | notebooks/Load climate data.ipynb | nberliner/delveData | gpl-2.0 |
This already gives us an indication that there are events that are extreme in the sense that they deviate by more than 1-2 standard deviations from the average of past years. However this still does not give us a robust and good indicator of when to call a climate event extreme.
A relative measure will be much more hel... | data["avg_diff_fold"] = np.abs(data["avg_diff"]) / data["_LastYearsStd"]
data_tmax = data[ data["Element"] == "TMAX" ] | notebooks/Load climate data.ipynb | nberliner/delveData | gpl-2.0 |
For plotting we will remove the few events that deviate extremely and would render the plotting impossible | tmpData = np.abs(np.asarray( data_tmax["avg_diff_fold"] ))
tmpData = tmpData[ tmpData < np.percentile(tmpData, 99.9) ]
hist_avg_fold, bin_edges_avg_fold = np.histogram(tmpData, bins=100, density=True) | notebooks/Load climate data.ipynb | nberliner/delveData | gpl-2.0 |
Here I will take prior knowlede (I looked already at the plot and went back one step) and assume that the distribution will look like a normal distribution. To visually emphasize this point we can fit the distribution and add the fit to the plot. | mu, std = norm.fit(np.concatenate((-tmpData,tmpData), axis=1))
x = np.linspace(0, 5, 100)
p = norm.pdf(x, mu, std)
print("Fitted a normal distribution at %.1f with standard deviation %.2f" %(mu, std))
fig = plt.figure(figsize=(10, 8), dpi=200)
ax = fig.add_subplot(111)
ax.tick_params(axis='both', which='major', label... | notebooks/Load climate data.ipynb | nberliner/delveData | gpl-2.0 |
From the plot we can see that there is no obvious cutoff point that we could choose so we will have to use common sense. I would argue that a good measure would be to declare the 25% highest values as extreme. This will give us a cuttoff point of: | cutoff = np.percentile(tmpData, 85)
print("The cutoff point is set to %.2f" %cutoff) | notebooks/Load climate data.ipynb | nberliner/delveData | gpl-2.0 |
What the plot above is not telling us is how the individual bins of the histogram are populated in time. By that I mean that each event in the histogram is linked to the year in which the measurement was taken. We can now ask the question if events that deviate far from the all time averages are more likely to have occ... | bin_years = list()
for i in range(1,len(bin_edges_avg_fold)):
start, end = bin_edges_avg_fold[i-1], bin_edges_avg_fold[i]
tmp = data_tmax[ data_tmax["avg_diff_fold"] > start ]
tmp = tmp[ tmp["avg_diff_fold"] < end ]
bin_years.append(tmp["Year"])
avg_time = [ np.average(item) for item in bin_years ]
a... | notebooks/Load climate data.ipynb | nberliner/delveData | gpl-2.0 |
B
Write a function, variance, which computes the variance of a list of numbers.
The function takes one argument: a list or 1D NumPy array of numbers. It returns one floating-point number: the variance of all the numbers.
Recall the formula for variance:
$$
variance = \frac{1}{N - 1} \sum_{i = 1}^{N} (x_i - \mu_x)^2
$$
... | try:
variance
except:
assert False
else:
assert True
import numpy as np
np.random.seed(5987968)
x = np.random.random(8491)
v = x.var(ddof = 1)
np.testing.assert_allclose(v, variance(x))
np.random.seed(4159)
y = np.random.random(25)
w = y.var(ddof = 1)
np.testing.assert_allclose(w, variance(y)) | assignments/A7/A7_Q1.ipynb | eds-uga/csci1360-fa16 | mit |
C
The lecture on statistics mentions latent variables, specifically how you cannot know what the underlying process is that's generating your data; all you have is the data, on which you have to impose certain assumptions in order to derive hypotheses about what generated the data in the first place.
To illustrate this... | import numpy as np
np.random.seed(5735636)
sample1 = np.random.normal(loc = 10, scale = 5, size = 10)
sample2 = np.random.normal(loc = 10, scale = 5, size = 1000)
sample3 = np.random.normal(loc = 10, scale = 5, size = 1000000)
#########################
# DON'T MODIFY ANYTHING #
# ABOVE THIS BLOCK #
#############... | assignments/A7/A7_Q1.ipynb | eds-uga/csci1360-fa16 | mit |
Here we look at some Chang'e 5 low data rate telemetry received with Allen Telescope array on 2021-01-23, during its transfer to the Sun-Earth L1 point. The recorded data corresponds to the frequency 8471.2 MHz, which corresponds to the lander.
The frames are CCSDS concatenated frames with a frames size of 220 bytes. | def load_frames(path):
frame_size = 220
frames = np.fromfile(path, dtype = 'uint8')
frames = frames[:frames.size//frame_size*frame_size].reshape((-1, frame_size))
return frames
frames = load_frames('ATA_2021-01-23/ce5_frames_1.u8') | CE5/CE-5 frame analysis ATA 2021-01-23.ipynb | daniestevez/jupyter_notebooks | gpl-3.0 |
AOS frames
AOS frames come from spacecraft 91 and virtual channels 1 and 2. Other combinations are most likely to corruted frames despite the fact that the Reed-Solomon decoder was successful. | aos = [CE5_AOSFrame.parse(f) for f in frames]
collections.Counter([a.primary_header.transfer_frame_version_number for a in aos])
collections.Counter([a.primary_header.spacecraft_id for a in aos
if a.primary_header.transfer_frame_version_number == 1])
collections.Counter([a.primary_header.virtual_... | CE5/CE-5 frame analysis ATA 2021-01-23.ipynb | daniestevez/jupyter_notebooks | gpl-3.0 |
Virtual channel 1
The vast majority of frames belong to virtual channel 1, which seems to send real-time telemetry. | [a.primary_header for a in aos if a.primary_header.virtual_channel_id == 1][:10]
vc1 = [a for a in aos if a.primary_header.virtual_channel_id == 1]
fc = np.array([a.primary_header.virtual_channel_frame_count for a in vc1])
[a.insert_zone for a in aos[:10]]
t_vc1 = np.datetime64('2012-08-01') + np.timedelta64(1, 's') ... | CE5/CE-5 frame analysis ATA 2021-01-23.ipynb | daniestevez/jupyter_notebooks | gpl-3.0 |
We need to sort the data, since the different files we've loaded up are not in chronological order. | vc1_packets = list(ccsds.extract_space_packets(vc1, 108, 1, get_timestamps = True))
vc1_sp_headers = [ccsds.SpacePacketPrimaryHeader.parse(p[0]) for p in vc1_packets] | CE5/CE-5 frame analysis ATA 2021-01-23.ipynb | daniestevez/jupyter_notebooks | gpl-3.0 |
There are space packets in may APIDs. The contents of each APID are shown belown in plot form, but it's not easy to guess what any of the values mean. | vc1_apids = collections.Counter([p.APID for p in vc1_sp_headers])
vc1_apids
vc1_by_apid = {apid : [p for h,p in zip(vc1_sp_headers, vc1_packets)
if h.APID == apid] for apid in vc1_apids}
plot_apids(vc1_by_apid, 108, 1) | CE5/CE-5 frame analysis ATA 2021-01-23.ipynb | daniestevez/jupyter_notebooks | gpl-3.0 |
๋ง๋ค์ด์ง ndarray ๊ฐ์ฒด์ ํํ์(representation)์ ๋ณด๋ฉด ๋ฐ๊นฅ์ชฝ์ array()๋ ๊ฒ์ด ๋ถ์ด ์์ ๋ฟ ๋ฆฌ์คํธ์ ๋์ผํ ๊ตฌ์กฐ์ฒ๋ผ ๋ณด์ธ๋ค. ์ค์ ๋ก 0, 1, 2, 3 ์ด๋ผ๋ ์์๊ฐ ์๋ ๋ฆฌ์คํธ๋ ๋ค์๊ณผ ๊ฐ์ด ๋ง๋ ๋ค. | L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(L))
L | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
๊ทธ๋ฌ๋ ndarray ํด๋์ค ๊ฐ์ฒด a์ ๋ฆฌ์คํธ ํด๋์ค ๊ฐ์ฒด b๋ ๋ง์ ์ฐจ์ด๊ฐ ์๋ค. ์ฐ์ ๋ฆฌ์คํธ ํด๋์ค ๊ฐ์ฒด๋ ๋ด๋ถ์ ์ผ๋ก linked list์ ๊ฐ์ ํํ๋ฅผ ๊ฐ์ง๋ฏ๋ก ๊ฐ๊ฐ์ ์์๊ฐ ๋ค๋ฅธ ์๋ฃํ์ด ๋ ์ ์๋ค. ๊ทธ๋ฌ๋ ndarray ํด๋์ค ๊ฐ์ฒด๋ C์ธ์ด์ ํ๋ ฌ์ฒ๋ผ ์ฐ์์ ์ธ ๋ฉ๋ชจ๋ฆฌ ๋ฐฐ์น๋ฅผ ๊ฐ์ง๊ธฐ ๋๋ฌธ์ ๋ชจ๋ ์์๊ฐ ๊ฐ์ ์๋ฃํ์ด์ด์ผ ํ๋ค. ์ด๋ฌํ ์ ์ฝ์ ๊ฐ์ง๋ ๋์ ๋ด๋ถ์ ์์์ ๋ํ ์ ๊ทผ๊ณผ ๋ฐ๋ณต๋ฌธ ์คํ์ด ๋นจ๋ผ์ง๋ค.
ndarray ํด๋์ค์ ๋ ๋ค๋ฅธ ํน์ฑ์ ํ๋ ฌ์ ๊ฐ ์์์ ๋ํ ์ฐ์ฐ์ ํ ๋ฒ์ ์ฒ๋ฆฌํ๋ ๋ฒกํฐํ ์ฐ์ฐ(vectorized operation)์ ์ง์ํ๋ค๋ ์ ... | a = np.arange(1000) #arange : ๊ทธ๋ฅ array range์ array๋ก ๋ฐ๊ฟ
%time a2 = a**2
a1 = np.arange(10)
print(a1)
print(2 * a1) | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
๋ฆฌ์คํธ ๊ฐ์ฒด์ ๊ฒฝ์ฐ์๋ ๋ค์๊ณผ ๊ฐ์ด ๋ฐ๋ณต๋ฌธ์ ์ฌ์ฉํด์ผ ํ๋ค. | L = range(1000)
%time L2 = [i**2 for i in L] | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
๊ฐ๊ฐ์ ์ฝ๋ ์คํ์์ IPython์ %time ๋งค์ง ๋ช
๋ น์ ์ด์ฉํ์ฌ ์คํ ์๊ฐ์ ์ธก์ ํ ๊ฒฐ๊ณผ ndarray์ ์ ๋๋ฒ์ค ์ฐ์ฐ ์คํ ์๋๊ฐ ๋ฆฌ์คํธ ๋ฐ๋ณต๋ฌธ ๋ณด๋ค ๋น ๋ฅธ ๊ฒ์ ๋ณผ ์ ์๋ค. ndarray์ ๋ฉ๋ชจ๋ฆฌ ํ ๋น์ ํ ๋ฒ์ ํ๋ ๊ฒ๋ ๋นจ๋ผ์ง ์ด์ ์ ํ๋์ด๊ณ ์ ๋๋ฒ์ค ์ฐ์ฐ์ ์ฌ์ฉํ๊ฒ ๋๋ฉด NumPy ๋ด๋ถ์ ์ผ๋ก ๊ตฌํ๋ ๋ฐ๋ณต๋ฌธ์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ ๋ฐ๋ณต๋ฌธ ์คํ ์์ฒด๋ ๋นจ๋ผ์ง๋ค.
๋ฐ๋ผ์ Python์ ์ฑ๋ฅ ๊ฐ์ ์ ์ํด ๋ฐ๋์ ์ง์ผ์ผํ๋ ์ฝ๋ฉ ๊ด๋ก ์ค์ ํ๋๊ฐ NumPy์ ndarray์ ๋ฒกํฐํ ์ฐ์ฐ์ผ๋ก ๋์ฒดํ ์ ์๋ ๊ฒฝ์ฐ์๋ Python ์์ฒด์ ๋ฐ๋ณต๋ฌธ์ ์ฌ์ฉํ์ง ์๋๋ค๋ ์ ์ด... | L = range(10)
print(L)
print(2 * L) | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
๋ค์ฐจ์ ํ๋ ฌ์ ์์ฑ
ndarray ๋ N-dimensional Array์ ์ฝ์์ด๋ค. ์ด๋ฆ ๊ทธ๋๋ก ndarray ํด๋์ค๋ ๋จ์ ๋ฆฌ์คํธ์ ์ ์ฌํ 1์ฐจ์ ํ๋ ฌ ์ด์ธ์๋ 2์ฐจ์ ํ๋ ฌ, 3์ฐจ์ ํ๋ ฌ ๋ฑ์ ๋ค์ฐจ์ ํ๋ ฌ ์๋ฃ ๊ตฌ์กฐ๋ฅผ ์ง์ํ๋ค.
์๋ฅผ ๋ค์ด ๋ค์๊ณผ ๊ฐ์ด ๋ฆฌ์คํธ์ ๋ฆฌ์คํธ๋ฅผ ์ด์ฉํ์ฌ 2์ฐจ์ ํ๋ ฌ์ ์์ฑํ๊ฑฐ๋ ๋ฆฌ์คํธ์ ๋ฆฌ์คํธ์ ๋ฆฌ์คํธ๋ฅผ ์ด์ฉํ์ฌ 3์ฐจ์ ํ๋ ฌ์ ์์ฑํ ์ ์๋ค. | a = np.array([0, 1, 2])
a
b = np.array([[0, 1, 2], [3, 4, 5]]) # 2 x 3 array
b
a = np.array([0, 0, 0, 1])
a
c = np.array([[[1,2],[3,4]],[[5,6],[7,8]]]) # 2 x 2 x 2 array
c | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
ํ๋ ฌ์ ์ฐจ์ ๋ฐ ํฌ๊ธฐ๋ ndim ์์ฑ๊ณผ shape ์์ฑ์ผ๋ก ์ ์ ์๋ค. | print(a.ndim)
print(a.shape)
a = np.array([[1,2,3 ],[3,4,5]])
a
a.ndim
a.shape
print(b.ndim)
print(b.shape)
print(c.ndim)
print(c.shape) | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
๋ค์ฐจ์ ํ๋ ฌ์ ์ธ๋ฑ์ฑ
ndarray ํด๋์ค๋ก ๊ตฌํํ ๋ค์ฐจ์ ํ๋ ฌ์ ์์ ํ๋ ํ๋๋ ๋ค์๊ณผ ๊ฐ์ด ์ฝค๋ง(comma ,)๋ฅผ ์ฌ์ฉํ์ฌ ์ ๊ทผํ ์ ์๋ค. ์ฝค๋ง๋ก ๊ตฌ๋ถ๋ ์ฐจ์์ ์ถ(axis)์ด๋ผ๊ณ ๋ ํ๋ค. ํ๋กฏ์ x์ถ๊ณผ y์ถ์ ๋ ์ฌ๋ฆฌ๋ฉด ๋ ๊ฒ์ด๋ค. | a = np.array([[0, 1, 2], [3, 4, 5]])
a
a[0,0] # ์ฒซ๋ฒ์งธ ํ์ ์ฒซ๋ฒ์งธ ์ด
a[0,1] # ์ฒซ๋ฒ์งธ ํ์ ๋๋ฒ์งธ ์ด
a[-1, -1] # ๋ง์ง๋ง ํ์ ๋ง์ง๋ง ์ด | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
๋ค์ฐจ์ ํ๋ ฌ์ ์ฌ๋ผ์ด์ฑ
ndarray ํด๋์ค๋ก ๊ตฌํํ ๋ค์ฐจ์ ํ๋ ฌ์ ์์ ์ค ๋ณต์ ๊ฐ๋ฅผ ์ ๊ทผํ๋ ค๋ฉด ์ผ๋ฐ์ ์ธ ํ์ด์ฌ ์ฌ๋ผ์ด์ฑ(slicing)๊ณผ comma(,)๋ฅผ ํจ๊ป ์ฌ์ฉํ๋ฉด ๋๋ค. | a = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
a
a[0, :] # ์ฒซ๋ฒ์งธ ํ ์ ์ฒด
a[:, 1] # ๋๋ฒ์งธ ์ด ์ ์ฒด
a[1, 1:] # ๋๋ฒ์งธ ํ์ ๋๋ฒ์งธ ์ด๋ถํฐ ๋์ด๊น์ง | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
ํ๋ ฌ ์ธ๋ฑ์ฑ
NumPy ndarray ํด๋์ค์ ๋๋ค๋ฅธ ๊ฐ๋ ฅํ ๊ธฐ๋ฅ์ ํ๋ ฌ ์ธ๋ฑ์ฑ(fancy indexing)์ด๋ผ๊ณ ๋ ๋ถ๋ฅด๋ ํ๋ ฌ ์ธ๋ฑ์ฑ(array indexing) ๋ฐฉ๋ฒ์ด๋ค. ์ธ๋ฑ์ฑ์ด๋ผ๋ ์ด๋ฆ์ด ๋ถ์์ง๋ง ์ฌ์ค์ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ง์(Query) ๊ธฐ๋ฅ์ ์ํํ๋ค.
ํ๋ ฌ ์ธ๋ฑ์ฑ์์๋ ๋๊ดํธ(Bracket, [])์์ ์ธ๋ฑ์ค ์ ๋ณด๋ก ์ซ์๋ ์ฌ๋ผ์ด์ค๊ฐ ์๋ ndarray ํ๋ ฌ์ ๋ฐ์ ์ ์๋ค. ์ฌ๊ธฐ์์๋ ์ด ํ๋ ฌ์ ํธ์์ ์ธ๋ฑ์ค ํ๋ ฌ์ด๋ผ๊ณ ๋ถ๋ฅด๊ฒ ๋ค. ํ๋ ฌ ์ธ๋ฑ์ฑ์ ๋ฐฉ์์์ ๋ถ๋ฆฌ์(Boolean) ํ๋ ฌ ๋ฐฉ์๊ณผ ์ ์ ํ๋ ฌ ๋ฐฉ์ ๋๊ฐ์ง๊ฐ ์๋ค.
๋จผ์ ๋ถ๋ฆฌ์ ํ๋ ฌ ์ธ๋ฑ์ฑ ๋ฐฉ์์ ์ธ๋ฑ... | a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
idx = np.array([True, False, True, False, True, False, True, False, True, False])
a[idx] | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
์ด๋ ๋ค์๊ณผ ๊ฐ์ด ๊ฐ๋จํ๊ฒ ์ธ ์๋ ์๋ค. | a[a % 2 == 0]
a[a % 2] # 0์ด True, 1์ด False | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
2์ฐจ์ ์ด์์ ์ธ๋ฑ์ค์ธ ๊ฒฝ์ฐ์๋ ๋ค์๊ณผ ๊ฐ์ด | a = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
[a % 2 == 0]
a[[a % 2 == 0]]
a[a % 2] | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
์ ์ ํ๋ ฌ ์ธ๋ฑ์ฑ์์๋ ์ธ๋ฑ์ค ํ๋ ฌ์ ์์ ๊ฐ๊ฐ์ด ์๋ ndarray ๊ฐ์ฒด ์์ ํ๋๋ฅผ ๊ฐ๋ฆฌํค๋ ์ธ๋ฑ์ค ์ ์์ด์ฌ์ผ ํ๋ค.
์๋ฅผ ๋ค์ด 1์ฐจ์ ํ๋ ฌ์์ ํ์๋ฒ์งธ ์์๋ง ๊ณจ๋ผ๋ด๋ ค๋ง ๋ค์๊ณผ ๊ฐ๋ค | a = np.array([0, 1, 2, 3, 4, 10, 6, 7, 8, 9]) * 10
idx = np.array([0, 5, 7, 9, 9]) #์์น๋ฅผ ๋ปํจ
a[idx] | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
์ ์ ํ๋ ฌ ์ธ๋ฑ์ค์ ํฌ๊ธฐ๋ ์๋์ ํ๋ ฌ ํฌ๊ธฐ์ ๋ฌ๋ผ๋ ์๊ด์๋ค. ๊ฐ์ ์์๋ฅผ ๋ฐ๋ณตํด์ ๊ฐ๋ฆฌํค๋ ๊ฒฝ์ฐ์๋ ์๋์ ํ๋ ฌ๋ณด๋ค ๋ ์ปค์ง๊ธฐ๋ ํ๋ค. | a = np.array([0, 1, 2, 3]) * 10
idx = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2])
a[idx]
a[0] | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
ํ๋ ฌ ์ธ๋ฑ์ฑ
๋ถ๋ฆฌ์(Boolean) ๋ฐฉ์ ํ๋ ฌ ์ธ๋ฑ์ฑ
True์ธ ์์๋ง ์ ํ
์ธ๋ฑ์ค์ ํฌ๊ธฐ๊ฐ ํ๋ ฌ์ ํฌ๊ธฐ์ ๊ฐ์์ผ ํ๋ค.
์์น ์ง์ ๋ฐฉ์ ํ๋ ฌ ์ธ๋ฑ์ฑ
์ง์ ๋ ์์น์ ์์๋ง ์ ํ
์ธ๋ฑ์ค์ ํฌ๊ธฐ๊ฐ ํ๋ ฌ์ ํฌ๊ธฐ์ ๋ฌ๋ผ๋ ๋๋ค. | joobun = np.array(["BSY","PJY","PJG","BSJ"])
idx = np.array([0,0,0,1,1,1,2,2,2,3,3,3,0,1,2,3])
joobun[idx]
a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a[(a % 2 == 0) & (a % 3 == 1)] | 06. ๊ธฐ์ด ์ ํ๋์/01. NumPy ์๊ฐ.ipynb | zzsza/Datascience_School | mit |
ๅ ่ฝฝๅๅๅคๆฐๆฎ
ๆๅปบ็ฅ็ป็ฝ็ป็ๅ
ณ้ฎไธๆญฅๆฏๆญฃ็กฎๅฐๅๅคๆฐๆฎใไธๅๅฐบๅบฆ็บงๅซ็ๅ้ไฝฟ็ฝ็ป้พไปฅ้ซๆๅฐๆๆกๆญฃ็กฎ็ๆ้ใๆไปฌๅจไธๆนๅทฒ็ปๆไพไบๅ ่ฝฝๅๅๅคๆฐๆฎ็ไปฃ็ ใไฝ ๅพๅฟซๅฐ่ฟไธๆญฅๅญฆไน ่ฟไบไปฃ็ ๏ผ | data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head() | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
ๆฐๆฎ็ฎไป
ๆญคๆฐๆฎ้ๅ
ๅซ็ๆฏไป 2011 ๅนด 1 ๆ 1 ๆฅๅฐ 2012 ๅนด 12 ๆ 31 ๆฅๆ้ดๆฏๅคฉๆฏๅฐๆถ็้ช่ฝฆไบบๆฐใ้ช่ฝฆ็จๆทๅๆไธดๆถ็จๆทๅๆณจๅ็จๆท๏ผcnt ๅๆฏ้ช่ฝฆ็จๆทๆฐๆฑๆปๅใไฝ ๅฏไปฅๅจไธๆน็ๅฐๅๅ ่กๆฐๆฎใ
ไธๅพๅฑ็คบ็ๆฏๆฐๆฎ้ไธญๅ 10 ๅคฉๅทฆๅณ็้ช่ฝฆไบบๆฐ๏ผๆไบๅคฉไธไธๅฎๆฏ 24 ไธชๆก็ฎ๏ผๆไปฅไธๆฏ็ฒพ็กฎ็ 10 ๅคฉ๏ผใไฝ ๅฏไปฅๅจ่ฟ้็ๅฐๆฏๅฐๆถ็ง้ใ่ฟไบๆฐๆฎๅพๅคๆ๏ผๅจๆซ็้ช่กไบบๆฐๅฐไบ๏ผๅทฅไฝๆฅไธไธ็ญๆ้ดๆฏ้ช่ก้ซๅณฐๆใๆไปฌ่ฟๅฏไปฅไปไธๆน็ๆฐๆฎไธญ็ๅฐๆธฉๅบฆใๆนฟๅบฆๅ้ฃ้ไฟกๆฏ๏ผๆๆ่ฟไบไฟกๆฏ้ฝไผๅฝฑๅ้ช่กไบบๆฐใไฝ ้่ฆ็จไฝ ็ๆจกๅๅฑ็คบๆๆ่ฟไบๆฐๆฎใ | rides[:24*10].plot(x='dteday', y='cnt', figsize=(10,4)) | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
ๆฅ็ๆฏๅคฉ็้ช่กๆฐๆฎ๏ผๅฏนๆฏ2011ๅนดๅ2012ๅนด | day_rides = pd.read_csv('Bike-Sharing-Dataset/day.csv')
day_rides = day_rides.set_index(['dteday'])
day_rides.loc['2011-08-01':'2011-12-31'].plot(y='cnt', figsize=(10,4))
day_rides.loc['2012-08-01':'2012-12-31'].plot(y='cnt', figsize=(10,4)) | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
่ๆๅ้๏ผๅๅ้๏ผ
ไธ้ขๆฏไธไบๅ็ฑปๅ้๏ผไพๅฆๅญฃ่ใๅคฉๆฐใๆไปฝใ่ฆๅจๆไปฌ็ๆจกๅไธญๅ
ๅซ่ฟไบๆฐๆฎ๏ผๆไปฌ้่ฆๅๅปบไบ่ฟๅถ่ๆๅ้ใ็จ Pandas ๅบไธญ็ย get_dummies() ๅฐฑๅฏไปฅ่ฝปๆพๅฎ็ฐใ | dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']
for each in dummy_fields:
dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)
rides = pd.concat([rides, dummies], axis=1)
fields_to_drop = ['instant', 'dteday', 'season', 'weathersit',
'weekday', 'atemp', 'mnth... | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
่ฐๆด็ฎๆ ๅ้
ไธบไบๆด่ฝปๆพๅฐ่ฎญ็ป็ฝ็ป๏ผๆไปฌๅฐๅฏนๆฏไธช่ฟ็ปญๅ้ๆ ๅๅ๏ผๅณ่ฝฌๆขๅ่ฐๆดๅ้๏ผไฝฟๅฎไปฌ็ๅๅผไธบ 0๏ผๆ ๅๅทฎไธบ 1ใ
ๆไปฌไผไฟๅญๆข็ฎๅ ๅญ๏ผไปฅไพฟๅฝๆไปฌไฝฟ็จ็ฝ็ป่ฟ่ก้ขๆตๆถๅฏไปฅ่ฟๅๆฐๆฎใ
ๅฐๆฐๆฎๆๅไธบ่ฎญ็ปใๆต่ฏๅ้ช่ฏๆฐๆฎ้
ๆไปฌๅฐๅคง็บฆๆๅ 21 ๅคฉ็ๆฐๆฎไฟๅญไธบๆต่ฏๆฐๆฎ้๏ผ่ฟไบๆฐๆฎ้ไผๅจ่ฎญ็ปๅฎ็ฝ็ปๅไฝฟ็จใๆไปฌๅฐไฝฟ็จ่ฏฅๆฐๆฎ้่ฟ่ก้ขๆต๏ผๅนถไธๅฎ้
็้ช่กไบบๆฐ่ฟ่กๅฏนๆฏใ | # Save data for approximately the last 21 days
test_data = data[-21*24:]
# Now remove the test data from the data set
data = data[:-21*24]
# Separate the data into features and targets
target_fields = ['cnt', 'casual', 'registered']
features, targets = data.drop(target_fields, axis=1), data[target_fields]
test_feat... | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
ๆไปฌๅฐๆฐๆฎๆๅไธบไธคไธชๆฐๆฎ้๏ผไธไธช็จไฝ่ฎญ็ป๏ผไธไธชๅจ็ฝ็ป่ฎญ็ปๅฎๅ็จๆฅ้ช่ฏ็ฝ็ปใๅ ไธบๆฐๆฎๆฏๆๆถ้ดๅบๅ็นๆง็๏ผๆไปฅๆไปฌ็จๅๅฒๆฐๆฎ่ฟ่ก่ฎญ็ป๏ผ็ถๅๅฐ่ฏ้ขๆตๆชๆฅๆฐๆฎ๏ผ้ช่ฏๆฐๆฎ้๏ผใ | # Hold out the last 60 days or so of the remaining data as a validation set
train_features, train_targets = features[:-60*24], targets[:-60*24]
val_features, val_targets = features[-60*24:], targets[-60*24:] | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
ๅผๅงๆๅปบ็ฝ็ป
ไธ้ขไฝ ๅฐๆๅปบ่ชๅทฑ็็ฝ็ปใๆไปฌๅทฒ็ปๆๅปบๅฅฝ็ปๆๅๅๅไผ ้้จๅใไฝ ๅฐๅฎ็ฐ็ฝ็ป็ๅๅไผ ้้จๅใ่ฟ้่ฆ่ฎพ็ฝฎ่ถ
ๅๆฐ๏ผๅญฆไน ้็ใ้่ๅๅ
็ๆฐ้๏ผไปฅๅ่ฎญ็ปไผ ้ๆฐ้ใ
<img src="assets/neural_network.png" width=300px>
่ฏฅ็ฝ็ปๆไธคไธชๅฑ็บง๏ผไธไธช้่ๅฑๅไธไธช่พๅบๅฑใ้่ๅฑ็บงๅฐไฝฟ็จ S ๅๅฝๆฐไฝไธบๆฟๆดปๅฝๆฐใ่พๅบๅฑๅชๆไธไธช่็น๏ผ็จไบ้ๅฝ๏ผ่็น็่พๅบๅ่็น็่พๅ
ฅ็ธๅใๅณๆฟๆดปๅฝๆฐๆฏย $f(x)=x$ใ่ฟ็งๅฝๆฐ่ทๅพ่พๅ
ฅไฟกๅท๏ผๅนถ็ๆ่พๅบไฟกๅท๏ผไฝๆฏไผ่่้ๅผ๏ผ็งฐไธบๆฟๆดปๅฝๆฐใๆไปฌๅฎๆ็ฝ็ป็ๆฏไธชๅฑ็บง๏ผๅนถ่ฎก็ฎๆฏไธช็ฅ็ปๅ
็่พๅบใไธไธชๅฑ็บง็ๆๆ่พๅบๅๆไธไธๅฑ็บง็ฅ็ปๅ
็่พๅ
ฅใ่ฟไธๆต็จๅซๅๅๅไผ ๆญ๏ผforward pro... |
class NeuralNetwork(object):
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
# Initialize w... | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
ๅๅ
ๆต่ฏ
่ฟ่ก่ฟไบๅๅ
ๆต่ฏ๏ผๆฃๆฅไฝ ็็ฝ็ปๅฎ็ฐๆฏๅฆๆญฃ็กฎใ่ฟๆ ทๅฏไปฅๅธฎๅฉไฝ ็กฎไฟ็ฝ็ปๅทฒๆญฃ็กฎๅฎ็ฐ๏ผ็ถๅๅๅผๅง่ฎญ็ป็ฝ็ปใ่ฟไบๆต่ฏๅฟ
้กปๆๅๆ่ฝ้่ฟๆญค้กน็ฎใ | import unittest
inputs = np.array([[0.5, -0.2, 0.1]])
targets = np.array([[0.4]])
test_w_i_h = np.array([[0.1, -0.2],
[0.4, 0.5],
[-0.3, 0.2]])
test_w_h_o = np.array([[0.3],
[-0.1]])
class TestMethods(unittest.TestCase):
##########
# Un... | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
่ฎญ็ป็ฝ็ป
็ฐๅจไฝ ๅฐ่ฎพ็ฝฎ็ฝ็ป็่ถ
ๅๆฐใ็ญ็ฅๆฏ่ฎพ็ฝฎ็่ถ
ๅๆฐไฝฟ่ฎญ็ป้ไธ็้่ฏฏๅพๅฐไฝๆฏๆฐๆฎไธไผ่ฟๆๅใๅฆๆ็ฝ็ป่ฎญ็ปๆถ้ดๅคช้ฟ๏ผๆ่
ๆๅคชๅค็้่่็น๏ผๅฏ่ฝๅฐฑไผ่ฟไบ้ๅฏน็นๅฎ่ฎญ็ป้๏ผๆ ๆณๆณๅๅฐ้ช่ฏๆฐๆฎ้ใๅณๅฝ่ฎญ็ป้็ๆๅคฑ้ไฝๆถ๏ผ้ช่ฏ้็ๆๅคฑๅฐๅผๅงๅขๅคงใ
ไฝ ่ฟๅฐ้็จ้ๆบๆขฏๅบฆไธ้ (SGD) ๆนๆณ่ฎญ็ป็ฝ็ปใๅฏนไบๆฏๆฌก่ฎญ็ป๏ผ้ฝ่ทๅ้ๆบๆ ทๆฌๆฐๆฎ๏ผ่ไธๆฏๆดไธชๆฐๆฎ้ใไธๆฎ้ๆขฏๅบฆไธ้็ธๆฏ๏ผ่ฎญ็ปๆฌกๆฐ่ฆๆดๅค๏ผไฝๆฏๆฏๆฌกๆถ้ดๆด็ญใ่ฟๆ ท็่ฏ๏ผ็ฝ็ป่ฎญ็ปๆ็ๆด้ซใ็จๅไฝ ๅฐ่ฏฆ็ปไบ่งฃ SGDใ
้ๆฉ่ฟญไปฃๆฌกๆฐ
ไนๅฐฑๆฏ่ฎญ็ป็ฝ็ปๆถไป่ฎญ็ปๆฐๆฎไธญๆฝๆ ท็ๆนๆฌกๆฐ้ใ่ฟญไปฃๆฌกๆฐ่ถๅค๏ผๆจกๅๅฐฑไธๆฐๆฎ่ถๆๅใไฝๆฏ๏ผๅฆๆ่ฟญไปฃๆฌกๆฐๅคชๅค๏ผๆจกๅๅฐฑๆ ๆณๅพๅฅฝๅฐๆณๅๅฐๅ
ถไปๆฐๆฎ๏ผ่ฟๅซๅ่ฟๆๅใไฝ ้่ฆ้ๆฉไธไธชไฝฟ่ฎญ็ปๆๅคฑๅพไฝ... | import sys
### Set the hyperparameters here ###
iterations = 4000
learning_rate = 0.5
hidden_nodes = 20
output_nodes = 1
N_i = train_features.shape[1]
network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)
losses = {'train':[], 'validation':[]}
for ii in range(iterations):
# Go through a random ... | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
ๆฃๆฅ้ขๆต็ปๆ
ไฝฟ็จๆต่ฏๆฐๆฎ็็็ฝ็ปๅฏนๆฐๆฎๅปบๆจก็ๆๆๅฆไฝใๅฆๆๅฎๅ
จ้ไบ๏ผ่ฏท็กฎไฟ็ฝ็ปไธญ็ๆฏๆญฅ้ฝๆญฃ็กฎๅฎ็ฐใ | fig, ax = plt.subplots(figsize=(8,4))
mean, std = scaled_features['cnt']
predictions = network.run(test_features).T*std + mean
ax.plot(predictions[0], label='Prediction')
ax.plot((test_targets['cnt']*std + mean).values, label='Data')
ax.set_xlim(right=len(predictions))
ax.legend()
dates = pd.to_datetime(rides.ix[test... | first-neural-network/Your_first_neural_network.ipynb | xaibeing/cn-deep-learning | mit |
Initialize dataset, print available variable names. In order to be able to access the data, save your API key in the file APIKEY and put it into the same folder where you run this notebook. | apikey = open('APIKEY').readlines()[0].strip()
dh = datahub_main(apikey)
ds = dataset('ecmwf_era5',dh,debug=True)
ds.variable_names()
# Choose location, variable
lon = 26
lat = 58
variable = '2_metre_temperature_surface'
d1 = ds.get_json_data_in_pandas(count=100000,**{'vars':'2_metre_temperature_surface','lon':lon,'... | api-examples/ERA5_tutorial.ipynb | planet-os/notebooks | mit |
Wind energy example
As a more advanced use case, let's try to analyse potential wind energy production in three different locations.
For this, we take wind speed at 100 m height, apply a simplified energy production curve to hourly data, and get a statistics for hourly and weekly average (wa) data. | def production_curve(wind_speed):
""" Production curve of a turbine/farm can be simplified as a
cube of wind speed, with production
starting from a particular wind speed 'v_cut_in'
getting maximum output power at wind speed 'v_rated'
production halted at very strong wind sp... | api-examples/ERA5_tutorial.ipynb | planet-os/notebooks | mit |
split_element
<b>split_element(func, in_stream, out_streams)</b>
<br>
<br>
where
<ol>
<li><b>func</b> is a function with an argument which is an element of a single input stream and that returns a list with one element for each out_stream. <i>func</i> may have additional keyword arguments and may also have a state.... | def simple_example_of_split_element():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Specify encapsulated functions
def f(v): return [v+100, v*2]
# Create agent with input stream x and output streams y, z.
split_element(func=f, in_stream=x, out_streams=[y,z])
... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Using Lambda Expressions
Lambda expressions in split_element can be convenient as shown in this example which is essentially the same as the previous one. | def example_of_split_element_with_lambda():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Create agent with input stream x and output streams y, z.
split_element(lambda v: [v+100, v*2], x, [y,z])
# Put test values in the input streams.
x.extend(list(range(5)))... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example of the decorator @split_e
The decorator <b>@split_e</b> operates the same as split_element, except that the agent is created by calling the decorated function.
<br>
Compare this example with the first example which used <i>split_element</i>. The two examples are almost identical. The difference is in the way th... | def simple_example_of_split_e():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Specify encapsulated functions
@split_e
def f(v): return [v+100, v*2]
# Create agent with input stream x and output streams y, z.
f(in_stream=x, out_streams=[y,z])
# Put te... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example of functional forms
You may want to use a function that returns the streams resulting from a split instead of having the streams specified in out_streams, i.e. you may prefer to write:
<br>
<br>
a, b, c = h(u)
<br>
<br>
where <i>u</i> is a stream that is split into streams <i>a</i>, <i>b</i>, and <i>c</i>,
ins... | def simple_example_of_functional_form():
# ------------------------------------------------------
# Specifying a functional form
# The functional form takes a single input stream and returns
# three streams.
def h(w):
# Specify streams
x = Stream('x')
y = Stream('y')
... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example with keyword arguments
This example shows how to pass keyword arguments to <i>split_element</i>. In the example, <i>addend</i> and <i>multiplicand</i> are arguments of <i>f</i> the encapsulated function, and these arguments are passed as keyword arguments to <i>split_element</i>. | def example_of_split_element_with_keyword_args():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Specify encapsulated functions
def f(v, addend, multiplicand):
return [v+addend, v*multiplicand]
# Create agent with input stream x and output streams y, z.
sp... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Split element with state
This example shows how to create an agent with state. The encapsulated function takes two arguments --- an element of the input stream and a <b>state</b> --- and it returns two values: a list of elements corresponding to the output streams and the <b>next state</b>. The function may have additi... | def example_of_split_element_with_state():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Specify encapsulated functions
def f(v, state):
next_state = state+1
return ([v+state, v*state], next_state)
# Create agent with input stream x and output streams ... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example with state and keyword arguments
This example shows an encapsulated function with a state and an argument called <i>state_increment</i> which is passed as a keyword argument to <i>split_element</i>. | def example_of_split_element_with_state_and_keyword_args():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Specify encapsulated functions
def f(v, state, state_increment):
next_state = state + state_increment
return ([v+state, v*state], next_state)
# Cr... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example with StreamArray and NumPy arrays | import numpy as np
from IoTPy.core.stream import StreamArray
def example_of_split_element_with_stream_array():
# Specify streams
x = StreamArray('x')
y = StreamArray('y')
z = StreamArray('z')
# Specify encapsulated functions
def f(v, addend, multiplier):
return [v+addend, v*multiplier]... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example of split list
split_list is the same as split_element except that the encapsulated function operates on a <i>list</i> of elements of the input stream rather than on a single element. Operating on a list can be more efficient than operating sequentially on each of the elements of the list. This is especially imp... | def example_of_split_list():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Specify encapsulated functions
def f(lst, addend, multiplier):
return ([v+addend for v in lst], [v*multiplier for v in lst])
# Create agent with input stream x and output streams y, z.
... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example of split list with arrays
In this example, the encapsulated function <i>f</i> operates on an array <i>a</i> which is a segment of the input stream array, <i>x</i>. The operations in <i>f</i> are array operations (not list operations). For example, the result of <i>a * multiplier </i> is specified by numpy multi... | def example_of_split_list_with_arrays():
# Specify streams
x = StreamArray('x')
y = StreamArray('y')
z = StreamArray('z')
# Specify encapsulated functions
def f(a, addend, multiplier):
# a is an array
# return two arrays.
return (a + addend, a * multiplier)
# Create... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Test of unzip
unzip is the opposite of zip_stream.
<br>
<br>
An element of the input stream is a list or tuple whose length is the same as the number of output streams; the <i>j</i>-th element of the list is placed in the <i>j</i>-th output stream.
<br>
<br>
In this example, when the unzip agent receives the triple (1,... | def simple_test_unzip():
# Specify streams
w = Stream('w')
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Create agent with input stream x and output streams y, z.
unzip(in_stream=w, out_streams=[x,y,z])
# Put test values in the input streams.
w.extend([(1, 10, 100), (2, 20,... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example of separate
<b>separate</b> is the opposite of <b>mix</b>.
<br>
The elements of the input stream are pairs (index, value). When a pair <i>(i,v)</i> arrives on the input stream the value <i>v</i> is appended to the <i>i</i>-th output stream.
<br>
<br>
In this example, when (0, 1) and (2, 100) arrive on the input... | def simple_test_separate():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
w = Stream('w')
# Create agent with input stream x and output streams y, z.
separate(in_stream=x, out_streams=[y,z,w])
# Put test values in the input streams.
x.extend([(0,1), (2, 100)... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example of separate with stream arrays.
This is the same example as the previous case. The only difference is that since the elements of the input stream are pairs, the dimension of <i>x</i> is 2. | def test_separate_with_stream_array():
# Specify streams
x = StreamArray('x', dimension=2)
y = StreamArray('y')
z = StreamArray('z')
# Create agent with input stream x and output streams y, z.
separate(in_stream=x, out_streams=[y,z])
# Put test values in the input streams.
x.extend... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example of split window
The input stream is broken up into windows. In this example, with <i>window_size</i>=2 and <i>step_size</i>=2, the sequence of windows are <i>x[0, 1], x[2, 3], x[4, 5], ....</i>.
<br>
<br>
The encapsulated function operates on a window and returns <i>n</i> values where <i>n</i> is the number of ... | def simple_example_of_split_window():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Specify encapsulated functions
def f(window): return (max(window), min(window))
# Create agent with input stream x and output streams y, z.
split_window(func=f, in_stream=x, out_st... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example that illustrates zip followed by unzip is the identity.
zip_stream followed by unzip returns the initial streams. | from IoTPy.agent_types.merge import zip_stream
def example_zip_plus_unzip():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
u = Stream('u')
v = Stream('v')
# Create agents
zip_stream(in_streams=[x,y], out_stream=z)
unzip(in_stream=z, out_streams=[u,v])
# ... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example that illustrates that mix followed by separate is the identity. | from IoTPy.agent_types.merge import mix
def example_mix_plus_separate():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
u = Stream('u')
v = Stream('v')
# Create agents
mix(in_streams=[x,y], out_stream=z)
separate(in_stream=z, out_streams=[u,v])
# Put test... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Simple example of timed_unzip
An element of the input stream is a pair (timestamp, list). The sequence of timestamps must be increasing. The list has length n where n is the number of output streams. The m-th element of the list is the value of the m-th output stream associated with that timestamp. For example, if an e... | def test_timed_unzip():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
# Create agent with input stream x and output streams y, z.
timed_unzip(in_stream=x, out_streams=[y,z])
# Put test values in the input streams.
x.extend([(1, ["A", None]), (5, ["B", "a"]), (7,... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Example that illustrates that timed_zip followed by timed_unzip is the identity. | from IoTPy.agent_types.merge import timed_zip
def test_timed_zip_plus_timed_unzip():
# Specify streams
x = Stream('x')
y = Stream('y')
z = Stream('z')
u = Stream('u')
v = Stream('v')
# Create agents
timed_zip(in_streams=[x,y], out_stream=z)
timed_unzip(in_stream=z, out_streams=[u,v]... | examples/ExamplesOfSplit.ipynb | AssembleSoftware/IoTPy | bsd-3-clause |
Let's continue with the necessary imports: | import calendar
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx
from scipy import stats
import pandas as pd
import statsmodels.api as sm
from typecheck import typecheck
import sys
sys.path.append("../lib") | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
High-level plotting
For our purposes, we will define high-level plotting as anything in the matplotlib world which:
Utilizes matplotlib APIs under the covers
In order to accomplish complicated plotting tasks
And provide an API for those tasks to the user, to employ either in conjunction with matplotlib directly, or in... | from matplotlib import sankey
fig = plt.figure(figsize=(18, 22))
ax = fig.add_subplot(
1, 1, 1,
xticks=[], yticks=[])
ax.set_title(("Rankine Power Cycle\nExample 8.6 from Moran and Shapiro\n"
"$Fundamentals \ of \ Engineering \ Thermodynamics$, "
"6th ed., 2008"),
fonts... | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
A more common example is code you would write in your own projects. For instance, if you recall from the notebook covering the matplotlib APIs, we created a module to demonstrate the object-oriented API for programmatic workflows. That little module is a perfect example of high-level plotting with matplotlib.
NetworkX
... | import lanl
from networkx.drawing.nx_agraph import graphviz_layout
# Set up the plot's figure instance
plt.figure(figsize=(14,14))
# Generate the data graph structure representing the route relationships
G = lanl.get_routes_graph(debug=True)
# Perform the high-level plotting operations in NetworkX
pos = graphviz_lay... | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Like we saw when creating a graph that would neatly render the matplotlib module layout in accordance with the philosophy of its architecture, Aric Hagberg had to do something similar when rendering the Internet routes from Los Alamos National Laboratory. We've put this code in the lanl module for this notebook repo; i... | graphviz_layout | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Taking a look at that file, we can see that graphviz_layout wraps the pygraphviz_layout function. From there, we see that NetworkX is converting pygraphviz's node data structure to something general that can be used for all backends. We're already several layers deep in NetworkX's high-level API internals.
Next, let's ... | nx.draw | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Now we're getting close to matplotlib! The nx_pylab module's draw function makes direct use of matplotlib.pyplot in order to:
Get the current figure from pyplot
Or, if it exists, from the axes object
Hold and un-hold the matplotlib figures
Call a matplotlib draw function
It also makes a subsequent call to the Network... | from scipy.stats import norm, rayleigh
a = rayleigh.rvs(loc=5, scale=2, size=1000) + 1
b = rayleigh.rvs(loc=5, scale=2, size=1000)
c = rayleigh.rvs(loc=5, scale=2, size=1000) - 1 | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Create a Pandas data structure instance: | data = pd.DataFrame({"a": a, "b": b, "c": c}, columns=["a", "b", "c"]) | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Let's take a look at a histogram plot of this data: | axes = data.plot(kind="hist", stacked=True, bins=30, figsize=(16, 8))
axes.set_title("Fabricated Wind Speed Data", fontsize=20)
axes.set_xlabel("Mean Hourly Wind Speed (km/hr)", fontsize=16)
_ = axes.set_ylabel("Velocity Counts", fontsize=16) | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
So what's going on here? Well, if you take a dive into the Pandas codebase, you'll find that there are wrappers in pandas.tools.plotting that do a bunch of work under the covers to make plotting from the DataFrame object an exercise in simplicity. In particular, look at plotting.plot_frame and plotting._plot.
Grammar o... | from bokeh.plotting import output_notebook
output_notebook() | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
The Bokeh example has been saved to this notebook's repo (and modified slightly); you can load it up with the following: | import burtin | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Since this series of notebooks are focused on matplotlib (and not Bokeh!), we won't go into too much detail, but it is definitely worth mentioning that Bokeh provides a matplotlib compatibility layer. It doesn't cover 100% of all matplotlib API usage a given project may entail, but enough so that one should be able to ... | import ggplot
from ggplot import components, geoms, scales, stats
from ggplot import exampledata | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Here's a quick look at some movie data collected over the 20th century: | data = exampledata.movies
aesthetics = components.aes(x='year', y='budget')
(ggplot.ggplot(aesthetics, data=data) +
stats.stat_smooth(span=.15, color='red', se=True) +
geoms.ggtitle("Movie Budgets over Time") +
geoms.xlab("Year") +
geoms.ylab("Dollars")) | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Views of data collected on the cuts and qualities of diamonds: | data = exampledata.diamonds
aesthetics = components.aes(x='price', fill='cut')
(ggplot.ggplot(aesthetics, data=data) +
geoms.geom_density(alpha=0.25) +
geoms.facet_wrap("clarity")) | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
ggplot offers some nice color options that, when used effectively, can be more revealing of data in hidden relationships. The following are examples of ggplot's support for ColorBrewer: | aesthetics = components.aes(x='price', y='carat', color='clarity')
plot = ggplot.ggplot(aesthetics, data=data)
point = geoms.geom_point(alpha=0.6)
(plot +
point +
scales.scale_color_brewer(type='qual', palette='Set1'))
(plot +
point +
scales.scale_color_brewer(type='seq', palette='YlOrRd'))
(plot +
point +
scal... | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
There is a great deal more to explore with ggplot. Be sure to check out:
* the main site
* the docs
* the Github repo
New styles in matplotlib
matplotlib has recently added support for ggplot styling. Let's contrast it with the defaults. First, import the demo code: | import mplggplot | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Now let's take a look at the default styling of some plots: | figure, axes = plt.subplots(ncols=2, nrows=2, figsize=(10, 10))
mplggplot.demo(axes)
plt.show() | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Though we are looking at the ggplot style here, there are actually several styles to choose from. Here's the list of the available ones: | plt.style.available | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Now we'll select "ggplot" and re-render our demo plots: | plt.style.use('bmh')
figure, axes = plt.subplots(ncols=2, nrows=2, figsize=(10, 10))
mplggplot.demo(axes)
plt.show() | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
It's not really a wonder that ggplot has so much appeal in the community :-)
Seaborn
As noted, the development of seaborn has been greatly inspired by the Grammar of Graphics and R's ggplot in particular. Here's what the notes say on the seaborn site:
<blockquote>
Seaborn aims to make visualization a central part of ex... | import seaborn as sns
pallete_name = "husl"
colors = sns.color_palette(pallete_name, 8)
colors.reverse()
cmap = mpl.colors.LinearSegmentedColormap.from_list(pallete_name, colors) | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Scatter Plot Matrices
Scatter plots offer a unique view on multivariate data sets, allowing one to see what sorts of correlations exist between variables, if any. Here is the famous "iris" data set in a seaborn pairplot scatter plot matrix which focuses on pair-wise relationships: | sns.set()
data_frame = sns.load_dataset("iris")
_ = sns.pairplot(data_frame, hue="species", size=2.5) | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Facet Grids
When you want to split up a data set by one or more variables, and then group subplots of these separated variables, you probably want to use a facet grid. Another use case is for examining repeated runs of an experiment to reveal potentially conditional relationships between variables. Below is a concocted... | import seademo
sns.set(style="ticks")
data = seademo.get_data_set()
grid = sns.FacetGrid(data, col="walk", hue="walk", col_wrap=5, size=2)
grid.map(plt.axhline, y=0, ls=":", c=".5")
grid.map(plt.plot, "step", "position", marker="o", ms=4)
grid.set(xticks=np.arange(5), yticks=[-3, 3],
xlim=(-.5, 4.5), ylim=(... | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Violin Plots
Violin plots are similar to box plots (the latter of which we will see more use of below in the "Data Analysis" section). Where box plots display variation in samples of a statistical population with different parts of the box indicating the degree of spread (among other things), the violin plot provide in... | sns.set(style="whitegrid")
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
used_networks = [1, 3, 4, 5, 6, 7, 8, 11, 12, 13, 16, 17]
level_values = df.columns.get_level_values("network").astype(int)
used_columns = level_values.isin(used_networks)
df = df.loc[:, used_columns]
corr_df = df.corr()... | github/MasteringMatplotlib/mmpl-high-level.ipynb | moonbury/pythonanywhere | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.