markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Betrachte den Inhalt der "target"-Spalte von df_x1_t1_trx_1_4. | analyze_target(df_x1_t1_trx_1_4) | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Als nächstes laden wir den Frame x3_t2_trx_3_1 und betrachten seine Dimension. | df_x3_t2_trx_3_1 = hdf.get('/x3/t2/trx_3_1')
print("Rows:", df_x3_t2_trx_3_1.shape[0])
print("Columns:", df_x3_t2_trx_3_1.shape[1]) | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Gefolgt von einer Analyse seiner Spaltenzusammensetzung und seiner "target"-Werte. | analyse_columns(df_x3_t2_trx_3_1)
analyze_target(df_x3_t2_trx_3_1) | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Frage: Was stellen Sie bzgl. der „Empfänger-Nummer_Sender-Nummer“-Kombinationen fest? Sind diese gleich? Welche Ausprägungen finden Sie in der Spalte „target“?
Antwort: Wir sehen, wenn jeweils ein Paar sendet, hören die anderen beiden Sender zu und messen ihre Verbindung zu den gerade sendenden Knoten (d.h. 6 Paare in... | vals = df_x1_t1_trx_1_4.loc[:,'trx_2_4_ifft_0':'trx_2_4_ifft_1999'].values
# one big heatmap
plt.figure(figsize=(14, 12))
plt.title('trx_2_4_ifft')
plt.xlabel("ifft of frequency")
plt.ylabel("measurement")
ax = sns.heatmap(vals, xticklabels=200, yticklabels=20, vmin=0, vmax=1, cmap='nipy_spectral_r')
plt.show() | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Wir betrachten wie verschiedene Farbschemata unterschiedliche Merkmale unserer Rohdaten hervorheben. | # compare different heatmaps
plt.figure(1, figsize=(12,10))
# nipy_spectral_r scheme
plt.subplot(221)
plt.title('trx_2_4_ifft')
plt.xlabel("ifft of frequency")
plt.ylabel("measurement")
ax = sns.heatmap(vals, xticklabels=200, yticklabels=20, vmin=0, vmax=1, cmap='nipy_spectral_r')
# terrain scheme
plt.subplot(222)
pl... | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Aufgabe 3: Groundtruth-Label anpassen | # Iterating over hdf data and creating interim data presentation stored in data/interim/testmessungen_interim.hdf
# Interim data representation contains aditional binary class (binary_target - encoding 0=empty and 1=not empty)
# and multi class target (multi_target - encoding 0-9 for each possible class)
from sklearn.p... | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Überprüfe neu beschrifteten Dataframe „/x1/t1/trx_3_1“ verwenden. Wir erwarten als Ergebnisse für 5 zu Beginn des Experiments „Empty“ (bzw. 0) und für 120 mitten im Experiment „Not Empty“ (bzw. 1). | hdf = pd.HDFStore('../../data/interim/01_testmessungen.hdf')
df_x1_t1_trx_3_1 = hdf.get('/x1/t1/trx_3_1')
print("binary_target for measurement 5:", df_x1_t1_trx_3_1['binary_target'][5])
print("binary_target for measurement 120:", df_x1_t1_trx_3_1['binary_target'][120])
hdf.close() | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Aufgabe 4: Einfacher Erkenner mit Hold-Out-Validierung
Wir folgen den Schritten in Aufgabe 4 und testen einen einfachen Erkenner. | from evaluation import *
from filters import *
from utility import *
from features import * | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Öffnen von Hdf mittels pandas | # raw data to achieve target values
hdf = pd.HDFStore('../../data/raw/TestMessungen_NEU.hdf') | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Beispiel Erkenner
Datensätze vorbereiten | # generate datasets
tst = ['1','2','3']
tst_ds = []
for t in tst:
df_tst = hdf.get('/x1/t'+t+'/trx_3_1')
lst = df_tst.columns[df_tst.columns.str.contains('_ifft_')]
#df_tst_cl,_ = distortion_filter(df_tst_cl)
groups = get_trx_groups(df_tst)
df_std = rf_grouped(df_tst, groups=groups, fn=r... | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Schließen von HDF Store | hdf.close() | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Aufgabe 5: Eigener Erkenner
Für die Konstruktion eines eigenen Erkenners führen wir die entsprechenden Preprocessing und Mapping Schritte ausgehend von den Roddaten erneut durch und passen diese unseren Bedürfnissen an.# Load hdfs data
hdfs = pd.HDFStore("../../data/raw/henrik/TestMessungen_NEU.hdf") | # Load raw data
hdf = pd.HDFStore("../../data/raw/TestMessungen_NEU.hdf")
# Check available keys in hdf store
print(hdf.keys) | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Vorverarbeitung
Zuerst passen wir die Groundtruth-Label an, entfernen Zeitstempel sowie Zeilenindices und speichern die resultierenden Frames ab. | hdf_path = "../../data/interim/02_tesmessungen.hdf"
# Mapping groundtruth to 0-empty and 1-not empty and prepare for further preprocessing by
# removing additional timestamp columns and index column
# Storing cleaned dataframes (no index, removed _ts columns, mapped multi classes to 0-empty, 1-not empty)
# to new hdfs... | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Wir sehen, dass nur noch die 6 x 2000 Messungen für die jeweiligen Paare sowie die 'target'-Werte in den resultierenden Frames enthalten sind. | hdf = pd.HDFStore(hdf_path)
df = hdf.get("/x1/t1/trx_1_2")
df.head()
# Step-1 repeating the previous taks 4 to get a comparable base result with the now dropped _ts and index column to improve from
# generate datasets
from evaluation import *
from filters import *
from utility import *
from features import *
def ... | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Aufgabe 6: Online Erkenner
Serialisierung des Models für den Online Predictor
Das zuvor gewählte Model wird serialisiert und in 'models/solution_ueb02' gespeichert damit es beim starten der REST-API geladen werden kann. | from sklearn.externals import joblib
joblib.dump(res['dt'], '../../models/solution_ueb02/model.plk') | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
Starten des online servers
Hierzu müssen die Abhängigkeiten Flask, flask_restful, flask_cors installiert sein
The following command starts a flask_restful server on localhost port:5444 which answers json post requests. The server is implemented in the file online.py within the ipynb folder and makes use of the final ch... | # Navigate to notebooks/solution_ueb02 and start the server
# with 'python -m online'
# Nun werden zeilenweise Anfragen an die REST-API simuliert, jeder valider json request wird mit einer
# json prediction response beantwortet | notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb | hhain/sdap17 | mit |
首先引入python正则表达式库re
1. 入门 | s = 'Blow low, follow in of which low. lower, lmoww oow aow bow cow 23742937 dow kdiieur998.'
p = 'low' | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
假设要在字符串s中查找单词low,由于该单词的规律就是low,因此可将low作为一个正则表达式,可命名为p。 | m = re.findall(p, s)
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
findall(pattern, string)是re模块中的函数,会在字符串string中将所有匹配正则表达式pattern模式的字符串提取出来,并以一个list的形式返回。该方法是从左到右进行扫描,所返回的list中的每个匹配按照从左到右匹配的顺序进行存放。
正则表达式low能够将所有单词low匹配出来,但是也会将lower,Blow等含有low字符串中的low也匹配出来。 | p = r'\blow\b'
m = re.findall(p, s)
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
\b,即boundary,是正则表达式中的一种特殊字符,表示单词的边界。正则表达式r'\blow\b'就是要单独匹配low,该字符串两侧为单词的边界(边界为空格等,但是并不是要匹配之) | p = r'[lmo]ow'
m = re.findall(p, s)
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
[lmo],匹配lmo字母中的任何一个 | p = r'[a-d]ow'
m = re.findall(p, s)
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
[a-d],匹配abcd字母中的任何一个 | p = r'\d'
m = re.findall(p, s)
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
\d,即digit,表示数字 | p = r'\d+'
m = re.findall(p, s)
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
+,元字符,表示一个或者重复多个对象,对象为+前面指定的模式
因此\d+可以匹配长度至少为1的任意正整数。
2. 基本匹配与实例
字符模式|匹配模式内容|等价于
----|---|--
[a-d]|One character of: a, b, c, d|[abcd]
[^a-d]|One character except: a, b, c, d|[^abcd]
abc丨def|abc or def|
\d|One digit|[0-9]
\D|One non-digit|[^0-9]
\s|One whitespace|[ \t\n\r\f\v]
\S|One non-whitespace|[^ \t\n\r\f\v]
\w|O... | m = re.findall(r'\d{3,4}-?\d{8}', '010-66677788,02166697788, 0451-22882828')
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
匹配电话号码,区号可以是3或者4位,号码为8位,中间可以有-或者没有。 | m = re.findall(r'[\u4e00-\u9fa5]', '测试 汉 字,abc,测试xia,可以')
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
匹配汉字
几个实例
正则表达式|匹配内容
----|---
[A-Za-z0-9]|匹配英文和数字
[\u4E00-\u9FA5A-Za-z0-9_]|中文英文和数字及下划线
^[a-zA-Z][a-zA-Z0-9_]{4,15}$`|合法账号,长度在5-16个字符之间,只能用字母数字下划线,且第一个位置必须为字母
3. 进阶
3.1 python正则表达式几个函数
函数|功能|用法
----|---|---
re.search|Return a match object if pattern found in string|re.search(r'[pat]tern', 'string')
re.finditer|Retu... | m = re.search(r'\d{3,4}-?\d{8}', '010-66677788,02166697788, 0451-22882828')
m
m.group() | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
利用group()函数,取出match对象中的内容 | ms = re.finditer(r'\d{3,4}-?\d{8}', '010-66677788,02166697788, 0451-22882828')
for m in ms:
print(m.group())
words = re.split(r'[,-]', '010-66677788,02166697788,0451-22882828')
words
p = re.compile(r'[,-]')
p.split('010-66677788,02166697788,0451-22882828') | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
利用compile()函数将正则表达式编译,如以后多次运行,可加快程序运行速度
3.2 分组与引用
Group Type|Expression
----|---
Capturing|( ... )
Non-capturing|(?: ... )
Capturing group named Y|(?P<Y> ... )
Match the Y'th captured group|\Y
Match the named group Y|(?P=Y)
(...) 将括号中的部分,放在一起,视为一组,即group。以该group来匹配符合条件的字符串。
group,可被同一正则表达式的后续,所引用,引用可以利用其位置,或者利用... | p = re.compile('(ab)+')
p.search('ababababab').group()
p.search('ababababab').groups() | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
有分组的情况,用groups()函数取出匹配的所有分组 | p=re.compile('(\d)-(\d)-(\d)')
p.search('1-2-3').group()
p.search('1-2-3').groups()
s = '喜欢/v 你/x 的/u 眼睛/n 和/u 深情/n 。/w'
p = re.compile(r'(\S+)/n')
m = p.findall(s)
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
按出现顺序捕获名词(/n)。 | p=re.compile('(?P<first>\d)-(\d)-(\d)')
p.search('1-2-3').group() | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
在分组内,可通过?P<name>的形式,给该分组命名,其中name是给该分组的命名 | p.search('1-2-3').group('first') | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
可利用group('name'),直接通过组名来获取匹配的该分组 | s = 'age:13,name:Tom;age:18,name:John'
p = re.compile(r'age:(\d+),name:(\w+)')
m = p.findall(s)
m
p = re.compile(r'age:(?:\d+),name:(\w+)')
m = p.findall(s)
m | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
(?:\d+),匹配该模式,但不捕获该分组。因此没有捕获该分组的数字 | s = 'abcdebbcde'
p = re.compile(r'([ab])\1')
m = p.search(s)
print('The match is {},the capture group is {}'.format(m.group(), m.groups())) | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
此即为反向引用
当分组([ab])内的a或b匹配成功后,将开始匹配\1,\1将匹配前面分组成功的字符。因此该正则表达式将匹配aa或bb。
类似地,r'([a-z])\1{3}',该正则将匹配连续的4个英文小写字母。 | s = '12,56,89,123,56,98, 12'
p = re.compile(r'\b(\d+)\b.*\b\1\b')
m = p.search(s)
m.group(1) | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
利用反向引用来判断是否含有重复数字,可提取第一个重复的数字。
其中\1是引用前一个分组的匹配。 | s = '12,56,89,123,56,98, 12'
p = re.compile(r'\b(?P<name>\d+)\b.*\b(?P=name)\b')
m = p.search(s)
m.group(1) | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
与前一个类似,但是利用了带分组名称的反向引用。
3.3 贪婪与懒惰
数量词|匹配模式内容
----|---
{2,5}?|Match 2 to 5 times (less preferred)
{2,}?|Match 2 or more times (less preferred)
{,5}?|Match 0 to 5 times (less preferred)
*?|Match 0 or more times (less preferred)
{,}?|Match 0 or more times (less preferred)
??|Match 0 or 1 times (less preferred)
{0,1}?|Mat... | p = re.compile('(ab)+')
p.search('ababababab').group()
p = re.compile('(ab)+?')
p.search('ababababab').group() | chapter3/python正则表达式基础快速教程.ipynb | zipeiyang/liupengyuan.github.io | mit |
Let us save the embedding for later use. | #### DUMP
#import pickle
#f = open('myembedding.pkl','wb')
#pickle.dump([final_embeddings,dictionary,reverse_dictionary],f)
#f.close()
num_points = 400
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
two_d_embeddings = tsne.fit_transform(final_embeddings[1:num_points+1, :])
def plot(embeddings, l... | 7.2 Word Embeddings.ipynb | jvitria/DeepLearningBBVA2016 | mit |
6. Understanding and using the embedding.
In the former code we have the dictionary that converts from the word to an index, and the reverse_dictionary that given an index returns the corresponding word. | import pickle
f = open('./dataset/myembedding.pkl','rb')
fe,dic,rdic=pickle.load(f)
f.close()
dic['woman']
rdic[42] | 7.2 Word Embeddings.ipynb | jvitria/DeepLearningBBVA2016 | mit |
The embedding tries to put together words with similar meaning. A good embedding allows to semantically operate. Let us check some simple semantical operations: | result = (fe[dic['two'],:]+ fe[dic['one'],:])
from scipy.spatial import distance
candidates=np.argsort(distance.cdist(fe,result[np.newaxis,:],metric="seuclidean"),axis=0)
for i in xrange(5):
idx=candidates[i][0]
print(rdic[idx]) | 7.2 Word Embeddings.ipynb | jvitria/DeepLearningBBVA2016 | mit |
We can also define word analogies: football is to ? as foot is to hand | result = (fe[dic['football'],:] - fe[dic['foot'],:] + fe[dic['hand'],:])
from scipy.spatial import distance
candidates=np.argsort(distance.cdist(fe,result[np.newaxis,:],metric="seuclidean"),axis=0)
for i in xrange(5):
idx=candidates[i][0]
print(rdic[idx])
result = (fe[dic['madrid'],:] - fe[dic['spain'],:] + ... | 7.2 Word Embeddings.ipynb | jvitria/DeepLearningBBVA2016 | mit |
Let us used a pretrained embedding. We will use a simple embedding detailed in Improving Word Representations via Global Context and Multiple Word Prototypes | import pandas as pd
df = pd.read_table("./dataset/wordVectors.txt",delimiter=" ",header=None)
embedding=df.values[:,:-1]
f = open("./dataset/vocab.txt",'r')
dictionary=dict()
for word in f.readlines():
dictionary[word] = len(dictionary)
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys())) ... | 7.2 Word Embeddings.ipynb | jvitria/DeepLearningBBVA2016 | mit |
Inter and Intra Similarities
The first measure that we can use to determine if something reasonable is happening is to look at, for each homework, the average similarity of two notebooks both pulled from that homework, and the average similarity of a notebook pulled from that homework and any notebook in the corpus not... | def get_avg_inter_intra_sims(X, y, val):
inter_sims = []
intra_sims = []
for i in range(len(X)):
for j in range(i+1, len(X)):
if y[i] == y[j] and y[i] == val:
intra_sims.append(similarities[i][j])
else:
inter_sims.append(similarities[i][j])
... | summary_of_work/server_notebooks/bottom_up/Bottom Up Random Forest SplitCall.ipynb | DataPilot/notebook-miner | apache-2.0 |
Sims color coded | %matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = 5, 15
def get_all_sims(X, y, val):
sims = []
sims_outer = []
for i in range(len(X)):
for j in range(i+1, len(X)):
if y[i] == val or y[j] == val:
if y[i] == y[j]:
sims.a... | summary_of_work/server_notebooks/bottom_up/Bottom Up Random Forest SplitCall.ipynb | DataPilot/notebook-miner | apache-2.0 |
Actual Prediction
While the above results are helpful, it is better to use a classifier that uses more information. The setup is as follows:
Split the data into train and test
Vectorize based on templates that exist
Build a random forest classifier that uses this feature representation, and measure the performance | import sklearn
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score
X, y = ci.get_data_set()
countvec = sklearn.feature_extraction.text.CountVectorizer()
X_list = [" ".join(el) for el in X]
countvec.fit(X_list)
X = countvec.tran... | summary_of_work/server_notebooks/bottom_up/Bottom Up Random Forest SplitCall.ipynb | DataPilot/notebook-miner | apache-2.0 |
Clustering
Lastly, we try unsupervised learning, clustering based on the features we've extracted, and measure using sillouette score. | X, y = ci.get_data_set()
countvec = sklearn.feature_extraction.text.CountVectorizer()
X_list = [" ".join(el) for el in X]
countvec.fit(X_list)
X = countvec.transform(X_list)
clusterer = sklearn.cluster.KMeans(n_clusters = 4).fit(X)
cluster_score = (sklearn.metrics.silhouette_score(X, clusterer.labels_))
cheat_score = ... | summary_of_work/server_notebooks/bottom_up/Bottom Up Random Forest SplitCall.ipynb | DataPilot/notebook-miner | apache-2.0 |
Trying to restrict features
The problem above is that there are too many unimportant features -- all this noise makes it hard to seperate the different classes. To try to counteract this, I'll try ranking the features using tfidf and only take some of them | X, y = ci.get_data_set()
tfidf = sklearn.feature_extraction.text.TfidfVectorizer()
X_list = [" ".join(el) for el in X]
tfidf.fit(X_list)
X = tfidf.transform(X_list)
#X = X.todense()
feature_array = np.array(tfidf.get_feature_names())
tfidf_sorting = np.argsort(X.toarray()).flatten()[::-1]
top_n = feature_array[tfidf_s... | summary_of_work/server_notebooks/bottom_up/Bottom Up Random Forest SplitCall.ipynb | DataPilot/notebook-miner | apache-2.0 |
T-SNE | X, y = ci.get_data_set()
tfidf = sklearn.feature_extraction.text.TfidfVectorizer()
X_list = [" ".join(el) for el in X]
tfidf.fit(X_list)
X = tfidf.transform(X_list)
#X = X.todense()
# This is a recommended step when using T-SNE
x_reduced = sklearn.decomposition.PCA(n_components=50).fit_transform(X.todense())
from skl... | summary_of_work/server_notebooks/bottom_up/Bottom Up Random Forest SplitCall.ipynb | DataPilot/notebook-miner | apache-2.0 |
What's happening
Figuring out what is going on is a bit difficult, but we can look at the top templates generated from the random forest, and see why they might have been chosen | '''
Looking at the output below, it's clear that the bottom up method is recognizing very specific
structures of ast graph, which makes sense because some structures are exactly repeated in
homeworks. For example:
treatment = pd.Series([0]*4 + [1]*2)
is a line in all of the homework one notebooks, and the top feature... | summary_of_work/server_notebooks/bottom_up/Bottom Up Random Forest SplitCall.ipynb | DataPilot/notebook-miner | apache-2.0 |
Get info about a dataset | # information about the ch04 dataset
dsinfo = service.datasets().get(datasetId="ch04", projectId=PROJECT).execute()
for info in dsinfo.items():
print(info) | 05_devel/google_api_client.ipynb | GoogleCloudPlatform/bigquery-oreilly-book | apache-2.0 |
List tables and creation times | # list tables in dataset
tables = service.tables().list(datasetId="ch04", projectId=PROJECT).execute()
for t in tables['tables']:
print(t['tableReference']['tableId'] + ' was created at ' + t['creationTime']) | 05_devel/google_api_client.ipynb | GoogleCloudPlatform/bigquery-oreilly-book | apache-2.0 |
Query and get result | # send a query request
request={
"useLegacySql": False,
"query": "SELECT start_station_name , AVG(duration) as duration , COUNT(duration) as num_trips FROM `bigquery-public-data`.london_bicycles.cycle_hire GROUP BY start_station_name ORDER BY num_trips DESC LIMIT 5"
}
print(request)
response = service.jobs().quer... | 05_devel/google_api_client.ipynb | GoogleCloudPlatform/bigquery-oreilly-book | apache-2.0 |
Asynchronous query and paging through results | # send a query request that will not terminate within the timeout specified and will require paging
request={
"useLegacySql": False,
"timeoutMs": 0,
"useQueryCache": False,
"query": "SELECT start_station_name , AVG(duration) as duration , COUNT(duration) as num_trips FROM `bigquery-public-data`.london_bicycles.... | 05_devel/google_api_client.ipynb | GoogleCloudPlatform/bigquery-oreilly-book | apache-2.0 |
Setup the matplotlib environment to make the plots look pretty. | # Show the plots inside the notebook.
%matplotlib inline
# Make the figures high-resolution.
%config InlineBackend.figure_format='retina'
# Various font sizes.
ticksFontSize=18
labelsFontSizeSmall=20
labelsFontSize=30
titleFontSize=34
legendFontSize=14
matplotlib.rc('xtick', labelsize=ticksFontSize)
matplotlib.rc('yti... | ResultingToGeneratedFragmentsRatio.ipynb | AleksanderLidtke/AnalyseCollisionFragments | mit |
Introduction
This is notebook analyses the data from a projection of an evolutionary space debris model DAMAGE. It investigates the amplification of the numbers of fragments that collisions generate themselves, which occurs due to follow-on collisions. The projected scenario is "mitigation only" with additional collisi... | import urllib2, numpy
from __future__ import print_function
# All collisions.
lines=urllib2.urlopen('https://raw.githubusercontent.com/AleksanderLidtke/\
AnalyseCollisionFragments/master/AllColGenerated').read(856393*25) # no. lines * no. chars per line
allColGen=numpy.array(lines.split('\n')[1:-1],dtype=numpy.float64... | ResultingToGeneratedFragmentsRatio.ipynb | AleksanderLidtke/AnalyseCollisionFragments | mit |
Analyse the ratio
Description
Investigate the fact that sometimes follow-on collisions will result in certain collisions being responsible for more fragments at some census epoch than they generated themselves. In order to do this, investigate the ratio between the number of fragments in the population snapshot in 2213... | # Compute the ratios.
allRatios=allColRes/allColGen
catRatios=catColRes/catColGen
# Plot.
fig=matplotlib.pyplot.figure(figsize=(12,8))
ax=fig.gca()
matplotlib.pyplot.grid(linewidth=1)
ax.set_xlabel(r"$Time\ (s)$",fontsize=labelsFontSize)
ax.set_ylabel(r"$Response\ (-)$",fontsize=labelsFontSize)
ax.set_xlim(0,7)
ax.set_... | ResultingToGeneratedFragmentsRatio.ipynb | AleksanderLidtke/AnalyseCollisionFragments | mit |
Not very legible, right? But some things can be observed in the above figure anyway. First of all, there's a "dip" in the number of generated fragments around $6.5\times 10^4$. This was caused by the fact that the number of generated fragments, $N$, exceeding a certain length $L_c$ is given by a power law:
$$ N(L_c)=0.... | bins=numpy.arange(0,allColGen.max(),500)
means=numpy.zeros(bins.size-1)
medians=numpy.zeros(bins.size-1)
meansCat=numpy.zeros(bins.size-1)
mediansCat=numpy.zeros(bins.size-1)
for i in range(bins.size-1):
means[i]=numpy.mean(allRatios[(allColGen>=bins[i]) & (allColGen<bins[i+1])])
medians[i]=numpy.median(allRati... | ResultingToGeneratedFragmentsRatio.ipynb | AleksanderLidtke/AnalyseCollisionFragments | mit |
The more fragments were generated in a collision, the fewer fragments a given collision gave rise to in the final population. This seems counter-intuitive because large collisions are expected to contribute more to the long-term growth of the debris population than others, which generate fewer fragments [2]. However, t... | ratioBins=numpy.linspace(0,2,100)
# Get colours for every bin of the number of generated fragments.
cNorm=matplotlib.colors.Normalize(vmin=0, vmax=bins.size-1)
scalarMap=matplotlib.cm.ScalarMappable(norm=cNorm,cmap=cm)
histColours=[]
for i in range(0,bins.size-1):
histColours.append(scalarMap.to_rgba(i))
# Plot the... | ResultingToGeneratedFragmentsRatio.ipynb | AleksanderLidtke/AnalyseCollisionFragments | mit |
Most collisions had a ratio of less than $2.0$. Only | numpy.sum(allRatios>=2.0)/float(allRatios.size)*100 | ResultingToGeneratedFragmentsRatio.ipynb | AleksanderLidtke/AnalyseCollisionFragments | mit |
Importing, downsampling, and visualizing data | # Get paths to all images and masks.
all_image_paths = glob('E:\\data\\lungs\\2d_images\\*.tif')
all_mask_paths = glob('E:\\data\\lungs\\2d_masks\\*.tif')
print(len(all_image_paths), 'image paths found')
print(len(all_mask_paths), 'mask paths found')
# Define function to read in and downsample an image.
def read_image... | deep_image_segmentation_with_convolutional_neural_networks.ipynb | nicholsonjohnc/jupyter | mit |
Split data into training and validation sets | X_train, X_test, y_train, y_test = train_test_split(all_images, all_masks, test_size=0.1)
print('Training input is', X_train.shape)
print('Training output is {}, min is {}, max is {}'.format(y_train.shape, y_train.min(), y_train.max()))
print('Testing set is', X_test.shape) | deep_image_segmentation_with_convolutional_neural_networks.ipynb | nicholsonjohnc/jupyter | mit |
Create CNN model | # Create a sequential model, i.e. a linear stack of layers.
model = Sequential()
# Add a 2D convolution layer.
model.add(
Conv2D(
filters=32,
kernel_size=(3, 3),
activation='relu',
input_shape=all_images.shape[1:],
padding='same'
)
)
# Add a 2D convolution layer.
mod... | deep_image_segmentation_with_convolutional_neural_networks.ipynb | nicholsonjohnc/jupyter | mit |
Train CNN model | history = model.fit(X_train, y_train, validation_split=0.10, epochs=10, batch_size=10)
test_no = 7
fig, ax = plt.subplots(nrows=1, ncols=3, sharex='col', sharey='row', figsize=(15,5))
ax[0].imshow(X_test[test_no,0], cmap='Blues')
ax[0].set_title('CT image', fontsize=18)
ax[0].tick_params(labelsize=16)
ax[1].imshow(y_t... | deep_image_segmentation_with_convolutional_neural_networks.ipynb | nicholsonjohnc/jupyter | mit |
```{admonition} Observación
:class: tip
En la celda anterior se utilizó el comando de magic %%bash. Algunos comandos de magic los podemos utilizar también con import. Ver ipython-magics
```
Características de los lenguajes de programación
Los lenguajes de programación y sus implementaciones tienen características como ... | %%file Rcf_python.py
import math
import time
def Rcf(f,a,b,n):
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are generated via formula: x_i = a+(i+1/2)h_hat for
i=0,1,...,n-1 and h_hat=(b-a)/n
Args:
f (float): function expression of in... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
R | %%file Rcf_R.R
Rcf<-function(f,a,b,n){
'
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are generated via formula: x_i = a+(i+1/2)h_hat for
i=0,1,...,n-1 and h_hat=(b-a)/n
Args:
f (float): function expression of integrand.
... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Julia
Ver: Julia: performance-tips | %%file Rcf_julia.jl
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
# Arguments
- `f::Float`: function expression of integrand.
- `a::Float`: left point of interval.
- `b::Float`: right point of interval.
- `n::Integer`: number of subintervals.
"""
function Rcf(f, a, b, n)
... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
(RCFJULIATYPEDVALUES)=
Rcf_julia_typed_values.jl | %%file Rcf_julia_typed_values.jl
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
# Arguments
- `f::Float`: function expression of integrand.
- `a::Float`: left point of interval.
- `b::Float`: right point of interval.
- `n::Integer`: number of subintervals.
"""
function Rcf(f, ... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
(RCFJULIANAIVE)=
Rcf_julia_naive.jl | %%file Rcf_julia_naive.jl
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
# Arguments
- `f::Float`: function expression of integrand.
- `a::Float`: left point of interval.
- `b::Float`: right point of interval.
- `n::Integer`: number of subintervals.
"""
function Rcf(f, a, b, n... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
C
Para la medición de tiempos se utilizaron las ligas: measuring-time-in-millisecond-precision y find-execution-time-c-program.
(RCFC)=
Rcf_c.c | %%file Rcf_c.c
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
#include <sys/time.h>
void Rcf(double ext_izq, double ext_der, int n,\
double *sum_res_p);
double f(double nodo);
int main(int argc, char *argv[]){
double sum_res = 0.0;
double a = 0.0, b = 1.0;
int n = 1e7;
stru... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
¿Por qué dar información sobre el tipo de valores (u objetos) que se utilizan en un código ayuda a que su ejecución sea más rápida?
Python es dynamically typed que se refiere a que un objeto de cualquier tipo y cualquier statement que haga referencia a un objeto, pueden cambiar su tipo. Esto hace difícil que la máquina... | v = -1.0
print(type(v), abs(v))
v = 1 - 1j
print(type(v), abs(v)) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
La función abs trabaja diferente dependiendo del tipo de objeto. Para un número entero o punto flotante regresa el negativo de $-1.0$ y para un número complejo calcula una norma Euclidiana tomando de $v$ su parte real e imaginaria: $\text{abs}(v) = \sqrt{v.real^2 + v.imag^2}$.
Lo anterior en la práctica implica la eje... | import math
import time
from pytest import approx
from scipy.integrate import quad
from IPython.display import HTML, display | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Para este caso requerimos tres archivos:
1.El código que será compilado en un archivo con extensión .pyx (escrito en Python).
```{admonition} Observación
:class: tip
La extensión .pyx se utiliza en el lenguaje Pyrex.
```
2.Un archivo setup.py que contiene las instrucciones para llamar a Cython y se encarga de crear e... | %%file Rcf_cython.pyx
def Rcf(f,a,b,n): #Rcf: rectángulo compuesto para f
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are generated via formula: x_i = a+(i+1/2)h_hat for
i=0,1,...,n-1 and h_hat=(b-a)/n
Args:
f (float): function expre... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Archivo setup.py que contiene las instrucciones para el build: | %%file setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize("Rcf_cython.pyx",
compiler_directives={'language_level' : 3})
) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Compilar desde la línea de comandos: | %%bash
python3 setup.py build_ext --inplace | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Importar módulo compilado y ejecutarlo: | f=lambda x: math.exp(-x**2) #using math library
n = 10**7
a = 0
b = 1
import Rcf_cython
start_time = time.time()
res = Rcf_cython.Rcf(f, a, b,n)
end_time = time.time()
secs = end_time-start_time
print("Rcf tomó",secs,"segundos" )
obj, err = quad(f, a, b)
print(res == approx(obj)) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Comando de magic %cython
```{margin}
Ver extensions-bundled-with-ipython para extensiones que antes se incluían en Ipython.
```
Al instalar Cython se incluye tal comando. Al ejecutarse crea el archivo .pyx, lo compila con setup.py e importa en el notebook. | %load_ext Cython
%%cython
def Rcf(f,a,b,n):
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are generated via formula: x_i = a+(i+1/2)h_hat for
i=0,1,...,n-1 and h_hat=(b-a)/n
Args:
f (float): function expression of integrand.
... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Anotaciones para analizar un bloque de código
Cython tiene la opción de annotation para generar un archivo con extensión .html en el que cada línea puede ser expandida haciendo un doble click que mostrará el código C generado. Líneas "más amarillas" refieren a más llamadas en la máquina virtual de Python, mientras que ... | %%bash
$HOME/.local/bin/cython --force -3 --annotate Rcf_cython.pyx | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Ver archivo creado: Rcf_cython.html
```{margin}
La liga correcta del archivo Rcf_cython.c es Rcf_cython.c
``` | display(HTML("Rcf_cython.html")) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{admonition} Comentarios
Para el código anterior el statement en donde se crean los nodos involucra un loop y es "muy amarilla". Si se perfila el código se verá que es una línea en la que se gasta una buena parte del tiempo total de ejecución del código.
```
Una primera opción que tenemos es crear los nodos para el ... | %%file Rcf_2_cython.pyx
def Rcf(f,a,b,n):
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are generated via formula: x_i = a+(i+1/2)h_hat for
i=0,1,...,n-1 and h_hat=(b-a)/n
Args:
f (float): function expression of integrand.
... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{margin}
La liga correcta del archivo Rcf_2_cython.c es Rcf_2_cython.c
``` | display(HTML("Rcf_2_cython.html")) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{admonition} Comentario
Para el código anterior los statements que están dentro del loop son "muy amarillos". En tales statements involucran tipos de valores que no cambiarán en la ejecución de cada loop. Una opción es declarar los tipos de objetos que están involucrados en el loop utilizando la sintaxis cdef. Ver f... | %%file Rcf_3_cython.pyx
def Rcf(f, double a, double b, unsigned int n):
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are generated via formula: x_i = a+(i+1/2)h_hat for
i=0,1,...,n-1 and h_hat=(b-a)/n
Args:
f (float): function express... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{margin}
La liga correcta del archivo Rcf_3_cython.c es Rcf_3_cython.c
``` | display(HTML("Rcf_3_cython.html")) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{admonition} Comentario
Al definir tipos, éstos sólo serán entendidos por Cython y no por Python. Cython utiliza estos tipos para convertir el código de Python a código de C.
```
Una opción con la que perdemos flexibilidad pero ganamos en disminuir tiempo de ejecución es directamente llamar a la función math.exp: | %%file Rcf_4_cython.pyx
import math
def Rcf(double a, double b, unsigned int n):
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are generated via formula: x_i = a+(i+1/2)h_hat for
i=0,1,...,n-1 and h_hat=(b-a)/n
Args:
a (float): left po... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{margin}
La liga correcta del archivo Rcf_4_cython.c es Rcf_4_cython.c
``` | display(HTML("Rcf_4_cython.html")) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Mejoramos el tiempo si directamente utilizamos la función exp de la librería math de Cython, ver calling C functions.
(RCF5CYTHON)=
Rcf_5_cython.pyx | %%file Rcf_5_cython.pyx
from libc.math cimport exp as c_exp
cdef double f(double x) nogil:
return c_exp(-x**2)
def Rcf(double a, double b, unsigned int n):
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are generated via formula: x_i = a+(i+1/2)h_... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{margin}
La liga correcta del archivo Rcf_5_cython.c es Rcf_5_cython.c
``` | display(HTML("Rcf_5_cython.html")) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{admonition} Comentario
Un tradeoff en la optimización de código se realiza entre flexibilidad, legibilidad y una ejecución rápida del código.
``` | %%file setup_2.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize("Rcf_2_cython.pyx",
compiler_directives={'language_level' : 3})
) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Compilar desde la línea de comandos: | %%bash
python3 setup_2.py build_ext --inplace
%%file setup_3.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize("Rcf_3_cython.pyx",
compiler_directives={'language_level' : 3})
) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Compilar desde la línea de comandos: | %%bash
python3 setup_3.py build_ext --inplace
%%file setup_4.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize("Rcf_4_cython.pyx",
compiler_directives={'language_level' : 3})
) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Compilar desde la línea de comandos: | %%bash
python3 setup_4.py build_ext --inplace
%%file setup_5.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize("Rcf_5_cython.pyx",
compiler_directives={'language_level' : 3})
) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Compilar desde la línea de comandos: | %%bash
python3 setup_5.py build_ext --inplace | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Importar módulos compilados: | import Rcf_2_cython, Rcf_3_cython, Rcf_4_cython, Rcf_5_cython
start_time = time.time()
res_2 = Rcf_2_cython.Rcf(f, a, b,n)
end_time = time.time()
secs = end_time-start_time
print("Rcf_2 tomó",secs,"segundos" ) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Verificamos que después de la optimización de código continuamos resolviendo correctamente el problema: | print(res_2 == approx(obj))
start_time = time.time()
res_3 = Rcf_3_cython.Rcf(f, a, b,n)
end_time = time.time()
secs = end_time-start_time
print("Rcf_3 tomó",secs,"segundos" )
print(res_3 == approx(obj))
start_time = time.time()
res_4 = Rcf_4_cython.Rcf(a, b,n)
end_time = time.time()
secs = end_time-start_time
pri... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Verificamos que después de la optimización de código continuamos resolviendo correctamente el problema: | print(res_5 == approx(obj)) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Ejemplo de implementación con NumPy
Comparamos con una implementación usando NumPy y vectorización: | import numpy as np
f_np = lambda x: np.exp(-x**2) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
(RCFNUMPY)=
Rcf_numpy | def Rcf_numpy(f,a,b,n):
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are generated via formula: x_i = a+(i+1/2)h_hat for
i=0,1,...,n-1 and h_hat=(b-a)/n
Args:
f (float): function expression of integrand.
a (float): le... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{admonition} Comentarios
La implementación con NumPy resulta ser la segunda más rápida principalmente por el uso de bloques contiguos de memoria para almacenar los valores y la vectorización. La implementación anterior, sin embargo, requiere un conocimiento de las funciones de tal paquete. Para este ejemplo utiliz... | %%file Rcf_5_cython_openmp.pyx
from cython.parallel import prange
from libc.math cimport exp as c_exp
cdef double f(double x) nogil:
return c_exp(-x**2)
def Rcf(double a, double b, unsigned int n):
"""
Compute numerical approximation using rectangle or mid-point
method in an interval.
Nodes are ge... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
```{admonition} Comentario
Con prange puede elegirse diferente scheduling. Si schedule recibe el valor static el trabajo a realizar se reparte equitativamente entre los cores y si algunos threads terminan antes permanecerán sin realizar trabajo, aka idle. Con dynamic y guided se reparte de manera dinámica at runtime qu... | %%bash
$HOME/.local/bin/cython -3 --force Rcf_5_cython_openmp.pyx | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
En el archivo setup.py se coloca la directiva -fopenmp.
```{margin}
Ver Rcf_5_cython_openmp.c para la implementación en C de la función Rcf_5_cython_openmp.Rcf.
``` | %%file setup_5_openmp.py
from setuptools import Extension, setup
from Cython.Build import cythonize
ext_modules = [Extension("Rcf_5_cython_openmp",
["Rcf_5_cython_openmp.pyx"],
extra_compile_args=["-fopenmp"],
extra_link_args=["-fopenmp"],
... | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Compilar desde la línea de comandos: | %%bash
python3 setup_5_openmp.py build_ext --inplace
import Rcf_5_cython_openmp
start_time = time.time()
res_5_openmp = Rcf_5_cython_openmp.Rcf(a, b, n)
end_time = time.time()
secs = end_time-start_time
print("Rcf_5_openmp tomó",secs,"segundos" ) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Verificamos que después de la optimización de código continuamos resolviendo correctamente el problema: | print(res_5_openmp == approx(obj)) | libro_optimizacion/temas/5.optimizacion_de_codigo/5.3/Compilacion_a_C.ipynb | ITAM-DS/analisis-numerico-computo-cientifico | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.