markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Expected Output:
<table style="width:20%">
<tr>
<td>**cost**</td>
<td> 0.692919893776 </td>
</tr>
</table>
Using the cache computed during forward propagation, you can now implement backward propagation.
Question: Implement the function backward_propagation().
Instructions:
Backpropagation is usually the... | # GRADED FUNCTION: backward_propagation
def backward_propagation(parameters, cache, X, Y):
"""
Implement the backward propagation using the instructions above.
Arguments:
parameters -- python dictionary containing our parameters
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Expected output:
<table style="width:80%">
<tr>
<td>**dW1**</td>
<td> [[ 0.01018708 -0.00708701]
[ 0.00873447 -0.0060768 ]
[-0.00530847 0.00369379]
[-0.02206365 0.01535126]] </td>
</tr>
<tr>
<td>**db1**</td>
<td> [[-0.00069728]
[-0.00060606]
[ 0.000364 ]
[ 0.00151207]] </td>
</tr>
... | # GRADED FUNCTION: update_parameters
def update_parameters(parameters, grads, learning_rate = 1.2):
"""
Updates parameters using the gradient descent update rule given above
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradie... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Expected Output:
<table style="width:80%">
<tr>
<td>**W1**</td>
<td> [[-0.00643025 0.01936718]
[-0.02410458 0.03978052]
[-0.01653973 -0.02096177]
[ 0.01046864 -0.05990141]]</td>
</tr>
<tr>
<td>**b1**</td>
<td> [[ -1.02420756e-06]
[ 1.27373948e-05]
[ 8.32996807e-07]
[ -3.20136836e-06]]<... | # GRADED FUNCTION: nn_model
def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):
"""
Arguments:
X -- dataset of shape (2, number of examples)
Y -- labels of shape (1, number of examples)
n_h -- size of the hidden layer
num_iterations -- Number of iterations in gradient descent loo... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Expected Output:
<table style="width:90%">
<tr>
<td>**W1**</td>
<td> [[-4.18494056 5.33220609]
[-7.52989382 1.24306181]
[-4.1929459 5.32632331]
[ 7.52983719 -1.24309422]]</td>
</tr>
<tr>
<td>**b1**</td>
<td> [[ 2.32926819]
[ 3.79458998]
[ 2.33002577]
[-3.79468846]]</td>
</tr>
<tr... | # GRADED FUNCTION: predict
def predict(parameters, X):
"""
Using the learned parameters, predicts a class for each example in X
Arguments:
parameters -- python dictionary containing your parameters
X -- input data of size (n_x, m)
Returns
predictions -- vector of predictions of o... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Expected Output:
<table style="width:40%">
<tr>
<td>**predictions mean**</td>
<td> 0.666666666667 </td>
</tr>
</table>
It is time to run the model and see how it performs on a planar dataset. Run the following code to test your model with a single hidden layer of $n_h$ hidden units. | # Build a model with a n_h-dimensional hidden layer
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)
# Plot the decision boundary
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y[0,])
plt.title("Decision Boundary for hidden layer size " + str(4)) | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Expected Output:
<table style="width:15%">
<tr>
<td>**Accuracy**</td>
<td> 90% </td>
</tr>
</table>
Accuracy is really high compared to Logistic Regression. The model has learnt the leaf patterns of the flower! Neural networks are able to learn even highly non-linear decision boundaries, unlike logistic ... | # This may take about 2 minutes to run
plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]
for i, n_h in enumerate(hidden_layer_sizes):
plt.subplot(5, 2, i+1)
plt.title('Hidden Layer of size %d' % n_h)
parameters = nn_model(X, Y, n_h, num_iterations = 5000)
plot_decision_boundary(... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Interpretation:
- The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models overfit the data.
- The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits the data well without also incurring noticable overfitting.
- Y... | # Datasets
noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()
datasets = {"noisy_circles": noisy_circles,
"noisy_moons": noisy_moons,
"blobs": blobs,
"gaussian_quantiles": gaussian_quantiles}
### START CODE HERE ### (choose your dataset)
dat... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
The Signature Class
The goetia SourmashSignature.Signature is derived from sourmash::MinHash, and so follows the same interface. This signature will contain 10000 hashes at a $K$ of 31. | all_signature = SourmashSignature.Signature.build(10000, 31, False, False, False, 42, 0) | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
The Signature Processor
SourmashSignature contains its own sequence processor. This processor is iterable; it will process the given sequences in chunks given by fine_interval. The default fine interval is 10000. Alternatively, we can call process to consume the entire sample. | processor = SourmashSignature.Processor.build(all_signature) | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
Let's get some data. We'll start with something small, an ecoli sequencing run. | !curl -L https://osf.io/wa57n/download > ecoli.1.fastq.gz
!curl -L https://osf.io/khqaz/download > ecoli.2.fastq.gz | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
Consuming Files
The processor can handle single or paired mode natively. There's nothing special to be done with paired reads for sourmash, so the paired mode just consumes each sequence in the pair one after the other. This is a full sequencing run of ~3.5 million sequences; it should take about ten-to-twenty seconds ... | %time processor.process('ecoli.1.fastq.gz', 'ecoli.2.fastq.gz') | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
If sourmash is installed, we can convert the signature to a sourmash.MinHash object to do further analysis. | all_mh = all_signature.to_sourmash()
all_mh | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
Chunked Processing
Now let's do it in chunked mode. We'll print info on the medium interval, which is contained in the state object. | chunked_signature = SourmashSignature.Signature.build(10000, 31, False, False, False, 42, 0)
processor = SourmashSignature.Processor.build(chunked_signature, 10000, 250000)
for n_reads, n_skipped, state in processor.chunked_process('ecoli.1.fastq.gz', 'ecoli.2.fastq.gz'):
if state.medium:
print('Processed'... | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
The similarity should be exact... | chunked_mh = chunked_signature.to_sourmash()
chunked_mh.similarity(all_mh) | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
Streaming Distance Calculation
Using the chunked processor for reporting is a bit boring. A more interesting use-case is is to track within-sample distances -- streaming analysis. We'll write a quick function to perform this analysis | def sourmash_stream(left, right, N=1000, K=31):
distances = []
times = []
streaming_sig = SourmashSignature.Signature.build(N, K, False, False, False, 42, 0)
# We'll set the medium_interval to 250000
processor = SourmashSignature.Processor.build(streaming_sig, 10000, 250000)
# Calculate a dist... | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
We can see that the similarity saturates at ~2 million sequences, with the exception of a dip later on -- this could be an instrument error. If we increase the size of the signature, the saturation curve will smooth out. | distances_large, times_large, mh_large = sourmash_stream('ecoli.1.fastq.gz', 'ecoli.2.fastq.gz', N=50000)
with FigureManager(show=True, figsize=(12,8)) as (fig, ax):
sns.lineplot(times_small, distances_small, label='$N$=1,000', ax=ax)
sns.lineplot(times_large, distances_large, label='$N$=50,000', ax=ax)
ax... | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
Smaller minhashes are more susceptible to sequence error, and so the saturation curve is noisy; additionally, the larger minhash detects saturation more clearly, and the distribution of distances leans more heavily toward 1.0.
Some Signal Processing
There are a number of metrics we could use to detect "saturation": wha... | def sliding_window_stddev(distances, window_size=10):
stddevs = np.zeros(len(distances) - window_size + 1)
for i in range(0, len(distances) - window_size + 1):
stddevs[i] = np.std(distances[i:i+window_size])
return stddevs
with FigureManager(show=True, figsize=(12,8)) as (fig, ax):
cutoff = .00... | examples/Streaming Sourmash Demo.ipynb | camillescott/boink | mit |
Next we initialize two arrays to keep track of the customers who arrive and who depart: | departures = []
arrivals = [] | Data Science UA - September 2017/Lecture 07 - Simulation Modeling/Bank_Customer_Arrival_Model.ipynb | iRipVanWinkle/ml | mit |
We simulate the arrivals and departures in a bank branch using a while loop | while t < closing_time or n >= 0:
# case 1 - within business hours, a customer arrives before any customer leaves the queue
if time_arrive <= time_depart and time_arrive <= closing_time:
t = time_arrive # move time along to the time of the new arrival
... | Data Science UA - September 2017/Lecture 07 - Simulation Modeling/Bank_Customer_Arrival_Model.ipynb | iRipVanWinkle/ml | mit |
Create a new (initially empty) viewer. This starts a webserver in a background thread, which serves a copy of the Neuroglancer client, and which also can serve local volume data and handles sending and receiving Neuroglancer state updates. | viewer = neuroglancer.Viewer() | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Print a link to the viewer (only valid while the notebook kernel is running). Note that while the Viewer is running, anyone with the link can obtain any authentication credentials that the neuroglancer Python module obtains. Therefore, be very careful about sharing the link, and keep in mind that sharing the notebook w... | viewer | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Add some example layers using the precomputed data source (HHMI Janelia FlyEM FIB-25 dataset). | with viewer.txn() as s:
s.layers['image'] = neuroglancer.ImageLayer(source='precomputed://gs://neuroglancer-public-data/flyem_fib-25/image')
s.layers['segmentation'] = neuroglancer.SegmentationLayer(source='precomputed://gs://neuroglancer-public-data/flyem_fib-25/ground_truth', selected_alpha=0.3)
| python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Display a numpy array as an additional layer. A reference to the numpy array is kept only as long as the layer remains in the viewer.
Move the viewer position. | with viewer.txn() as s:
s.voxel_coordinates = [3000.5, 3000.5, 3000.5] | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Hide the segmentation layer. | with viewer.txn() as s:
s.layers['segmentation'].visible = False
import tensorstore as ts
image_vol = await ts.open({'driver': 'neuroglancer_precomputed', 'kvstore': 'gs://neuroglancer-public-data/flyem_fib-25/image/'})
a = np.zeros((200,200,200), np.uint8)
def make_thresholded(threshold):
a[...] = image_vol[300... | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Modify the overlay volume, and call invalidate() to notify the Neuroglancer client. | make_thresholded(100)
volume.invalidate() | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Select a couple segments. | with viewer.txn() as s:
s.layers['segmentation'].segments.update([1752, 88847])
s.layers['segmentation'].visible = True | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Print the neuroglancer viewer state. The Neuroglancer Python library provides a set of Python objects that wrap the JSON-encoded viewer state. viewer.state returns a read-only snapshot of the state. To modify the state, use the viewer.txn() function, or viewer.set_state. | viewer.state | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Print the set of selected segments.| | viewer.state.layers['segmentation'].segments | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Update the state by calling set_state directly. | import copy
new_state = copy.deepcopy(viewer.state)
new_state.layers['segmentation'].segments.add(10625)
viewer.set_state(new_state) | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Bind the 't' key in neuroglancer to a Python action. | num_actions = 0
def my_action(s):
global num_actions
num_actions += 1
with viewer.config_state.txn() as st:
st.status_messages['hello'] = ('Got action %d: mouse position = %r' %
(num_actions, s.mouse_voxel_coordinates))
print('Got my-action')
print(' Mouse... | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Change the view layout to 3-d. | with viewer.txn() as s:
s.layout = '3d'
s.projection_scale = 3000 | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Take a screenshot (useful for creating publication figures, or for generating videos). While capturing the screenshot, we hide the UI and specify the viewer size so that we get a result independent of the browser size. | from ipywidgets import Image
screenshot = viewer.screenshot(size=[1000, 1000])
screenshot_image = Image(value=screenshot.screenshot.image)
screenshot_image | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Change the view layout to show the segmentation side by side with the image, rather than overlayed. This can also be done from the UI by dragging and dropping. The side by side views by default have synchronized position, orientation, and zoom level, but this can be changed. | with viewer.txn() as s:
s.layout = neuroglancer.row_layout(
[neuroglancer.LayerGroupViewer(layers=['image', 'overlay']),
neuroglancer.LayerGroupViewer(layers=['segmentation'])]) | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Remove the overlay layer. | with viewer.txn() as s:
s.layout = neuroglancer.row_layout(
[neuroglancer.LayerGroupViewer(layers=['image']),
neuroglancer.LayerGroupViewer(layers=['segmentation'])]) | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Create a publicly sharable URL to the viewer state (only works for external data sources, not layers served from Python). The Python objects for representing the viewer state (neuroglancer.ViewerState and friends) can also be used independently from the interactive Python-tied viewer to create Neuroglancer links. | print(neuroglancer.to_url(viewer.state)) | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
Stop the Neuroglancer web server, which invalidates any existing links to the Python-tied viewer. | neuroglancer.stop() | python/examples/jupyter-notebook-demo.ipynb | google/neuroglancer | apache-2.0 |
下面读取上一节存储的训练集和测试集回测数据,如下所示: | abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_CN
abupy.env.g_data_fetch_mode = EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL
abu_result_tuple = abu.load_abu_result_tuple(n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME,
custom_name='train_cn')
abu_result_... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
1. A股训练集主裁训练
下面开始使用训练集交易数据训练主裁,裁判组合使用两个abupy中内置裁判AbuUmpMainDeg和AbuUmpMainPrice,两个外部自定义裁判使用‘第18节 自定义裁判决策交易‘中编写的AbuUmpMainMul和AbuUmpMainDegExtend
第一次运行select:train main ump,然后点击run select,如果已经训练过可select:load main ump直接读取以训练好的主裁: | # 需要全局设置为A股市场,在ump会根据市场类型保存读取对应的ump
abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_CN
ump_deg=None
ump_mul=None
ump_price=None
ump_main_deg_extend=None
# 使用训练集交易数据训练主裁
orders_pd_train_cn = abu_result_tuple.orders_pd
def train_main_ump():
print('AbuUmpMainDeg begin...')
AbuUmpMainDeg.ump_main_clf... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
2. 验证A股主裁是否称职
下面首先通过从测试集交易中筛选出来已经有交易结果的交易,如下: | # 选取有交易结果的数据order_has_result
order_has_result = abu_result_tuple_test.orders_pd[abu_result_tuple_test.orders_pd.result != 0] | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
order_has_result的交易单中记录了所买入时刻的交易特征,如下所示: | order_has_result.filter(regex='^buy(_deg_|_price_|_wave_|_jump)').head() | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
可以通过一个一个迭代交易单,将交易单中的买入时刻特征传递给ump主裁决策器,让每一个主裁来决策是否进行拦截,这样可以统计每一个主裁的拦截成功率,以及整体拦截率等,如下所示:
备注:
如下的代码使用abupy中再次封装joblib的多进程调度使用示例,以及abupy中封装的多进程进度条的使用示例
3.4下由于子进程中pickle ump的内部类会找不到,所以暂时只使用一个进程一个一个的处理 | def apply_ml_features_ump(order, predicter, progress, need_hit_cnt):
if not isinstance(order.ml_features, dict):
import ast
# 低版本pandas dict对象取出来会成为str
ml_features = ast.literal_eval(order.ml_features)
else:
ml_features = order.ml_features
progress.show()
# 将交易单中的买入时刻特征传递... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
通过把所有主裁的决策进行相加, 如果有投票1的即会进行拦截,四个裁判整体拦截正确率统计: | block_pd = order_has_result.filter(regex='^ump_*')
# 把所有主裁的决策进行相加
block_pd['sum_bk'] = block_pd.sum(axis=1)
block_pd['result'] = order_has_result['result']
# 有投票1的即会进行拦截
block_pd = block_pd[block_pd.sum_bk > 0]
print('四个裁判整体拦截正确率{:.2f}%'.format(block_pd[block_pd.result == -1].result.count() / block_pd.result.count() * ... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
下面统计每一个主裁的拦截正确率: | from sklearn import metrics
def sub_ump_show(block_name):
sub_block_pd = block_pd[(block_pd[block_name] == 1)]
# 如果失败就正确 -1->1 1->0
sub_block_pd.result = np.where(sub_block_pd.result == -1, 1, 0)
return metrics.accuracy_score(sub_block_pd[block_name], sub_block_pd.result) * 100, sub_block_pd.result.coun... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
3. A股训练集边裁训练
下面开始使用训练集交易数据训练训裁,裁判组合依然使用两个abupy中内置裁判AbuUmpEdgeDeg和AbuUmpEdgePrice,两个外部自定义裁判使用‘第18节 自定义裁判决策交易‘中编写的AbuUmpEdgeMul和AbuUmpEegeDegExtend,如下所示
备注:由于边裁的运行机制,所以边裁的训练非常快,这里直接进行训练,不再从本地读取裁判决策数据 | # 需要全局设置为A股市场,在ump会根据市场类型保存读取对应的ump
abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_CN
print('AbuUmpEdgeDeg begin...')
AbuUmpEdgeDeg.ump_edge_clf_dump(orders_pd_train_cn)
edge_deg = AbuUmpEdgeDeg(predict=True)
print('AbuUmpEdgePrice begin...')
AbuUmpEdgePrice.ump_edge_clf_dump(orders_pd_train_cn)
edge_p... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
4. 验证A股边裁是否称职
使用与主裁类似的方式,一个一个迭代交易单,将交易单中的买入时刻特征传递给ump边裁决策器,让每一个边裁来决策是否进行拦截,统计每一个边裁的拦截成功率,以及整体拦截率等,如下所示:
备注:如下的代码使用abupy中再次封装joblib的多进程调度使用示例,以及abupy中封装的多进程进度条的使用示例 | def apply_ml_features_edge(order, predicter, progress):
if not isinstance(order.ml_features, dict):
import ast
# 低版本pandas dict对象取出来会成为str
ml_features = ast.literal_eval(order.ml_features)
else:
ml_features = order.ml_features
# 边裁进行裁决
progress.show()
# 将交易单中的买入时刻特征传递... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
通过把所有边裁的决策进行统计, 如果有投票-1的结果即判定loss_top的拿出来和真实交易结果result组成结果集,统计四个边裁的整体拦截正确率以及拦截率,如下所示: | block_pd = order_has_result.filter(regex='^edge_*')
"""
由于predict返回的结果中1代表win top
但是我们只需要知道loss_top,所以只保留-1, 其他1转换为0。
"""
block_pd['edge_block'] = \
np.where(np.min(block_pd, axis=1) == -1, -1, 0)
# 拿出真实的交易结果
block_pd['result'] = order_has_result['result']
# 拿出-1的结果,即判定loss_top的
block_pd = block_pd[block_p... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
下面再统计每一个 边裁的拦截正确率: | from sklearn import metrics
def sub_edge_show(edge_name):
sub_edge_block_pd = order_has_result[(order_has_result[edge_name] == -1)]
return metrics.accuracy_score(sub_edge_block_pd[edge_name], sub_edge_block_pd.result) * 100, sub_edge_block_pd.shape[0]
print('角度边裁拦截正确率{0:.2f}%, 拦截交易数量{1:}'.format(*sub_edge_show... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
4. 在abu系统中开启主裁拦截模式,开启边裁拦截模式
内置边裁的开启很简单,只需要通过env中的相关设置即可完成,如下所示,分别开启主裁和边裁的两个内置裁判: | # 开启内置主裁
abupy.env.g_enable_ump_main_deg_block = True
abupy.env.g_enable_ump_main_price_block = True
# 开启内置边裁
abupy.env.g_enable_ump_edge_deg_block = True
abupy.env.g_enable_ump_edge_price_block = True
# 回测时需要开启特征生成,因为裁判开启需要生成特征做为输入
abupy.env.g_enable_ml_feature = True
# 回测时使用上一次切割好的测试集数据
abupy.env.g_enable_last_spli... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
用户自定义裁判的开启在‘第18节 自定义裁判决策交易‘ 也示例过,通过ump.manager.append_user_ump即可
注意下面还需要把10,30,50,90,120日走势拟合角度特征的AbuFeatureDegExtend,做为回测时的新的视角来录制比赛(记录回测特征),因为裁判里面有AbuUmpEegeDegExtend和AbuUmpMainDegExtend,它们需要生成带有10,30,50,90,120日走势拟合角度特征的回测交易单
代码如下所示: | feature.clear_user_feature()
# 10,30,50,90,120日走势拟合角度特征的AbuFeatureDegExtend,做为回测时的新的视角来录制比赛
feature.append_user_feature(AbuFeatureDegExtend)
# 打开使用用户自定义裁判开关
ump.manager.g_enable_user_ump = True
# 先clear一下
ump.manager.clear_user_ump()
# 把新的裁判AbuUmpMainDegExtend类名称使用append_user_ump添加到系统中
ump.manager.append_user_ump(AbuU... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
买入因子,卖出因子等依然使用相同的设置,如下所示: | # 初始化资金500万
read_cash = 5000000
# 买入因子依然延用向上突破因子
buy_factors = [{'xd': 60, 'class': AbuFactorBuyBreak},
{'xd': 42, 'class': AbuFactorBuyBreak}]
# 卖出因子继续使用上一节使用的因子
sell_factors = [
{'stop_loss_n': 1.0, 'stop_win_n': 3.0,
'class': AbuFactorAtrNStop},
{'class': AbuFactorPreAtrNStop, 'pre_atr_... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
完成裁判组合的开启,即可开始回测,回测操作流程和之前的操作一样:
下面开始回测,第一次运行select:run loop back ump,然后点击run select_ump,如果已经回测过可select:load test ump data直接从缓存数据读取: | abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_CN
abupy.env.g_data_fetch_mode = EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL
abu_result_tuple_test_ump = None
def run_loop_back_ump():
global abu_result_tuple_test_ump
abu_result_tuple_test_ump, _ = abu.run_loop_back(read_cash,
... | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
下面对比针对A股市场测试集交易开启主裁,边裁拦截和未开启主裁,边裁,结果可以看出拦截了接近一半的交易,胜率以及盈亏比都有大幅度提高: | AbuMetricsBase.show_general(*abu_result_tuple_test_ump, returns_cmp=True, only_info=True)
AbuMetricsBase.show_general(*abu_result_tuple_test, returns_cmp=True, only_info=True) | abupy_lecture/21-A股UMP决策(ABU量化使用文档).ipynb | bbfamily/abu | gpl-3.0 |
Enter name of directory that contains your data in the cell below, or...
...leave it unchanged to try out reducer with low-resolution dataset
That low-resolution dataset will expand to about 300MB when uncompressed | # To use the sample data set:
data_dir = reducer.notebook_dir.get_data_path()
# Or, uncomment line below and modify as needed
# data_dir = 'path/to/your/data'
destination_dir = '.' | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Type any comments about this dataset here
Double-click on the cell to start editing it.
Load your data set | images = ImageFileCollection(location=data_dir, keywords='*') | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Image Summary
Includes browser and image/metadata viewer
This is not, strictly speaking, part of reduction, but is a handy way to take a quick look at your files. | fits_browser = ImageBrowser(images, keys=['imagetyp', 'exposure'])
fits_browser.display() | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
You can reconfigure the image browser if you want (or not)
By passing different keys into the tree constructor you can generate a navigable tree based on any keys you want. | im_a_tree_too = ImageBrowser(images, keys=['filter', 'imagetyp', 'exposure'])
im_a_tree_too.display() | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Make a combined bias image
Reduce the bias images | bias_reduction = astro_gui.Reduction(description='Reduce bias frames',
toggle_type='button',
allow_bias=False,
allow_dark=False,
allow_flat=False,
... | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Combine bias images to make combined bias | reduced_collection = ImageFileCollection(location=destination_dir, keywords='*')
bias = astro_gui.Combiner(description="Combined Bias Settings",
toggle_type='button',
file_name_base='combined_bias',
image_source=reduced_collection,
... | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Make a combined dark
Reduce dark images | reduced_collection = ImageFileCollection(location=destination_dir, keywords='*')
dark_reduction = astro_gui.Reduction(description='Reduce dark frames',
toggle_type='button',
allow_bias=True,
master_source=redu... | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Combine reduced darks
Note the Group by option in the controls that appear after you execute the cell below. reducer will make a master for each value of the FITS keyword listed in Group by. By default this keyword is named exposure for darks, so if you have darks with exposure times of 10 sec, 15 sec and 120 sec you w... | reduced_collection = ImageFileCollection(location=destination_dir, keywords='*')
dark = astro_gui.Combiner(description="Make Combined Dark(s)",
toggle_type='button',
file_name_base='combined_dark',
group_by='exposure',
... | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Make combined flats
Reduce flat images | reduced_collection = ImageFileCollection(location=destination_dir, keywords='*')
flat_reduction = astro_gui.Reduction(description='Reduce flat frames',
toggle_type='button',
allow_bias=True,
master_source=redu... | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Build combined flats
Again, note the presence of Group by. If you typically use twilight flats you will almost certainly want to group by filter, not by filter and exposure. | reduced_collection = ImageFileCollection(location=destination_dir, keywords='*')
flat = astro_gui.Combiner(description="Make Combined Flat(s)",
toggle_type='button',
file_name_base='combined_flat',
group_by='filter',
... | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Reduce the science images
There is some autmatic matching going on here:
If darks are subtracted a dark of the same edxposure time will be used, if available. If not, and dark scaling is enabled, the dark with the closest exposure time will be scaled to match the science image.
If the dark you want to scale appears no... | reduced_collection = ImageFileCollection(location=destination_dir, keywords='*')
light_reduction = astro_gui.Reduction(description='Reduce light frames',
toggle_type='button',
allow_cosmic_ray=True,
master_... | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Wonder what the reduced images look like? Make another image browser... | reduced_collection = ImageFileCollection(location=destination_dir, keywords='*')
reduced_browser = ImageBrowser(reduced_collection, keys=['imagetyp', 'filter'])
reduced_browser.display() | reducer/reducer-template.ipynb | mwcraig/reducer | bsd-3-clause |
Reformat into a TensorFlow-friendly shape:
- convolutions need the image data formatted as a cube (width by height by #channels)
- labels as float 1-hot encodings. | image_size = 28
num_labels = 10
num_channels = 1 # grayscale
import numpy as np
def reformat(dataset, labels):
dataset = dataset.reshape(
(-1, image_size, image_size, num_channels)).astype(np.float32)
labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
return dataset, labels
train_dataset,... | deep_learning/examples/4_convolutions.ipynb | tuanvu216/udacity-course | mit |
Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes. | batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
graph = tf.Graph()
with graph.as_default():
# Input data.
tf_train_dataset = tf.placeholder(
tf.float32, shape=(batch_size, image_size, image_size, num_channels))
tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
tf_vali... | deep_learning/examples/4_convolutions.ipynb | tuanvu216/udacity-course | mit |
Create smFRET data-files
Create a file for a single FRET efficiency
In this section we show how to save a single smFRET data file. In the next section we will perform the same steps in a loop to generate a sequence of smFRET data files.
Here we load a diffusion simulation opening a file to save
timstamps in write mode.... | S = pbm.ParticlesSimulation.from_datafile('0168', mode='w')
S.particles.diffusion_coeff_counts
#S = pbm.ParticlesSimulation.from_datafile('0168') | notebooks/PyBroMo - 2. Generate smFRET data, including mixtures.ipynb | tritemio/PyBroMo | gpl-2.0 |
Simulate timestamps of smFRET
Example1: single FRET population
Define the simulation parameters with the following syntax: | params = dict(
em_rates = (200e3,), # Peak emission rates (cps) for each population (D+A)
E_values = (0.75,), # FRET efficiency for each population
num_particles = (20,), # Number of particles in each population
bg_rate_d = 1500, # Poisson background rate (cps) Donor channel
bg_rate_a ... | notebooks/PyBroMo - 2. Generate smFRET data, including mixtures.ipynb | tritemio/PyBroMo | gpl-2.0 |
Create the object that will run the simulation and print a summary: | mix_sim = pbm.TimestapSimulation(S, **params)
mix_sim.summarize() | notebooks/PyBroMo - 2. Generate smFRET data, including mixtures.ipynb | tritemio/PyBroMo | gpl-2.0 |
Run the simualtion: | rs = np.random.RandomState(1234)
mix_sim.run(rs=rs, overwrite=False, skip_existing=True) | notebooks/PyBroMo - 2. Generate smFRET data, including mixtures.ipynb | tritemio/PyBroMo | gpl-2.0 |
Save simulation to a smFRET Photon-HDF5 file: | mix_sim.save_photon_hdf5(identity=dict(author='John Doe',
author_affiliation='Planet Mars')) | notebooks/PyBroMo - 2. Generate smFRET data, including mixtures.ipynb | tritemio/PyBroMo | gpl-2.0 |
Example 2: 2 FRET populations
To simulate 2 population we just define the parameters with
one value per population, except for the Poisson background
rate that is a single value for each channel. | params = dict(
em_rates = (200e3, 180e3), # Peak emission rates (cps) for each population (D+A)
E_values = (0.75, 0.35), # FRET efficiency for each population
num_particles = (20, 15), # Number of particles in each population
bg_rate_d = 1500, # Poisson background rate (cps) Donor channel... | notebooks/PyBroMo - 2. Generate smFRET data, including mixtures.ipynb | tritemio/PyBroMo | gpl-2.0 |
Burst analysis
The generated Photon-HDF5 files can be analyzed by any smFRET burst
analysis program. Here we show an example using the opensource
FRETBursts program: | import fretbursts as fb
filepath = list(Path('./').glob('smFRET_*'))
filepath
d = fb.loader.photon_hdf5(str(filepath[1]))
d
d.A_em
fb.dplot(d, fb.timetrace);
d.calc_bg(fun=fb.bg.exp_fit, tail_min_us='auto', F_bg=1.7)
d.bg_dd, d.bg_ad
d.burst_search(F=7)
d.num_bursts
ds = d.select_bursts(fb.select_bursts.size,... | notebooks/PyBroMo - 2. Generate smFRET data, including mixtures.ipynb | tritemio/PyBroMo | gpl-2.0 |
NOTE: Unless you simulated a diffusion of 30s or more the previous histogram will be very poor. | fb.bext.burst_data(ds) | notebooks/PyBroMo - 2. Generate smFRET data, including mixtures.ipynb | tritemio/PyBroMo | gpl-2.0 |
Imports | import numpy as np
import qutip as qt
from qutip.ipynbtools import version_table | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Plotting Support | %matplotlib inline | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Settings | qt.settings.colorblind_safe = True | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Dilations of CPTP Maps
We'll start by considering the case in which $\Phi(X) = U X U^\dagger$ for a random unitary operator $U \in \Uni(\Hil_X, \Hil_X)$. | phi = qt.to_super(qt.rand_unitary_haar(4))
qt.visualization.hinton(phi) | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
By construction, $\Phi$ has one Kraus operator--- the random unitary itself. Because of numerical precision in finding eigenvalues of the Choi matrix, a decomposition will result in many operators with very small norms. | for K in qt.to_kraus(phi):
print(K.norm()) | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Because $\Phi$ only has one Kraus operator, the Stinespring dilation will use a 1-dimensional ancillary space. | A, B = qt.to_stinespring(phi)
print(A.dims) | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
If we ask for a random channel of Choi rank 2 (that is, with 2 Kraus operators), then the corresponding space will be two-dimensional instead. | A, B = qt.to_stinespring(qt.rand_super_bcsz(4, rank=2))
print(A.dims) | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Moreover, since we have demanded that $A$ and $B$ are the Stinespring pair for a channel, we can easily verify that $A = B$. | A - B | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Differences of Random Channels
Next, let's consider two random qubit channels from the [BCSZ distribution](qutip.visualization.hinton. | phi1 = qt.rand_super_bcsz(2)
phi2 = qt.rand_super_bcsz(2) | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Looking at the Pauli-basis Hinton diagram for the difference between these channels gives some insight into how this map behaves. | qt.visualization.hinton(phi1 - phi2) | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
In particular, note that $\Delta\Phi := \Phi_1 - \Phi_2$ annilates the traceful parts of its input, leaving an operator with negative eigenvalues. | d_phi = qt.to_super(phi1 - phi2)
rho_in = qt.rand_dm(2)
rho = qt.vector_to_operator(d_phi * qt.operator_to_vector(rho_in))
print("Trace: {}\nEigenvalues:{}".format(rho.tr(), rho.eigenenergies()))
rho | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Because $\Delta \Phi$ is not completely positive, we cannot obtain a Kraus decomposition where the left and right operators are the same: | Ks = qt.to_kraus(d_phi)
rho - sum(K * rho_in * K.dag() for K in Ks) | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
On the other hand, if we allow the left and right Kraus operators to be different, or consider a Stinespring dilation, we get the right answer: | A, B = qt.to_stinespring(d_phi)
rho - (A * rho_in * B.dag()).ptrace((0,)) | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Constructing System-Environment Models
For a channel $\Phi \in \Chan(\Hil_X, \Hil_X)$, once we have found the Stinespring dilation $A$, we then represent $\Phi$ as a unitary on the full space, $U \in \Uni(\Hil_X \otimes \Hil_Z)$, interpreting $\Hil_Z$ as a preparation of an environment. Concretely, we want to find $U$ ... | A, B = qt.to_stinespring(qt.rand_super_bcsz(3))
V = qt.tensor(A, qt.basis(A.dims[0][-1], 0).dag())
# This adds an annoying left index, so let's drop it now.
del V.dims[0][-1]
V
rho = qt.rand_dm_ginibre(3)
(A * rho * A.dag()).ptrace((0,)) - (V * qt.tensor(rho, qt.ket2dm(qt.basis(A.dims[0][-1], 0))) * V.dag()).ptrace((0... | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
It thus remains to extend $V$ to act non-trivially on the full space. This is done by noting that the singular values of $V$ are each one or zero, convienently partitioning $\Hil_X \otimes \Hil_Z$ into the null space of $V$ and its complement. | Vu, Vs, Vv = np.linalg.svd(V.data.todense())
U = qt.Qobj(Vu, dims=V.dims) * qt.Qobj(Vv, dims=V.dims)
U * U.dag() | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
We finish by verifying that preparing an environment state, evolving under the system/environment unitary $U$, then partial tracing over the environment produces the same map as the original channel. | (A * rho * A.dag()).ptrace((0,)) - (U * qt.tensor(rho, qt.ket2dm(qt.basis(A.dims[0][-1], 0))) * U.dag()).ptrace((0,)) | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Epilouge | version_table() | examples/example-stinespring.ipynb | zasdfgbnm/qutip-notebooks | lgpl-3.0 |
Lets look at a random image and its label | # Pull out a random image & its label
random_image_index = 200
random_image = mnist.train.images[random_image_index]
random_image_label = mnist.train.labels[random_image_index]
# Print the label and the image as grayscale
print("Image label: %d"%(random_image_label.argmax()))
pil_image = Image.fromarray(((random_image... | notebooks/Nearest Neighbors.ipynb | abhay1/tf_rundown | mit |
Nearest Neighbor Classifier
Build a nearest neighbors classifier using a subset of mnist data. | # Read only a subsample
X_train_input, Y_train_input = mnist.train.next_batch(5000)
X_test_input, Y_test_input = mnist.test.next_batch(200) | notebooks/Nearest Neighbors.ipynb | abhay1/tf_rundown | mit |
Step 1: Create placeholders to hold the images.
Using None for a dimension in shape means it can be any number. | # Create placeholders
x_train_tensor = tf.placeholder(tf.float32, shape=(None, 784))
x_test_tensor = tf.placeholder(tf.float32, shape=[784]) | notebooks/Nearest Neighbors.ipynb | abhay1/tf_rundown | mit |
Step 2: Lets build a graph using the following operations
First get the deltas along each dimension (pixel value): Use tf.substract to subtract X_train_input (train) with x_test_tensor (test).
(Note that X_train_input has 784 columns (28x28) and can have any number of rows (examples). x_test_tensor however is a vec... | # Image deltas
deltas = tf.subtract(x_train_tensor, x_test_tensor)
squared_deltas = tf.square(deltas)
# L2 distance: Root of the sum of squared deltas
distance = tf.sqrt(tf.reduce_sum(squared_deltas, axis=1))
# This is the nearest neighbor
nearest_neighbor = tf.arg_min(distance, 0) | notebooks/Nearest Neighbors.ipynb | abhay1/tf_rundown | mit |
Now lets create a session and run the graph over the entire test set | # A variable to keep track of the accuracy
accuracy = 0
# Initializing global variables
init = tf.global_variables_initializer()
# Create a session to run the graph
with tf.Session() as sess:
# Run initialization
sess.run(init)
# Loop over all the test data
for i in range(len(X_test_input)):
... | notebooks/Nearest Neighbors.ipynb | abhay1/tf_rundown | mit |
Now we can extend this to more than just one nearest neighbor and feed "k" in at runtime. | # Lets create a placeholder for k
k = tf.placeholder(tf.int32)
# Distances computation doesn't change.
# Create a new variable that holds a vector of nearest neighbors
# Use the top k function but flip the distance scores with a engative sign
# K is fed in
# The top k returns both values and indicies as a tuple. Usin... | notebooks/Nearest Neighbors.ipynb | abhay1/tf_rundown | mit |
Exercice 1 : Constuire l'ensemble des lettres supprimées et ajoutées
Deux mots n'ont pas forcément la même longueur, il est donc difficile de les comparer lettre à lettre. De même, on ne doit pas tenir compte de l'ordre des lettres dans chaque mot. Cette contrainte peut paraître plus difficile à mettre en oeuvre. Pourt... | def compte_lettre(mot):
d = {}
for c in mot:
d[c] = d.get(c,0) + 1
return d
compte_lettre("lettre"), compte_lettre("etre") | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
Une lettre est ajoutée ou supprimée entre deux mots si son décompe est différent dans les deux dictionnaires. On s'en sert pour contruire la liste des lettres supprimées et ajoutées. Cela revient à construire la différence entre deux dictionnaires. | mot1 = "lettre"
mot2 = "etres"
d1 = compte_lettre(mot1)
d2 = compte_lettre(mot2)
suppression = {}
for l in d1:
c1 = d1[l]
c2 = d2.get(l, 0) # la lettre l n'appartient pas forcément au second mot
if c2 != c1:
suppression[l] = c2 - c1
ajout = {}
for l in d2:
if l not in d1:
c1 ... | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
Exercice 2 : écrire une fonction qui calcule la distance de Jaccard
On copie et on colle le code précédent pour créer la distance. | def jaccard(mot1, mot2):
d1 = compte_lettre(mot1)
d2 = compte_lettre(mot2)
suppression = {}
for l in d1:
c1 = d1[l]
c2 = d2.get(l, 0) # la lettre l n'appartient pas forcément au second mot
if c2 != c1:
suppression[l] = c2 - c1
ajout = {}
for l in d2:
... | _doc/notebooks/td1a_algo/td1a_correction_session4_5_jaccard.ipynb | sdpython/ensae_teaching_cs | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.