markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
myHDL Implementation | @block
def DAC_1Bit(x, y, clk, rst):
"""
A 1bit SigmaDelta DAC based on
http://old.myhdl.org/doku.php/projects:dsx1000
using a Instantiation approach
Inputs:
x (2's): Input Digital word to be translated to PDM ouput
-----------------------------
clk (bool): system clock inp... | myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | Peeker.clear()
clk, rst=[Signal(bool(0)) for i in range(2)]
Peeker(clk, 'clk'); Peeker(rst, 'rst')
x=Signal(intbv(0, min=MinV, max=MaxV)); Peeker(x, 'x')
y=Signal(bool(0)); Peeker(y, 'y')
DUT=DAC_1Bit(x, y, clk, rst)
def DAC_TB():
@always(delay(1)) ## delay in nano seconds
def clkGen():
clk.nex... | myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL to Verilog | DUT.convert()
VerilogTextReader('DAC_1Bit'); | myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
2. Extract just data from the year 1980 and beyond from the loaded cube | tcoord = cube.coord('time')
def since_1980(cell):
return tcoord.units.num2date(cell.point).year >= 1980
tcon = iris.Constraint(time=since_1980)
cube = cube.extract(tcon)
tcoord = cube.coord('time')
print(tcoord.units.num2date(tcoord.points.min()))
print(tcoord.units.num2date(tcoord.points.max())) | course_content/solutions/iris_exercise_3.ipynb | ajdawson/python_for_climate_scientists | gpl-3.0 |
3. Define a function which takes a coordinate and a single time point as arguments, and returns the decade. For example, your function should return 2010 for the following:
time = iris.coords.DimCoord([10], 'time', units='days since 2018-01-01')
print your_decade_function(time, time.points[0]) | def get_decade(coord, point):
year = coord.units.num2date(point).year
return (year // 10) * 10
time = iris.coords.DimCoord([10], 'time', units='days since 2018-01-01')
print(get_decade(time, time.points[0])) | course_content/solutions/iris_exercise_3.ipynb | ajdawson/python_for_climate_scientists | gpl-3.0 |
4. Add a "decade" coordinate to the loaded cube using your function and the coord categorisation module | import iris.coord_categorisation as coord_cat
coord_cat.add_categorised_coord(cube, 'decade', 'time', get_decade)
print(cube.coord('decade')) | course_content/solutions/iris_exercise_3.ipynb | ajdawson/python_for_climate_scientists | gpl-3.0 |
5. Calculate the decadal means cube for this scenario | import iris.analysis
cube = cube.aggregated_by('decade', iris.analysis.MEAN)
print(cube) | course_content/solutions/iris_exercise_3.ipynb | ajdawson/python_for_climate_scientists | gpl-3.0 |
6. Create a figure with 3 rows and 4 columns displaying the decadal means, with the decade displayed prominently in each axes' title (hint: the slices or slices_over method of the cube will be helpful, especially combined with the built-in enumerate function in a for-loop) | import matplotlib.pyplot as plt
import iris.plot as iplt
plt.figure(figsize=(12, 6))
plt.suptitle('Decadal means for the A1B scenario')
for i, decade_cube in enumerate(cube.slices(['latitude', 'longitude'])):
plt.subplot(3, 4, i+1)
iplt.contourf(decade_cube, 20, cmap='viridis')
plt.title('{}'.format(decad... | course_content/solutions/iris_exercise_3.ipynb | ajdawson/python_for_climate_scientists | gpl-3.0 |
1. Partition data | # data is taken from kaggle.com/c/talkingdata-adtracking-fraud-detection
input_file = '../data/train_sample.csv'
output_dir = "../data/partitioned"
def partition_by(df, column, output_dir):
directory = f"{output_dir}/{column}"
if not os.path.exists(directory):
os.makedirs(directory)
df.groupby(colu... | automated-feature-engineering-selection/notebooks/3-featuretools-scale.ipynb | alexandrnikitin/workshops | mit |
2. Create distributed EntitySets | input_path = '../data/partitioned/app'
dtypes = {
'ip': 'uint32',
'app': 'uint16',
'device': 'uint16',
'os': 'uint16',
'channel': 'uint16',
'is_attributed': 'uint8'
}
to_read = ['app', 'device', 'os', 'channel', 'is_attributed', 'click_time']
to_parse = ['click_time']
filenames = glob(f"{input... | automated-feature-engineering-selection/notebooks/3-featuretools-scale.ipynb | alexandrnikitin/workshops | mit |
3. Calculate feature matrices and definitions | def calc_feature_matrix(es, entity_id, cutoff_time):
feature_matrix, feature_defs = ft.dfs(
entityset=es,
target_entity=entity_id,
cutoff_time=cutoff_time,
training_window=ft.Timedelta("3 days"),
max_depth=3
)
return feature_matrix, feature_defs
# For the sake of si... | automated-feature-engineering-selection/notebooks/3-featuretools-scale.ipynb | alexandrnikitin/workshops | mit |
4. Compute the distributed features | out = feature_matrices.compute()
_, feature_defs = out[0]
feature_matrices = list(map(list, zip(*out)))[0]
feature_matrix = pd.concat(feature_matrices)
feature_defs
feature_matrix | automated-feature-engineering-selection/notebooks/3-featuretools-scale.ipynb | alexandrnikitin/workshops | mit |
Challenge 1 | model = sm.OLS(y, X['Intercept'])
fit = model.fit()
fit.summary() | Projects/Challenges/challenge_set_5_prashant.ipynb | ptpro3/ptpro3.github.io | mit |
This model is representing the null hypothesis. | records = range(89)
plt.scatter(records, y, color='g')
plt.scatter(records, fit.predict(X['Intercept']))
plt.hist((y['DomesticTotalGross'] - fit.predict(X['Intercept']))); | Projects/Challenges/challenge_set_5_prashant.ipynb | ptpro3/ptpro3.github.io | mit |
Challenge 2 | model = sm.OLS(y, X[['Intercept','Budget']])
fit = model.fit()
fit.summary()
plt.scatter(X['Budget'], y, color='g')
plt.scatter(X['Budget'], fit.predict(X[['Intercept','Budget']]))
plt.scatter(X['Budget'], fit.predict(X[['Intercept','Budget']]) - y['DomesticTotalGross']) | Projects/Challenges/challenge_set_5_prashant.ipynb | ptpro3/ptpro3.github.io | mit |
For higher budget, higher grossing movies there is some spread in the data and the model's residuals are higher
Challenge 3 | y3, X3 = patsy.dmatrices('DomesticTotalGross ~ Rating', data=df, return_type="dataframe")
X3.head()
model = sm.OLS(y3, X3)
fit = model.fit()
fit.summary()
records3 = range(100)
plt.scatter(records3, y3, color='g')
plt.scatter(records3, fit.predict(X3))
plt.hist((y3['DomesticTotalGross'] - fit.predict(X3))); | Projects/Challenges/challenge_set_5_prashant.ipynb | ptpro3/ptpro3.github.io | mit |
Here, the model is using the 'rating' to predict Domestic gross. Since there's 4 ratings, it's predicting one of 4 domestic gross values.
Challenge 4 | y4, X4 = patsy.dmatrices('DomesticTotalGross ~ Budget + Runtime + Rating', data=df, return_type="dataframe")
X4.head()
model = sm.OLS(y4, X4)
fit = model.fit()
fit.summary()
plt.scatter(records, y4, color='g')
plt.scatter(records, fit.predict(X4)) | Projects/Challenges/challenge_set_5_prashant.ipynb | ptpro3/ptpro3.github.io | mit |
Challenge 5 | X_train, X_test, y_train, y_test = train_test_split(X4, y4, test_size=0.25)
y_test.shape
model = sm.OLS(y_train, X_train)
fit = model.fit()
fit.summary()
records5 = range(23)
plt.scatter(records5, y_test, color='g')
plt.scatter(records5, fit.predict(X_test)) | Projects/Challenges/challenge_set_5_prashant.ipynb | ptpro3/ptpro3.github.io | mit |
1. Eksplorasi Awal Data - Advertising (6 poin) | df = pd.read_csv('https://github.com/aliakbars/uai-ai/raw/master/datasets/advertising.csv', index_col=0) | scripts/tugas1b.ipynb | aliakbars/uai-ai | mit |
Soal 1.1.a (1 poin)
Laporkan deskripsi dari Advertising dataset dengan menggunakan metode dari Pandas!
Soal 1.1.b (2 poin)
Berapa nilai sales paling rendah dan nilai sales paling tinggi dari data yang Anda miliki? Berapa ribu dollar uang yang dihabiskan untuk membayar biaya iklan di TV, radio, dan newspaper untuk produ... | def load_file(url):
filename = url.split('/')[-1]
with open(filename, 'wb') as f:
resp = requests.get(url)
f.write(resp.content)
return np.load(filename)
X = load_file('https://github.com/aliakbars/uai-ai/raw/master/datasets/food.npy')
y = load_file('https://github.com/aliakbars/uai-ai/raw/... | scripts/tugas1b.ipynb | aliakbars/uai-ai | mit |
Load the data from our JSON file.
The data is stored as a dictionary of dictionaries in the json file. We store it that way beacause it's easy to add data to the existing master data file. Also, I haven't figured out how to get it in a database yet. | with open('../pipeline/data/Day90ApartmentData.json') as f:
my_dict1 = json.load(f)
with open('../pipeline/data/ProcessedDay90ApartmentData.json') as g:
my_dict2 = json.load(g)
dframe1 = DataFrame(my_dict1)
dframe1 = dframe1.T
dframe1 = dframe1[['content', 'laundry', 'price', 'dog', 'bed',
'bath', 'feet', ... | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
Clean up the data a bit
Right now the 'shared' and 'split' are included in number of bathrooms. If I were to convert that to a number I would consider a shared/split bathroom to be half or 0.5 of a bathroom. | dframe.bath = dframe.bath.replace('shared',0.5)
dframe.bath = dframe.bath.replace('split',0.5)
dframe.smoking = dframe.smoking.replace(np.nan, 'smoking')
dframe.furnished = dframe.furnished.replace(np.nan,'not furnished')
dframe.wheelchair = dframe.wheelchair.replace(np.nan, 'not wheelchair accessible')
dframe.describ... | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
It looks like Portland!!!
Let's cluster the data. Start by creating a list of [['lat','long'], ...] | XYdf = dframe[dframe.lat > 45.4][dframe.lat < 45.6][dframe.long < -122.0][dframe.long > -123.5]
data = [[XYdf['lat'][i],XYdf['long'][i]] for i in XYdf.index]
| analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
We'll use K Means Clustering because that's the clustering method I recently learned in class! There may be others that work better, but this is the tool that I know | from sklearn.cluster import KMeans
km = KMeans(n_clusters=40)
km.fit(data)
neighborhoods = km.cluster_centers_
%pylab inline
figure(1,figsize=(20,12))
plot([row[1] for row in data],[row[0] for row in data],'b.')
for i in km.cluster_centers_:
plot(i[1],i[0], 'g*',ms=25)
'''Note to Riley: come back and make it lo... | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
We chose our neighborhoods!
I've found that every once in a while the centers end up in different points, but are fairly consistant. Now let's process our data points and figure out where the closest neighborhood center is to it! | neighborhoods = neighborhoods.tolist()
for i in enumerate(neighborhoods):
i[1].append(i[0])
print neighborhoods | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
Create a function that will label each point with a number coresponding to it's neighborhood | def clusterer(X, Y,neighborhoods):
neighbors = []
for i in neighborhoods:
distance = ((i[0]-X)**2 + (i[1]-Y)**2)
neighbors.append(distance)
closest = min(neighbors)
return neighbors.index(closest)
neighborhoodlist = []
for i in dframe.index:
neighborhoodlist.append(clusterer(dframe[... | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
Here's the new Part. We're breaking out the neighborhood values into their own columns. Now the algorithms can read them as categorical data rather than continuous data. | from sklearn import preprocessing
def CategoricalToBinary(dframe,column_name):
le = preprocessing.LabelEncoder()
listy = le.fit_transform(dframe[column_name])
dframe[column_name] = listy
unique = dframe[column_name].unique()
serieslist = [list() for _ in xrange(len(unique))]
for column... | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
Ok, lets put it through Decision Tree!
What about Random Forest? | from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score
reg = RandomForestRegressor()
reg = reg.fit(features_train, price_train)
forest_pred = reg.predict(features_test)
forest_pred = np.array([[item] for item in forest_pred])
print r2_score(forest_pred, price_test)
plt.scatter(forest... | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
Wow! up to .87! That's our best yet! What if we add more trees??? | reg = RandomForestRegressor(n_estimators = 100)
reg = reg.fit(features_train, price_train)
forest_pred = reg.predict(features_test)
forest_pred = np.array([[item] for item in forest_pred])
print r2_score(forest_pred, price_test)
print plt.scatter(pred,price_test)
from sklearn.tree import DecisionTreeRegressor
reg = ... | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
Up to .88!
So what is our goal now? I'd like to see if adjusting the number of neighborhoods increases the accuracy. same for the affect with the number of trees | def neighborhood_optimizer(dframe,neighborhood_number_range, counter_num):
XYdf = dframe[dframe.lat > 45.4][dframe.lat < 45.6][dframe.long < -122.0][dframe.long > -123.5]
data = [[XYdf['lat'][i],XYdf['long'][i]] for i in XYdf.index]
r2_dict = []
for i in neighborhood_number_range:
counter = coun... | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
Looks like the optimum is right around 10 or 11, and then starts to drop off. Let's get a little more granular and look at a smaller range | neighborhood_number_range = [i for _,i in enumerate(range(7,15))]
neighborhood_number_range
r2_dict = neighborhood_optimizer(dframe,neighborhood_number_range,10)
print r2_dict
plt.scatter([x[0] for x in r2_dict],[x[1] for x in r2_dict]) | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
Trying a few times, it looks like 10, 11 and 12 get the best results at ~.85. Of course, we'll need to redo some of these optomizations after we properly process our data. Hopefully we'll see some more consistency then too. | r2_dict = neighborhood_optimizer(dframe,[10,11,12],25) | analysis/Munge-Copy2.ipynb | rileyrustad/pdxapartmentfinder | mit |
Creating an experiment object
First, we start with generating a pynoddy experiment object. The experiment class inherits all the methods from the base pynoddy.history class and we can directly import the Gippsland Basin model that we want to analyse into the object: | reload(pynoddy.experiment)
# the model itself is now part of the repository, in the examples directory:
history_file = os.path.join(repo_path, "examples/GBasin_Ve1_V4_b.his")
gipps_topo_ex = pynoddy.experiment.Experiment(history = history_file) | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Some basic information about the model can be obtained with: | gipps_topo_ex.info() | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
We can have a quick look at the model in a section view (note that Noddy is now executed in the background when required - and the output automatically generated in the required resolution): | gipps_topo_ex.plot_section('y') | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
The base plot is not very useful - but we can create a section plot with a define vertical exaggeration (keyword ve) and plot the colorbar in horizontal orientation: | # gipps_topo_ex.determine_model_stratigraphy()
gipps_topo_ex.plot_section('x', ve = 5, position = 'centre',
cmap = 'YlOrRd',
title = '',
colorbar = False)
gipps_topo_ex.plot_section('y', position = 100, ve = 5.,
cmap = 'YlOrRd',
title = '',... | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Note: The names of the model stratigraphy (colorbar labels) are unfortunately not defined correctly in the input file - we need to fix that, then we should get useful labels, as well!
Loading parameters ranges from file
We now need to define the parameter ranges. This step can either be done through explicit definition... | reload(pynoddy.experiment)
# the model itself is now part of the repository, in the examples directory:
history_file = os.path.join(repo_path, "examples/GBasin_Ve1_V4_b.his")
gipps_topo_ex = pynoddy.experiment.Experiment(history = history_file)
gipps_topo_ex.load_parameter_file(os.path.join(repo_path, "examples/gipps_... | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Generating random perturbations of the model
Before generating random prerturbations, we should now store the base version so that we can always revert to it at a later stage: | gipps_topo_ex.freeze() | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
For a reproducible experiment, we can also set the random seed: | gipps_topo_ex.set_random_seed(12345) | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
And now, let's perturb the model: | gipps_topo_ex.random_perturbation() | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Let's see what happened: we can compare the new model to the base model as we stored it before: | fig = plt.figure(figsize = (12,6))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
gipps_topo_ex.plot_section(ax = ax1, direction = 'x', model_type = "base",
colorbar = False, title = "", ve = 5.)
gipps_topo_ex.plot_section(ax = ax2, direction = 'x', colorbar = False,
... | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
...and another perturbation: | gipps_topo_ex.random_perturbation()
fig = plt.figure(figsize = (12,6))
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
gipps_topo_ex.plot_section(ax = ax1, direction = 'x', model_type = "base",
colorbar = False, title = "", ve = 5.)
gipps_topo_ex.plot_sectio... | docs/notebooks/Gippsland-topology.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Detrended Fluctuation Analysis is a method which allows to measure self-affinity properties of time series. It is claimed to be very roboust method for Hurst exponent estimation even for nonstationary signals. It consists of three main steps:
1) Cumulative sum calculation;
2) Detrending time series in windows $\Delta n... | def calc_rms(x, scale):
"""
Root Mean Square in windows with linear detrending.
Args:
-----
*x* : numpy.array
one dimensional data vector
*scale* : int
length of the window in which RMS will be calculaed
Returns:
--------
*rms* : numpy.array
RMS dat... | dfa/notebook/dfa_simulations.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Firstly let's just test our implemetation on randomly generated power-law data. | n = 2**12
dfa_alpha = 0.7
x = power_law_noise(n, dfa_alpha)
scales, fluct, esta = dfa(x, show=1)
print("DFA exponent {}".format(esta)) | dfa/notebook/dfa_simulations.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
We got acceptable estimation of the initial value of $\alpha$=0.7.
Simulation 1: artifacts
Now we are ready to perform the first simulation. In biomedical signals (EEG in particular) many high amplitude artifacts appear. Those can be caused by body movements, eyes blinking or just by recording device. Typically, in mos... | mr = ss.morlet(100, w=0.9, s=0.3)
plt.plot(mr.real) | dfa/notebook/dfa_simulations.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Artifacts look very often as a big unexpected peak with much higher amplitude than the rest of the signal. I decided to model it as a Morlet wavelet with low frequency. I multiply part of the signal by that shape with some arbitrarly big amplitude.
The picture below shows an example of signal with artifact. | x = power_law_noise(n, dfa_alpha)
plt.figure(figsize=(9,7))
plt.subplot(211)
plt.plot(x)
plt.title("Original signal")
plt.ylim([-2.3,2.3])
ncut = 500
idx = 400
mr = ss.morlet(ncut, w=1, s=0.3)
x[idx:idx+ncut] *= 10*mr.real
plt.subplot(212)
plt.plot(x)
plt.ylim([-2.3,2.3])
plt.xlabel('time')
plt.title("Signal with artif... | dfa/notebook/dfa_simulations.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Now we perform bootstrapping, so in principle repeat such an operation Nrep times adding artifacts in random places with random amplitudes and lengths. | Nrep = 1000 # how many resamplings
x_down, x_top = 400, 3500 # range of artifacts beginnings
sig_amp, mu_amp = 3.5, 10 # amplitude parameters (to random Gauss generator)
sig_ncut, mu_ncut = 100, 500 # length of the artifact
dfavec = np.zeros(Nrep)
for i in range(Nrep):
if i%10==0: print(... | dfa/notebook/dfa_simulations.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
As a result we get a histogram with confidence level values marked by red dashed lines and actual value marked as a purple line. We see that we cannot reject a null-hypothesis that artifacts (those generated as above) don't have any impact on DFA exponent estimation. | alpha = 0.05
v1 = st.scoreatpercentile(dfavec, 0.5*alpha*100)
v2 = st.scoreatpercentile(dfavec, 100-0.5*alpha*100)
plt.figure(figsize=(9,6))
plt.hist(dfavec, color='#57aefc')
plt.axvline(v1, color='r', linestyle='--')
plt.axvline(v2, color='r', linestyle='--')
plt.axvline(dfa_alpha, color='m')
plt.ylabel('Counts')
plt.... | dfa/notebook/dfa_simulations.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Simulation 2: slicing
In the second simulation we are going to check what happens if we slice the signal and join two pieces together. Does it affect DFA value?
As it happened before firstly we consider only signle case. | n = 2**13
x = power_law_noise(n, dfa_alpha)
plt.figure(figsize=(9,7))
plt.subplot(211)
plt.plot(x)
plt.title("Original signal")
plt.subplot(212)
idx = 1400
gap_width = 400
x_c = np.concatenate((x[:idx],x[idx+gap_width:]))
plt.plot(x_c)
plt.xlabel('time')
plt.title("Sliced signal")
scales, fluct, estaalpha = dfa(x_c)
pr... | dfa/notebook/dfa_simulations.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
And now we test it by bootstrapping. | Nrep = 1000 # how many resamplings
x_down, x_top = int(0.1*n), int(0.9*n) # range of slice
sig_gw, mu_gw = 100, 300 # gap width
gap_width = 200
dfavec = np.zeros(Nrep)
for i in range(Nrep):
if i%10==0: print(i, end=" ")
x = power_law_noise(n, dfa_alpha)
idx = np.ra... | dfa/notebook/dfa_simulations.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Once again the initial value is in between confidence intervals so we can infer that slicing has no effect on DFA estimation. | alpha = 0.05
v1 = st.scoreatpercentile(dfavec, 0.5*alpha*100)
v2 = st.scoreatpercentile(dfavec, 100-0.5*alpha*100)
plt.figure(figsize=(9, 6))
plt.hist(dfavec, color='#57aefc')
plt.axvline(v1, color='r', linestyle='--')
plt.axvline(v2, color='r', linestyle='--')
plt.axvline(dfa_alpha, color='m')
plt.ylabel('Counts')
plt... | dfa/notebook/dfa_simulations.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Run the following in the Terminal (CPU):
python /root/src/main/python/debug/debug_model_cpu.py | %%bash
cat /root/src/main/python/debug/debug_model_gpu.py | oreilly.ml/high-performance-tensorflow/notebooks/05_Debug_Model.ipynb | shareactorIO/pipeline | apache-2.0 |
从计算器开始 | 5 + 100
100 / 10
100 * 10
100 - 99
10 % 3
10 ** 3
10 ** (1/3)
import math
math.pi
math.sin(math.pi/2)
math.floor(9.23432)
math.ceil(9.234) | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
应用题:
1、小姐姐去买水果,苹果5元一斤,葡萄15元一斤,现在小姐姐买了2斤苹果,1.5斤葡萄,问,小姐姐买这两种水果分别花了多少钱?总共花了多少钱? | # 苹果的花费
print(5*2)
# 葡萄的花费
print(15*1.5)
# 总花费
print((5*2) + (15*1.5)) | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
三个问题:
1、如果脱离了题干和注释,我们无法理解 5 * 2 是什么意思
2、当计算总价的时候,重复计算了苹果和葡萄的花费
3、输出是一个数字,表达不清晰 | apple_price = 5
apple_weight = 2
apple_cost = apple_price * apple_weight
grape_price = 15
grape_weight = 1.5
grape_cost = grape_price * grape_weight
total_cost = apple_cost + grape_cost
print(apple_cost, total_cost) | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
增强的格式化字符串函数 format | "苹果的花费为:{};葡萄的花费为:{};总花费为:{}".format(apple_cost, grape_cost, total_cost) | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
变量: 代表某个值得名称 | number + 2 | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
语法糖 | a = 10
b = 20
a, b = b, a
print("a is {}, b is {}".format(a, b)) | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
命名规范
1、标识符的第一个字符必须是字母表中的字母(大写或小写)或者一个下划线
2、标识符名称的其他部分可以由字母(大写或小写)、下划线(‘_’)或数字(0-9)组成。
3、标识符名称是对大小写敏感的。 | n = 10
N = 10
# 错误: 首字符为数字
3thidnf = 10
# 字母中间有空格,为非法字符
my name = 100
# -是变量命名中的非法字符
my-name = 10
round(100/3, 3) | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
代码规范建议
1、不要使用单字符
2、变量名能清晰表达变量的意思
3、合理使用字母中间下划线
变量类型
1、字符串 str
2、数字 int float complex ..
3、列表 list
4、元组 tuple
5、字典 dict
数值类型 | number = 10
number = number + 10
number += 10
number -= 10
number *= 10
number /= 10
import math
# 乘方、开放
math.pow(3, 10)
# 推荐是用
3 ** 10
math.floor(2.23242)
math.ceil(2.234234)
# 度的转换
math.radians(180)
math.sin(math.pi/2)
min(10, 12, 234, 100, 1)
max(10, 12, 234, 100, 1)
sum([10, 12, 234, 100, 1])
divmod(10,... | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
bool型 | True, False
True == 1
False == 0
# 不建议这样写,没有意义, 有一个特例,后面会讲到
True + 10
100 > 10 | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
bool类型,运算: 与运算、或运算、非运算 | # 与运算,同为真则为真
True and False
# 或运算, 只要一个为真则为真
True or False
# 非运算,取反
not False | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
| 操作符 | 解释 |
| --- | --- |
| < | 小于 |
| <= | 小于等于 |
| > | 大于 |
| >= | 大于等于 |
| == | 等于 |
| != | 不等于 |
| is | 是相同对象 |
字符串 | # 字符串可以用双引号,也可以用单引号。通过单、双引号的恰当使用,可以避免不必要的字符转义(escape),也就是说,可以避免使用 \ (转义字符)
line = "hello world"
line = "hello world\""
line = 'hello \'world'
# 字符串的加法操作
line_1 = "ni hao, "
line_2 = 'xiaojiejie'
line_1 + line_2
# 字符串的乘法操作
line = 'nihao '
line * 10
# 字符串是不可变类型的变量
line
line = 'buhao '
line
# 返回字符串的长度
len(line)
lin... | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
markdown中表格的写法
| 序号 | 名称 | 年龄 |
| --- | :---: | --- |
| 1 | wong | 18 |
| 2 | sun xing zhe | 500 |
切片 | line = 'huan ying da jia lai wan men shang ke' | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
取前十个字符 | line[0:10]
line[0:20:3] | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
取后十个字符 | line[-10:] | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
翻转字符 | line[::-1] | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
单字符
单字符是不可以进行赋值的 | line[-1] = 'E'
line.capitalize()
line = "ASDFASDFEWFSDF"
line.capitalize()
# 居中
line.center(20)
# 计数
line.count('Z') | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
字符串首尾判断 | line.endswith('FEWFSDD')
line.startswith('ASDFA')
line
line.find('A', 2)
# 当字符不存在时,报错
line.index('Z')
line = 'Aslkdfjsldkf'
line.upper()
line.lower()
line.istitle()
line.isupper()
line.islower()
line = ' lskdas k \n\t '
line.strip()
line.rstrip()
line.lstrip()
line = 'Aslkdfjsldkf'
line.swapcase() | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
【重点】上面我们用到的所有字符串函数,都是为我们生成了一个新的字符串,原有的字符串是不变的 | line = "ni hao"
id(line)
new_line = line.upper()
id(line), id(new_line) | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
列表 | # 空列表
varibals = []
varibals = list() | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
可以容纳任意类型的对象,任意数量的对象 【重点】列表是可变类型的 | varibals = [1, 2, 3, 'ni hao', 'hello, python', [], [100, 100]]
varibals = []
varibals.append(1)
varibals.append(2)
varibals.append('ni hao')
varibals
varibals[0] = 10
varibals | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
python是一种动态类型的语言,一个变量是什么类型,要看程序在运行过程中变量所代表的值是什么 | var = 10
type(var)
var = 'str'
type(var) | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
切片 | varibals[-2:]
varibals + [1,23]
varibals * 4 | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
序列 列表是一种容器型的序列;字符串是一种扁平型的序列 | len(varibals)
# 没有返回值,而是修改了我们列表对象本身
varibals.append(1)
varibals
# 清空
varibals.clear()
varibals = [1,12,23,4234, [1,2]]
new_varibals = varibals.copy()
new_varibals[-1][0] = 99999
new_varibals
varibals
id(new_varibals[-1]), id(varibals[-1])
a = [1,2]
b = [3,4]
a + b
a.extend(b)
a
a
a.insert(0, 100)
a
a.pop(0... | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
tuple | var = tuple()
var = ()
type(var)
var = (1,2, 1, 3,4,5, [23,34,43])
var.count(1)
var.index(5)
a, b = 10, 20
a = 10, 20
a | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
| 元组变量 | 字符串变量 | 列表变量 |
| --- | --- | -- |
| t_1 = [1,2,3,4,5] | s_1 = 'ni hao' | l_1 = [1,2,3,4,5] |
| t_2 = [5,6,7,8,9] | s_2 = 'how are you' | l_2 = [6,7,8,9,10] |
| 函数 | 元组 | 实例 | 字符串 | 实例 | 列表 | 实例 |
| :--- | :---: | :--- | :---: | :--- | :---: | :-- | :--- |
| + | ✅ | t_1 + t_2 | ✅ | s_1 + s_2 | ✅ | l_1 + l_2 |
... | var = {}
var = dict()
type(var)
var = {
'中': 100,
'左': 200
}
var['中']
words = ['中', '左']
location = [100, 200]
location[words.index('中')] | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
拉锁函数 | new_var = list(zip(words, location))
new_var
dict(new_var)
list(zip([1,2], [3,4, 5], [4,5,5]))
students = ['wong', 'li', 'sun', 'zhao', 'qian']
money = dict.fromkeys(students, 10) | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
访问字典中的值 | money['wong']
a = money.get('ww', '100')
print(a)
money.keys()
money.values()
money.items()
# 删除操作
money.pop('wong')
money
money['nihao'] = 100
money
money.setdefault('haha', 1000)
money | python第一课课件.ipynb | superliaoyong/plist-forsource | apache-2.0 |
Set image and catalogue filenames | xidplus.__path__[0]
#Folder containing maps
imfolder=xidplus.__path__[0]+'/../test_files/'
pswfits=imfolder+'cosmos_itermap_lacey_07012015_simulated_observation_w_noise_PSW_hipe.fits.gz'#SPIRE 250 map
pmwfits=imfolder+'cosmos_itermap_lacey_07012015_simulated_observation_w_noise_PMW_hipe.fits.gz'#SPIRE 350 map
plwfits... | docs/build/html/notebooks/examples/XID+example_run_script_profile.ipynb | H-E-L-P/XID_plus | mit |
Load in images, noise maps, header info and WCS information | #-----250-------------
hdulist = fits.open(pswfits)
im250phdu=hdulist[0].header
im250hdu=hdulist[1].header
im250=hdulist[1].data*1.0E3 #convert to mJy
nim250=hdulist[2].data*1.0E3 #convert to mJy
w_250 = wcs.WCS(hdulist[1].header)
pixsize250=3600.0*w_250.wcs.cd[1,1] #pixel size (in arcseconds)
hdulist.close()
#-----35... | docs/build/html/notebooks/examples/XID+example_run_script_profile.ipynb | H-E-L-P/XID_plus | mit |
Load in catalogue you want to fit (and make any cuts) | hdulist = fits.open(catfolder+prior_cat)
fcat=hdulist[1].data
hdulist.close()
inra=fcat['RA']
indec=fcat['DEC']
# select only sources with 100micron flux greater than 50 microJy
sgood=fcat['S100']>0.050
inra=inra[sgood]
indec=indec[sgood] | docs/build/html/notebooks/examples/XID+example_run_script_profile.ipynb | H-E-L-P/XID_plus | mit |
XID+ uses Multi Order Coverage (MOC) maps for cutting down maps and catalogues so they cover the same area. It can also take in MOCs as selection functions to carry out additional cuts. Lets use the python module pymoc to create a MOC, centered on a specific position we are interested in. We will use a HEALPix order of... | from astropy.coordinates import SkyCoord
from astropy import units as u
#c = SkyCoord(ra=[150.74]*u.degree, dec=[2.03]*u.degree)
c = SkyCoord(ra=inra*u.degree, dec=indec*u.degree)
import pymoc
moc=pymoc.util.catalog.catalog_to_moc(c,100,15) | docs/build/html/notebooks/examples/XID+example_run_script_profile.ipynb | H-E-L-P/XID_plus | mit |
XID+ is built around two python classes. A prior and posterior class. There should be a prior class for each map being fitted. It is initiated with a map, noise map, primary header and map header and can be set with a MOC. It also requires an input prior catalogue and point spread function. | #---prior250--------
prior250=xidplus.prior(im250,nim250,im250phdu,im250hdu, moc=moc)#Initialise with map, uncertianty map, wcs info and primary header
prior250.prior_cat(inra,indec,prior_cat)#Set input catalogue
prior250.prior_bkg(-5.0,5)#Set prior on background (assumes Gaussian pdf with mu and sigma)
#---prior350---... | docs/build/html/notebooks/examples/XID+example_run_script_profile.ipynb | H-E-L-P/XID_plus | mit |
Set PRF. For SPIRE, the PRF can be assumed to be Gaussian with a FWHM of 18.15, 25.15, 36.3 '' for 250, 350 and 500 $\mathrm{\mu m}$ respectively. Lets use the astropy module to construct a Gaussian PRF and assign it to the three XID+ prior classes. | #pixsize array (size of pixels in arcseconds)
pixsize=np.array([pixsize250,pixsize350,pixsize500])
#point response function for the three bands
prfsize=np.array([18.15,25.15,36.3])
#use Gaussian2DKernel to create prf (requires stddev rather than fwhm hence pfwhm/2.355)
from astropy.convolution import Gaussian2DKernel
... | docs/build/html/notebooks/examples/XID+example_run_script_profile.ipynb | H-E-L-P/XID_plus | mit |
Replace YOUR_KEY with your OTX API key. You can find it on your settings page https://otx.alienvault.com/settings.
Subscriptions
The getall() method accesses your subscriptions. It downloads all the OTX pulses and their assocciated indicators of compromise (IOCs) from your account. This includes:
- All pulses you subs... | pulses = otx.getall()
len(pulses) | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
Let's list a few pulses: | json_normalize(pulses)[0:5] | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
author_name: The username of the OTX User that created the pulse
created: Date when the pulse was created in the system
description: Describes the pulse in terms of the type of threat it poses, and any other facts that may link it to other threat indicators.
id: Unique identifier of the pulse
indicators: Collection of ... | json_normalize(pulses[1]["indicators"]) | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
_id: Unique identifier of the IOC
created: Date IOC was added to the pulse
description: Describe the Indicator Of Compromise
indicator: The IOC
indicator_type: Type of indicator
The following Indicator Types are supported (also defined in IndicatorTypes.py): | indicator_types = [
{
"name": "IPv4",
"description": "An IPv4 address indicating the online location of a server or other computer."
},
{
"name": "IPv6",
"description": "An IPv6 address indicating the online location of a server or other computer."
},
{
"name": "dom... | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
Events
Besides receiving the pulse information, there is another function that can retrieve different events that are ocurring in the OTX system and affect your account. | events = otx.getevents_since(mtime)
json_normalize(events) | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
id: object id of this event. Unique reference identifier
action : "[subscribe | unsubscribe | delete]", Currently supports subscribe / unsubscribe events for users and pulses and delete events for pulses
object_type : "[pulse | user]", // Currently supports events for pulse and user objects
object_id : "[pulse id | au... | pulses = otx.search_pulses("Russian")
json_normalize(pulses["results"]) | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
Let's say we're interested in viewing the full details (including indicators) from one of our search results. For example maybe we're interested in the Enigma Ransomware: | pulse_id = pulses["results"][1]["id"]
pulse_details = otx.get_pulse_details(pulse_id)
json_normalize(pulse_details) | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
Indicator details
Let's investigate an indicator included in the Enigma Ransomware pulse. | indicator = pulse_details["indicators"][4]["indicator"]
indicator_details = otx.get_indicator_details_full(IndicatorTypes.IPv4, indicator) | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
Indicator details are divided into sections for convenience: | indicator_details.keys()
json_normalize(indicator_details["url_list"])
json_normalize(indicator_details["passive_dns"].get('passive_dns')) | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
Indicator details are not available for all supported indicator types. IndicatorTypes.supported_api_types contains a list of the indicator types you can use with get_indicator_details_by_section and get_indicator_details_full.
Create pulse
You can create new pulses using the create_pulse function. A name string is r... | indicators = [{"indicator": "82.194.84.121", "description":"", "type": "IPv4"}, {"indicator": "82.194.84.122", "description":"", "type": "IPv4"}]
new_pulse = otx.create_pulse(name="IPy Notebook Test", indicators=indicators, public=False)
json_normalize(new_pulse) | howto_use_python_otx_api.ipynb | AlienVault-Labs/OTX-Python-SDK | apache-2.0 |
Sieci neuronowe
Metody uczenia
Trochę historii: Perceptron liniowy
Mark 1 perceptron (Frank Rosenblatt, 1957):
* Aparat przeznaczony do rozpoznawania obrazu;
* 400 fotokomórek
* Wagi to potencjometry;
* Wagi aktualizowana za pomocą silniczków.
The New York Times, 1958:
[...] the embryo of an electronic computer that ... | from IPython.display import YouTubeVideo
YouTubeVideo('cNxadbrN_aI', width=800, height=600) | Wyklady/10/Sieci neuronowe.ipynb | emjotde/UMZ | cc0-1.0 |
Uczenie (bez ingerencji człowieka)
Cykl uczenia perceptronu (w sumie 2000 "epok"):
* pokazanie (do kamery cyfrowej) planszy z kolejnym obiektem (np. trójkat, koło, kwadrat,...);
* zaobserwowanie, jaka lampka się zapaliła na wyjściu;
* sprawdzenie, czy jest to właściwa lampka (arbitralnie ustalona);
* wysłanie sygnału "... | import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': 16})
plt.figure(figsize=(10,6))
x = [-1,-.23,1]
y = [-1, -1, 1]
plt.ylim(-1.2,1.2)
plt.xlim(-1.2,1.2)
plt.plot([-2,2],[1,1], color='black', ls="dashed")
plt.plot([-2,2],[-1,-1], color='black', ls="dashed")
plt.step(x, y, lw=3... | Wyklady/10/Sieci neuronowe.ipynb | emjotde/UMZ | cc0-1.0 |
$$ g(z) = \left{
\begin{array}{rl}
1 & \textrm{gdy $z > \theta_0$} \
-1 & \textrm{wpp.}
\end{array}
\right. $$
gdzie $z = \theta_0x_0 + \ldots + \theta_nx_n$. Niech $\theta_0$ to próg aktywacji, ustalamy $x_0 = 1$.
Składamy wszystko w całość | %%tikz -l arrows,automata,positioning,shapes,shapes.geometric,fit -f png -s 2000,1400
\tikzstyle{every node}=[font=\large]
\tikzstyle{every path}=[line width=1pt]
\node[state] (x0) {$1$};
\node[state] (x1) [below=0.5cm of x0] {$x_1$};
\node[state] (x2) [below=0.5cm of x1] {$x_2$};
\node[state, draw=none,fill=none] (do... | Wyklady/10/Sieci neuronowe.ipynb | emjotde/UMZ | cc0-1.0 |
Pseudokod
Ustal wartości początkowe $\theta$ (wektor 0 lub liczby losowe blisko 0)
Dla każdego przykładu $(x^{(i)}, y^{(i)})$, dla $i=1,\ldots,m$
Oblicz wartość wyjścia $o^{(i)}$:
$$o^{(i)} = g(\theta^{T}x^{(i)}) = g(\sum_{j=0}^{n} \theta_jx_j^{(i)})$$
Wykonaj aktualizację wag (tzw. perceptron rule):
$$ \theta := \the... |
plt.figure(figsize=(16,7))
plt.subplot(121)
x = [-2,-.23,2]
y = [-1, -1, 1]
plt.ylim(-1.2,1.2)
plt.xlim(-2.2,2.2)
plt.plot([-2,2],[1,1], color='black', ls="dashed")
plt.plot([-2,2],[-1,-1], color='black', ls="dashed")
plt.step(x, y, lw=3)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color... | Wyklady/10/Sieci neuronowe.ipynb | emjotde/UMZ | cc0-1.0 |
Rozwiązanie: SGD!
Perceptron a regresja liniowa | %%tikz -l arrows,automata,positioning,shapes,shapes.geometric,fit -f png -s 2000,1400
\tikzstyle{every node}=[font=\large]
\tikzstyle{every path}=[line width=1pt]
\node[state] (x0) {$1$};
\node[state] (x1) [below=0.5cm of x0] {$x_1$};
\node[state] (x2) [below=0.5cm of x1] {$x_2$};
\node[state, draw=none,fill=none] (do... | Wyklady/10/Sieci neuronowe.ipynb | emjotde/UMZ | cc0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.