markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Let's quickly define a function to plot one of the digits, we will need it later down the line. It might also be useful to have a function to plot multiple digits in a batch (we will also use this function later). The following two cells will not produce any output. | def plot_digit(data):
image = data.reshape(28, 28)
plt.imshow(image, cmap = mpl.cm.binary,
interpolation="nearest")
plt.axis("off")
def plot_digits(instances, images_per_row=10, **options):
size = 28
images_per_row = min(len(instances), images_per_row)
images = [instance.reshape(s... | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Great, now we can plot multiple digits at once. Let's ignore the details of the `np.r_[]` function and the indexing used within it for now and focus on what it does: it takes ten examples of each digit from the data array, which we can then plot with our `plot_digits()` function. | plt.figure(figsize=(9,9))
example_images = np.r_[X[:12000:600], X[13000:30600:600], X[30600:60000:590]]
plot_digits(example_images, images_per_row=10)
save_fig("more_digits_plot")
plt.show() | Saving figure more_digits_plot
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Ok, at this point we have a fairly good idea how our data array looks like: we have an array of 70,000 images with 28x28 pixels each. The entries in the array are sorted according to ascending digits, i.e. it starts with images of zeros and ends with images of nines at entry 59,999. Entries `x[60000:]` onwards are mean... | y[36000] | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Good! As a very last step, let's split train and test and store them separately. Because we also don't want our training to be biased, we should shuffle the entries randomly (i.e. not sort them in ascending order anymore). We can do this with the `np.random.permutation(60000)` function which returns a random permutatio... | X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]
import numpy as np
shuffle_index = np.random.permutation(60000)
X_train, y_train = X_train[shuffle_index], y_train[shuffle_index] | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Binary classifier Before going towards a classifier, which can distinguish _all_ digits, let's start with something simple. Since our random digit `X[36000]` was a five, why not design a classifier that can distinguish fives from other digits? Let's first rewrite our labels from integers to booleans: | y_train_5 = (y_train == 5) # an array of booleans which is 'True' whenever y_train is == 5
y_test_5 = (y_test == 5)
y_train_5 # let's look at the array | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
A good model for the classification is the Stochastic Gradient Descent that was introduced in the lecture. Conveniently, Skiki-Learn already has such a classifier implemented, so let's import it and give it our training data `X_train` with the true labels `y_train_5`. | from sklearn.linear_model import SGDClassifier
# SDG relies on randomness, but by fixing the `random_state` we can get reproducible results.
# The other values are just to avoid a warning issued by Skikit-Learn ...
sgd_clf = SGDClassifier(random_state=42, max_iter=5, tol=-np.infty)
sgd_clf.fit(X_train, y_train_5) | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
If the training of the classifier was successful, it should be able to predict the label of our example instance `X[36000]` correctly. | sgd_clf.predict([some_digit]) | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
That's good, but it doesn't really give us an idea about the overall performance of the classifier. One good measure for this introduced in the lecture is the cross-validation score. In k-fold cross-validation, the training data is split into k equal subsets. Then the classifier is trained on k-1 sets and evaluated on ... | from sklearn.model_selection import cross_val_score
cross_val_score(sgd_clf, X_train, y_train_5, cv=3, scoring="accuracy") | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
While these numbers seem amazingly good, keep in mind, that only 10% of our training data are images of fives, so even a classifier which always predicts 'not five' would reach an accuracy of about 90% ...In the following box, maybe you can try to implement the cross validation yourself! The `StratifiedKFold` creates k... | from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone
skfolds = StratifiedKFold(n_splits=3, random_state=42)
for train_indices, test_indices in skfolds.split(X_train, y_train_5):
clone_clf = clone(sgd_clf) # make a clone of the classifier
# [...] some code is missing here
X_... | Fraction of correct predictions: 0.9502
Fraction of correct predictions: 0.96565
Fraction of correct predictions: 0.96495
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Let's move on to another performance measure: the confusion matrix. The confusion matrix is a 2x2 matrix and includes the number of true positives, false positives (type-I error), true negatives and false negatives (type-II error). First, let's use another of Scitkit-Learn's functions: `cross_val_predict` takes our cla... | from sklearn.model_selection import cross_val_predict
# Take our SGD classifer and perform a 3-fold cross-validation.
y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3)
# Print some of the predicted labels.
print(y_train_pred) | [False False False ... False False False]
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Using cross-validation always gives us a 'clean', i.e. unbiased estimate of our prediction power, because the performance of the classifier is evaluated on data it hadn't seen during training. Now we have our predicted labels in `y_train_pred` and can compare them to the true labels `y_train_5`. So let's create a confu... | from sklearn.metrics import confusion_matrix
confusion_matrix(y_train_5, y_train_pred) | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
How do we read this? The rows correspond to the _true_ classes, the columns to the _predicted_ classes. So the 53,272 means that about fifty-three thousand numbers that are 'not five' were predicted as such, while 1307 were predicted to be fives. 4344 true fives were predicted to be fives, but 1077 were not. Sometimes ... | matrix = confusion_matrix(y_train_5, y_train_pred)
row_sums = matrix.sum(axis=1)
matrix / row_sums[:, np.newaxis] | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
There are other metrics to evaluate the performance of classifiers as we saw in the lecture. One example is the _precision_ which is the rate of true positives among all positives. The precision is a measure how many of our predicted positives are _actually_ positives, i.e. it can be calculated as TP / (TP + FP) (TP = ... | from sklearn.metrics import precision_score, recall_score
print(precision_score(y_train_5, y_train_pred))
# Can you reproduce this value by hand? All info should be in the confusion matrix.
tp = matrix[1][1]
fp = matrix[0][1]
precision_by_hand = tp / (tp + fp)
print("By hand: %s" % precision_by_hand) | 0.7687135020350381
By hand: 0.7687135020350381
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Or in words: 77% of our predicted fives are _actually_ fives, while 23% of the predicted fives are other numbers.Another metric, which is often used in conjunction with the _precision_, is the _recall_. The recall is a measure of how many of the true positives as predicted as such, i.e. "how many true positives do we i... | print(recall_score(y_train_5, y_train_pred))
# Again, it should be straight-forward to make this calculation by hand. Can you try?
tp = matrix[1][1]
fn = matrix[1][0]
recall_by_hand = tp / (tp + fn)
print("By hand: %s" % recall_by_hand) | 0.801328168234643
By hand: 0.801328168234643
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
In words: only 80% of the fives are correctly predicted to be fives. Doesn't look as great as the 95% prediction rate, does it? A nice combination for precision and recall is their harmonic mean, usually known (and in the lecture introduced as) the _F_1 score_. The harmonic mean (as opposed to the arithmetic mean) is v... | from sklearn.metrics import f1_score
print(f1_score(y_train_5, y_train_pred))
# Once more, it is fairly easy to calculate this by hand. Give it a try!
f1_score_by_hand = 2 / (1/precision_by_hand + 1/recall_by_hand)
print("By hand: %s" % f1_score_by_hand) | 0.7846820809248555
By hand: 0.7846820809248556
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Of course, a balanced precision and recall is not _always_ desirable. Whether you want both to be equally high, depends on the use case. Sometimes, you'd definitely want to classify as many true positives as such, with the tradeoff to have low precision (example: in a test for a virus you want every true positive to kn... | y_scores = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3,
method="decision_function")
print(y_scores) # Print scores to get an idea ... | [ -434076.49813641 -1825667.15281624 -767086.76186905 ...
-867191.25267994 -565357.11420164 -366599.16018198]
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
This again gives us a numpy array with 60,000 entries, all of which contain a floating point value with the predicted score. Now, as we've seen before, Scikit-Learn provides many functions out-of-the-box to evaluate classifiers. The following `precision_recall_curve` metric gives us tuples of precision, recall and thre... | from sklearn.metrics import precision_recall_curve
precisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores)
print(precisions)
def plot_precision_recall_vs_threshold(precisions, recalls, thresholds):
plt.plot(thresholds, precisions[:-1], "b--", label="Precision", linewidth=2)
plt.plot(thres... | Saving figure precision_recall_vs_threshold_plot
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Looks good! Bonus question: why is the precision curve bumpier than the recall?Let's assume we want to optimise our classfier for a precision value of 93%. Can you find a good threshold? The below threshold is just a test value and definitely too low. | threshold = -20000
y_train_pred_93 = (y_scores > threshold)
print("precision: %s" % precision_score(y_train_5, y_train_pred_93))
print("recall: %s" % recall_score(y_train_5, y_train_pred_93)) | precision: 0.7297430021280079
recall: 0.8223574986164914
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Sometimes, plotting precision vs. recall can also be helpful. | def plot_precision_vs_recall(precisions, recalls):
plt.plot(recalls, precisions, "b-", linewidth=2)
plt.xlabel("Recall", fontsize=16)
plt.ylabel("Precision", fontsize=16)
plt.axis([0, 1, 0, 1])
plt.figure(figsize=(8, 6))
plot_precision_vs_recall(precisions, recalls)
save_fig("precision_vs_recall_plot")... | Saving figure precision_vs_recall_plot
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
ROC curvesBecause it's an extremely common performance measure, we should also have a look at the ROC curve (_receiver operating characteristic_). ROC curves plot true positives vs. false positives, or usually the true positive _rate_ vs. the false positive _rate_. While the first is exactly what we called _recall_ so... | from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_train_5, y_scores) | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Now we can plot them: | def plot_roc_curve(fpr, tpr, label=None):
plt.plot(fpr, tpr, linewidth=2, label=label)
plt.plot([0, 1], [0, 1], 'k--')
plt.axis([0, 1, 0, 1])
plt.xlabel('False Positive Rate', fontsize=16)
plt.ylabel('True Positive Rate', fontsize=16)
plt.figure(figsize=(8, 6))
plot_roc_curve(fpr, tpr)
save_fig("ro... | Saving figure roc_curve_plot
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
It is always desirable to have the curve as close to the top left corner as above. As a measure for this, one usually calculates the _area under curve_. What is the AUC value for a random classifier? | from sklearn.metrics import roc_auc_score
roc_auc_score(y_train_5, y_scores) | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Multiclass classificationSo far we have completely ignored the fact that our training data not only includes fives and 'other digits', but in fact ten different input labels (one for each digit). Multiclass classification will allow us to distinguish each of them individually and predict the _most likely class_ for ea... | sgd_clf.fit(X_train, y_train) | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
How does it classify our previous example of something that looked like a five? | sgd_clf.predict([some_digit]) | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Great! But what exactly happens under the hood? It actually calculates ten different scores for the ten different binary classifiers and picks the class with the highest score. We can see this by calling the `decision_function()` as we did earlier: | some_digit_scores = sgd_clf.decision_function([some_digit])
print(some_digit_scores) # Print us the array content
print("Largest entry: %s" % np.argmax(some_digit_scores)) # Get the index of the largest entry | [[-311402.62954431 -363517.28355739 -446449.5306454 -183226.61023518
-414337.15339485 161855.74572176 -452576.39616343 -471957.14962573
-518542.33997148 -536774.63961222]]
Largest entry: 5
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Scikit-Learn even comes with a class to run the one-versus-one approach as well. We can just give it our SGD classifier instance and then call the `fit()` function on it: | from sklearn.multiclass import OneVsOneClassifier
ovo_clf = OneVsOneClassifier(sgd_clf)
ovo_clf.fit(X_train, y_train)
# What does it predict for our random five?
ovo_clf.predict([some_digit]) | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
And how many classifiers does this one-versus-one approach need? Can you come up with the formula? | print("Number of estimators: %s" % len(ovo_clf.estimators_)) | Number of estimators: 45
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Back to the one-versus-all approach – how good are we? For that, we can calculate the cross-validation score once more to get values for the accuracy. Bear in mind that now we are running a _ten-class_ classification! | cross_val_score(sgd_clf, X_train, y_train, cv=3, scoring="accuracy") | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
This is not bad at all, although you could probably spend hours optimising the hyperparameters of this model. How good does the onve-versus-one approach perform? Try it out!Let's look at some other performance measures for the one-versus-all classifier. A good point to start is the confusing matrix. | y_train_pred = cross_val_predict(sgd_clf, X_train, y_train, cv=3)
conf_mx = confusion_matrix(y_train_pred, y_train)
conf_mx | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Ok, maybe it's better to display this in a plot: | def plot_confusion_matrix(matrix):
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
plt.xlabel('Predicted class', fontsize=16)
plt.ylabel('True class', fontsize=16)
cax = ax.matshow(matrix)
fig.colorbar(cax)
plot_confusion_matrix(conf_mx)
save_fig("confusion_matrix_plot", tight_lay... | Saving figure confusion_matrix_plot
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
It's still very hard to see what's going on. So maybe we should (1) normalise the matrix by rows again, (2) "remove" all diagonal entries, because those are not interesting for us for the error analysis. | row_sums = conf_mx.sum(axis=1, keepdims=True)
norm_conf_mx = conf_mx / row_sums
np.fill_diagonal(norm_conf_mx, 0)
plot_confusion_matrix(norm_conf_mx)
save_fig("confusion_matrix_errors_plot", tight_layout=False)
plt.show() | Saving figure confusion_matrix_errors_plot
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
It seems we're predicting many of the eights wrong. In particular, many of them are predicted to be a five! On the other hand, not many fives are misclassified as eights. Interesting, right? Let's pick out some eights and fives, each of which are either correctly predicted, or predicted as the other class. Maybe lookin... | cl_a, cl_b = 8, 5 # Define class a and class b for the plot
# Training data from class a, which is predicted as a.
X_aa = X_train[(y_train == cl_a) & (y_train_pred == cl_a)]
# Training data from class a, which is predicted as b.
X_ab = X_train[(y_train == cl_a) & (y_train_pred == cl_b)]
# Training data from class ... | Saving figure error_analysis_digits_plot
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
"Build Your First Neural Network with PyTorch" * article * dataset requires `torch 1.4.0` | import os
from os.path import dirname
import numpy as np
import pandas as pd
from tqdm import tqdm
import seaborn as sns
from pylab import rcParams
import matplotlib.pyplot as plt
from matplotlib import rc
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classificatio... | net(t) 0.506089448928833
| MIT | wip/nn4.ipynb | ArenasGuerreroJulian/kglab |
SoftwareDesign 2020年10月号 第1特集 Pythonではじめる統計学 第1章 統計分析に必須のライブラリ リスト1 | import seaborn as sns
tips = sns.load_dataset("tips")
sns.catplot(
data=tips, x="time", y="tip", kind="violin"
) | _____no_output_____ | BSD-2-Clause | SoftwareDesign202010_0101.ipynb | zfukuoka/Copying_a_sutra |
リスト2標本空間が $\{a_1, \dotsc, a_n\}$ であるとき、その算術平均 $(\displaystyle A)$ は次のとおりに定義される。$$A = \frac{1}{n}\sum_{k=1}^{n} a_k = \frac{a_1 + a_2 + \dotsb + a_n}{n}$$ NumPy入門 ndarray型 | import numpy as np
int_arr = np.array([1, 2])
int_arr.dtype
float_arr = np.array([1, 2], dtype=np.float32)
float_arr.dtype
float_arr.astype(np.int) | _____no_output_____ | BSD-2-Clause | SoftwareDesign202010_0101.ipynb | zfukuoka/Copying_a_sutra |
ndarrayオブジェクト生成 | np.arange(3)
np.arange(0, 2.5, 0.5)
np.zeros(3)
np.ones([2, 3])
np.random.seed(1)
np.random.rand(3,3)
arr1 = np.arange(1, 4)
arr1
arr2 = np.arange(1, 13).reshape(4, 3)
arr2 | _____no_output_____ | BSD-2-Clause | SoftwareDesign202010_0101.ipynb | zfukuoka/Copying_a_sutra |
要素へのアクセス | arr1[0]
arr1[1:3]
arr2[0]
arr2[1, 2]
arr2[0, 1:3]
arr1[1] = 10
arr1
arr2[1, :2] = 100
arr2 | _____no_output_____ | BSD-2-Clause | SoftwareDesign202010_0101.ipynb | zfukuoka/Copying_a_sutra |
ブロードキャスト | li = [1, 2, 3]
[x + 1 for x in li]
arr1 = np.array([1, 2, 3])
arr1 + 1
# 前述のコードから続けてそのまま動かすと、テキストと異なる結果になる
# 恐らく、arr2を途中で変えたことを忘れたか、無視したものと考えられる
# このため、テキストにはないが改めてarr2の初期化を行う
arr2 = np.arange(1, 13).reshape(4, 3)
arr1 + arr2 | _____no_output_____ | BSD-2-Clause | SoftwareDesign202010_0101.ipynb | zfukuoka/Copying_a_sutra |
関数の適用 | np.power(arr1, arr2)
abs(np.array([1, -2, 3]))
sum(np.array([1, 2, 3]))
def my_func(x):
return x ** 2 + 1
my_func(arr1) | _____no_output_____ | BSD-2-Clause | SoftwareDesign202010_0101.ipynb | zfukuoka/Copying_a_sutra |
Scraping transfermarkt by html | from selenium.webdriver import (Chrome, Firefox)
import time
import requests
from bs4 import BeautifulSoup
from html_scraper import db
players = db['players']
player_urls = db['player_urls']
browser = Firefox()
url = 'https://www.transfermarkt.co.uk/primera-division/startseite/wettbewerb/AR1N'
browser.get(url)
elems =... | _____no_output_____ | MIT | scraping_tools/trans_markt_scraper_instructions.ipynb | d-v-dlee/super_liga_xg |
Go from club_url to detailed page club_url | detailed_url = []
for url in url_links:
change_url = url.replace('startseite', 'kader')
url_final = change_url + '/plus/1'
detailed_url.append(url_final)
detailed_url | _____no_output_____ | MIT | scraping_tools/trans_markt_scraper_instructions.ipynb | d-v-dlee/super_liga_xg |
old code... skip down to scraping to DBMongo step | from html_scraper import scrape_player_info
scrape_player_info(detailed_url, delay=15)
db
club1 = detailed_url[0]
browser.get(club1)
sel = 'td.hauptlink a'
link_elements = browser.find_elements_by_css_selector(sel)
print(link_elements[0].text)
sel = 'td.zentriert'
link_elements = browser.find_elements_by_css_selector(s... | _____no_output_____ | MIT | scraping_tools/trans_markt_scraper_instructions.ipynb | d-v-dlee/super_liga_xg |
Scraping to DB Mongo | db_urls = detailed_url.copy()
db_urls
from html_scraper import get_all_player_data_from_url, team_scrape
teams = [get_all_player_data_from_url(url) for url in db_urls]
from html_scraper import add_player_to_db
import pandas as pd
for url in db_urls:
player_data = get_all_player_data_from_url(url)
print(url)
... | https://www.transfermarkt.co.uk/club-atletico-boca-juniors/kader/verein/189/saison_id/2018/plus/1
https://www.transfermarkt.co.uk/ca-independiente-de-avellaneda/kader/verein/1234/saison_id/2018/plus/1
https://www.transfermarkt.co.uk/club-atletico-river-plate/kader/verein/209/saison_id/2018/plus/1
https://www.transferma... | MIT | scraping_tools/trans_markt_scraper_instructions.ipynb | d-v-dlee/super_liga_xg |
check db | db.players
players = db.players.find()
players.count()
master_list = []
for player in players:
master_list.append(player)
master_list
pd.DataFrame(master_list)
| _____no_output_____ | MIT | scraping_tools/trans_markt_scraper_instructions.ipynb | d-v-dlee/super_liga_xg |
Boolean Operators | a=1
b=2
print(a>b)
print(a<b)
print(a==b)
print(a!=b) | False
True
False
True
| Apache-2.0 | Expressions_and_Operations.ipynb | EJ-Capito/CPEN-21A-ECE-2-3 |
bool() function | print(bool(15))
print(bool(True))
print(bool(1))
print(bool(False))
print(bool(0))
print(bool(None))
print(bool([])) | True
True
True
False
False
False
False
| Apache-2.0 | Expressions_and_Operations.ipynb | EJ-Capito/CPEN-21A-ECE-2-3 |
Functions return a Boolean | def myFunction():return False
if myFunction():
print("True")
else:
print("False") | False
| Apache-2.0 | Expressions_and_Operations.ipynb | EJ-Capito/CPEN-21A-ECE-2-3 |
Arithmetic Operator | print(10>9)
print(10<9)
print(10==9)
print(10+5)
print(10-5)
print(10*5)
print(10/5)
print(10%5)
print(10//3)
print(10**2) | True
False
False
15
5
50
2.0
0
3
100
| Apache-2.0 | Expressions_and_Operations.ipynb | EJ-Capito/CPEN-21A-ECE-2-3 |
Bitwise operators | a=60 #0011 1100
b=13 #0000 1101
print(a & b)
print(a | b)
print(a^b)
print(a<<2) #0011 1100
print(a>>1) #0000 1101 | 12
61
49
240
30
| Apache-2.0 | Expressions_and_Operations.ipynb | EJ-Capito/CPEN-21A-ECE-2-3 |
Assignment Operator | a+=3 #Same as a=a+3, a=60+3, a=63
print(a) | 63
| Apache-2.0 | Expressions_and_Operations.ipynb | EJ-Capito/CPEN-21A-ECE-2-3 |
Logical Operator | a = True
b = False
print(a and b)
print(a or b)
print(not(a or b))
print(a > b and b > a)
print(a==a or b==b)
print(not(a==a or b==b)) | False
True
False
False
True
False
| Apache-2.0 | Expressions_and_Operations.ipynb | EJ-Capito/CPEN-21A-ECE-2-3 |
Identify Operators | print(a is b)
print(a is not b) | _____no_output_____ | Apache-2.0 | Expressions_and_Operations.ipynb | EJ-Capito/CPEN-21A-ECE-2-3 |
Here i run for 30 epochs but in 25 epcohs i got validation accuracy as 99.40%. | _____no_output_____ | Apache-2.0 | MNIST_data_set_with_pure_Convolution.ipynb | Jyotiranjan404/Pure-CNN-using-MNIST-dataset | |
Copyright 2018 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Phân loại cơ bản: Dự đoán ảnh quần áo giày dép Xem trên TensorFlow.org Chạy trên Google Colab Xem mã nguồn trên GitHub Tải notebook **Lưu ý:** Cộng đồng TensorFlow tại Việt Nam đã và đang dịch những tài liệu này từ nguyên bản tiếng Anh.Những bản dịch này được hoàn thiện dựa trên sự nỗ lực ... | # TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Import tập dữ liệu về quần áo và giày dép từ Fashion MNIST Chúng ta sẽ dùng tập dữ liệu về quần áo và giày dép từ [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist), chứa khoảng 70,000 ảnh đen trắng phân thành 10 loại. Mỗi một ảnh là một loại quần áo hoặc giày dép với độ phân giải thấp (28 by 28 pixel),... | fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Tập dữ liệu sau khi được tải sẽ trả về 4 mảng NumPy:* 2 mảng `train_images` và `train_labels` là *tập huấn luyện*. Mô hình sẽ học từ dữ liệu của 2 mảng này.* 2 mảng `test_images` vả `test_labels` là *tập kiểm thử*. Sau khi mô hình được huấn luyện xong, chúng ta sẽ chạy thử mô hình với dữ liệu đầu vào từ `test_images` đ... | class_names = ['Áo thun', 'Quần dài', 'Áo liền quần', 'Đầm', 'Áo khoác',
'Sandal', 'Áo sơ mi', 'Giày', 'Túi xách', 'Ủng'] | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Khám phá dữ liệuChúng ta có thể khám phá dữ liệu một chút trước khi huấn luyện mô hình. Câu lệnh sau sẽ cho ta thấy có 60.000 ảnh trong tập huấn luyện, với mỗi ảnh được biểu diễn theo dạng 28x28 pixel: | train_images.shape | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Tương tự, tập huấn luyện cũng có 60.000 nhãn đối ứng: | len(train_labels) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Mỗi nhãn là một số nguyên từ 0 đến 9: | train_labels | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Có 10.000 ảnh trong tập kiểm thử, mỗi ảnh cũng được biểu diễn ở dãng 28 x 28 pixel: | test_images.shape | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Và tập kiểm thử cũng chứa 10,000 nhãn: | len(test_labels) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Tiền xử lý dữ liệuDữ liệu cần được tiền xử lý trước khi được dùng để huấn luyện mạng neuron. Phân tích ảnh đầu tiên trong tập dữ liệu, chúng ta sẽ thấy các pixel có giá trị từ 0 đến 255: | plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show() | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Chúng ta cần tiền xử lý để mỗi một điểm ảnh có giá trị từ 0 đến 1 (có thể hiểu là 0% đến 100%). Để làm điều này, chúng ta chỉ cần lấy giá trị của pixel chia cho 255. Cần lưu ý rằng việc tiền xử lý này phải được áp dụng đồng thời cho cả *tập huấn luyện* và *tập kiểm thử*: | train_images = train_images / 255.0
test_images = test_images / 255.0 | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Để chắc chắn việc tiền xử lý diễn ra chính xác, chúng ta có thể in ra 25 ảnh đầu trong *tập huấn luyện* cùng với tên lớp dưới mỗi ảnh. | plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show() | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Xây dựng mô hìnhĐể xây dựng mạng neuron, chúng tay cần cấu hình các layer của mô hình, và sau đó biên dịch mô hình. Thiết lập các layersThành phần cơ bản của một mạng neuron là các *layer*. Các layer trích xuất các điểm đặc biệt từ dữ liệu mà chúng đón nhận. Khi thực hiện tốt, những điểm đặc biệt này mang nhiều ý ngh... | model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
]) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Trong mạng neuron trên, lớp đầu tiên, `tf.keras.layers.Flatten`, chuyển đổi định dạng của hình ảnh từ mảng hai chiều (28x28) thành mảng một chiều (28x28 = 784). Tưởng tương công việc của layer này là cắt từng dòng của anh, và ghép nối lại thành một dòng duy nhất nhưng dài gấp 28 lần. Lớp này không có trọng số để học, n... | model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Huấn luyện mô hìnhHuấn luyện mô hình mạng neuron cần các bước sau:1. Cung cấp dữ liệu huấn luyện cho mô hình. Trong ví dụ này, dữ liệu huấn luyện năm trong 2 mảng `train_images` và `train_labels`2. Mô hình sẽ học cách liên kết ảnh với nhãn.3. Chúng ta sẽ yêu cầu mô hình đưa ra dự đoán từ dữ liệu của tập kiểm thử, tron... | model.fit(train_images, train_labels, epochs=10) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Trong quá trình huấn luyện, các số liệu như thiệt hại và hay độ chính xác được hiển thị. Với dữ liệu huấn luyện này, mô hình đạt đến độ accuracy vào khoảng 0.88 (88%). Đánh giá mô hìnhTiếp theo, chúng đánh giá các chất lượng của mô hình bằng tập kiểm thử: | test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Đến thời điểm này, chúng ta thấy rằng độ accuracy của mô hình, khi đánh giá bằng tập kiểm thử, hơi thấp hơn so với số liệu trong quá trình huấn luyện. Khoảng cách giữa hai độ accuracy khi huấn luyện và khi kiểm thử thể hiện sự *overfitting*. Overfitting xảy ra khi một mô hình ML hoạt động kém hơn khi được cung cấp các ... | predictions = model.predict(test_images) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Ở đây, mô hình sẽ dự đoán nhãn cho từng hình ảnh trong bộ thử nghiệm. Hãy xem dự đoán đầu tiên: | predictions[0] | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Trong ví dụ này, dự đoán là một mảng 10 số thực, mỗi số tương ứng với "độ tự tin" của mô hình rằng ảnh đó thuộc về nhãn đó. Chúng ta có thể thấy nhãn nào có độ tư tin cao nhất: | np.argmax(predictions[0]) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Vậy là mô hình tự tin nhất rằng ảnh này là một loại ủng, hoặc `class_names[9]`. Đối chiếu với nhãn trong tập kiểm thử, ta thấy dự đoán này là đúng: | test_labels[0] | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Ta thử vẽ biểu đồ để xem các dự đoán trên cả 10 lớp của mô hình. | def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
colo... | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Chúng ta có thể nhìn vào ảnh 0th, các dự đoán, và mảng dự đoán.Nhãn dự đoán đúng màu xanh và nhãn sai màu đỏ. Con số là số phần trăm của các nhãn được dự đoán. | i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_v... | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Thử vẽ biểu đồ với vài ảnh và dự đoán đi kèm. Chú ý thấy rằng mô hình đôi khi dự đoán sai dù điểm tự tin rất cao. | # Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1... | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Cuối cùng, dùng mô hình để đưa ra dự đoán về một ảnh duy nhất. | # Grab an image from the test dataset.
img = test_images[1]
print(img.shape) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Các mô hình `tf.keras` được tối ưu hóa để đưa ra dự đoán về một *lô* hoặc bộ sưu tập các ví dụ cùng một lúc. Theo đó, mặc dù bạn đang sử dụng một ảnh duy nhất, bạn cần thêm nó vào list: | # Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0))
print(img.shape) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Dự đoán nhãn cho ảnh này: | predictions_single = model.predict(img)
print(predictions_single)
plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
`model.predict` trả về một list của lists — mỗi list cho mỗi ảnh trong lô dữ liệu. Lấy dự đoán cho hình ảnh trong lô: | np.argmax(predictions_single[0]) | _____no_output_____ | Apache-2.0 | site/vi/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Convolutional Neural Networks: ApplicationWelcome to Course 4's second assignment! In this notebook, you will:- Implement helper functions that you will use when implementing a TensorFlow model- Implement a fully functioning ConvNet using TensorFlow **After this assignment you will be able to:**- Build and train a Con... | import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
import tensorflow as tf
from tensorflow.python.framework import ops
from cnn_utils import *
%matplotlib inline
np.random.seed(1) | _____no_output_____ | MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
Run the next cell to load the "SIGNS" dataset you are going to use. | # Loading the data (signs)
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset() | _____no_output_____ | MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
As a reminder, the SIGNS dataset is a collection of 6 signs representing numbers from 0 to 5.The next cell will show you an example of a labelled image in the dataset. Feel free to change the value of `index` below and re-run to see different examples. | # Example of a picture
index = 5
plt.imshow(X_train_orig[index])
print ("y = " + str(np.squeeze(Y_train_orig[:,index]))) | y = 4
| MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
In Course 2, you had built a fully-connected network for this dataset. But since this is an image dataset, it is more natural to apply a ConvNet to it.To get started, let's examine the shapes of your data. | X_train = X_train_orig/255
X_test = X_test_orig/255
Y_train = convert_to_one_hot(Y_train_orig, 6).T #.T used for transpose
Y_test = convert_to_one_hot(Y_test_orig, 6).T
print ("number of training examples = " + str(X_train.shape[0]))
print ("number of test examples = " + str(X_test.shape[0]))
print ("X_train shape: " +... | number of training examples = 1080
number of test examples = 120
X_train shape: (1080, 64, 64, 3)
Y_train shape: (1080, 6)
X_test shape: (120, 64, 64, 3)
Y_test shape: (120, 6)
| MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
1.1 - Create placeholdersTensorFlow requires that you create placeholders for the input data that will be fed into the model when running the session.**Exercise**: Implement the function below to create placeholders for the input image X and the output Y. You should not define the number of training examples for the m... | # GRADED FUNCTION: create_placeholders
def create_placeholders(n_H0, n_W0, n_C0, n_y):
"""
Creates the placeholders for the tensorflow session.
Arguments:
n_H0 -- scalar, height of an input image
n_W0 -- scalar, width of an input image
n_C0 -- scalar, number of channels of the input
n_... | X = Tensor("Placeholder:0", shape=(?, 64, 64, 3), dtype=float32)
Y = Tensor("Placeholder_1:0", shape=(?, 6), dtype=float32)
| MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
**Expected Output** X = Tensor("Placeholder:0", shape=(?, 64, 64, 3), dtype=float32) Y = Tensor("Placeholder_1:0", shape=(?, 6), dtype=float32) 1.2 - Initialize parametersYou will initialize weights/filters $W1$ and $W2$ using `tf.contrib.layers.xavier_initializer(seed = 0)`. You don't need to worry about bias ... | # GRADED FUNCTION: initialize_parameters
def initialize_parameters():
"""
Initializes weight parameters to build a neural network with tensorflow. The shapes are:
W1 : [4, 4, 3, 8]
W2 : [2, 2, 8, 16]
Returns:
parameters -- a dictionary of tensors containi... | W1 = [ 0.00131723 0.14176141 -0.04434952 0.09197326 0.14984085 -0.03514394
-0.06847463 0.05245192]
W2 = [-0.08566415 0.17750949 0.11974221 0.16773748 -0.0830943 -0.08058
-0.00577033 -0.14643836 0.24162132 -0.05857408 -0.19055021 0.1345228
-0.22779644 -0.1601823 -0.16117483 -0.10286498]
| MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
** Expected Output:** W1 = [ 0.00131723 0.14176141 -0.04434952 0.09197326 0.14984085 -0.03514394 -0.06847463 0.05245192] W2 = [-0.08566415 0.17750949 0.11974221 0.16773748 -0.0830943 -0.08058 -0.00577033 -0.14643836 0.24162132... | # GRADED FUNCTION: forward_propagation
def forward_propagation(X, parameters):
"""
Implements the forward propagation for the model:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED
Arguments:
X -- input dataset placeholder, of shape (input size, number of ex... | Z3 = [[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376 0.46852064]
[-0.17601591 -1.57972014 -1.4737016 -2.61672091 -1.00810647 0.5747785 ]]
| MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
**Expected Output**: Z3 = [[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376 0.46852064] [-0.17601591 -1.57972014 -1.4737016 -2.61672091 -1.00810647 0.5747785 ]] 1.3 - Compute costImplement the compute cost function below. You might find these two functions helpful: - **tf.nn.sof... | # GRADED FUNCTION: compute_cost
def compute_cost(Z3, Y):
"""
Computes the cost
Arguments:
Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)
Y -- "true" labels vector placeholder, same shape as Z3
Returns:
cost - Tensor of the c... | cost = 2.91034
| MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
**Expected Output**: cost = 2.91034 1.4 Model Finally you will merge the helper functions you implemented above to build a model. You will train it on the SIGNS dataset. You have implemented `random_mini_batches()` in the Optimization programming assignment of course 2. Remember that thi... | # GRADED FUNCTION: model
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.009,
num_epochs = 100, minibatch_size = 64, print_cost = True):
"""
Implements a three-layer ConvNet in Tensorflow:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED
A... | _____no_output_____ | MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
Run the following cell to train your model for 100 epochs. Check if your cost after epoch 0 and 5 matches our output. If not, stop the cell and go back to your code! | _, _, parameters = model(X_train, Y_train, X_test, Y_test)
| Cost after epoch 0: 1.918090
Cost after epoch 5: 1.545281
Cost after epoch 10: 1.005111
Cost after epoch 15: 0.828035
Cost after epoch 20: 0.684271
Cost after epoch 25: 0.648975
Cost after epoch 30: 0.574304
Cost after epoch 35: 0.557773
Cost after epoch 40: 0.502622
Cost after epoch 45: 0.511315
Cost after epoch 50: 0... | MIT | Convolution+model+-+Application+-+v1 (1).ipynb | suvam14das/Finger-Sign-detector-using-CNN |
Slow Stochastic | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
# yfinance is used to fetch data
import yfinance as yf
yf.pdr_override()
# input
symbol = 'AAPL'
start = '2018-08-01'
end = '2019-01-01'
# Read data
df = yf.download(symbol,start,end)
# View Co... | _____no_output_____ | MIT | Python_Stock/Technical_Indicators/Stochastic_Slow.ipynb | eu90h/Stock_Analysis_For_Quant |
Candlestick with Slow Stochastic | from matplotlib import dates as mdates
import datetime as dt
dfc = df.copy()
dfc['VolumePositive'] = dfc['Open'] < dfc['Adj Close']
#dfc = dfc.dropna()
dfc = dfc.reset_index()
dfc['Date'] = mdates.date2num(dfc['Date'].astype(dt.date))
dfc.head()
from mpl_finance import candlestick_ohlc
fig = plt.figure(figsize=(14,10... | _____no_output_____ | MIT | Python_Stock/Technical_Indicators/Stochastic_Slow.ipynb | eu90h/Stock_Analysis_For_Quant |
ロジスティック写像$$f(x, a) = a x (1 - x)$$ | import numpy as np
import pathfollowing as pf
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set('poster', 'whitegrid', 'dark', rc={"lines.linewidth": 2, 'grid.linestyle': '-'})
def func(x, a):
return np.array([a[0] * x[0] * (1.0 - x[0])])
def dfdx(x,a):
return np.array([[a[0]*(1.... | _____no_output_____ | BSD-3-Clause | notebooks/continuation/logistic.ipynb | tmiyaji/sgc164 |
不動点の追跡- $(x, a) = (2/3, 3)$で周期倍分岐が起こる | x=np.array([0.5])
a=np.array([2.0])
bd,bp,lp,pd=pf.pathfollow(x, a, func, dfdx, dfda,nmax=45, h=0.05, epsr=1.0e-10, epsb=1.0e-10, amin=0.0,amax=4.0,problem='map', quiet=True) | # parameter arrived at boundary
| BSD-3-Clause | notebooks/continuation/logistic.ipynb | tmiyaji/sgc164 |
周期倍分岐点 | bd[pd[0]] | _____no_output_____ | BSD-3-Clause | notebooks/continuation/logistic.ipynb | tmiyaji/sgc164 |
周期点の追跡 周期2の周期点の枝に切り替える | v2 = pf.calcSwitchingVectorPD(bd[pd[0]], func, dfdx, dfda, period=2)
x2=bd[pd[0]]['x']
a2=bd[pd[0]]['a']
bd2,bp2,lp2, pd2=pf.pathfollow(x2, a2, func, dfdx, dfda, w=v2, nmax=65, h=0.025, epsr=1.0e-10, epsb=1.0e-10, amin=0.0,amax=4.0,problem='map', quiet=True,period=2) | # parameter arrived at boundary
| BSD-3-Clause | notebooks/continuation/logistic.ipynb | tmiyaji/sgc164 |
周期点の周期倍分岐 | bd2[pd2[0]] | _____no_output_____ | BSD-3-Clause | notebooks/continuation/logistic.ipynb | tmiyaji/sgc164 |
周期4の周期点の枝に切り替える | v4 = pf.calcSwitchingVectorPD(bd2[pd2[0]], func, dfdx, dfda, period=4)
x4=bd2[pd2[0]]['x']
a4=bd2[pd2[0]]['a']
bd4,bp4,lp4, pd4=pf.pathfollow(x4, a4, func, dfdx, dfda, w=v4, nmax=65, h=0.0125, epsr=1.0e-10, amin=0.0,amax=4.0,epsb=1.0e-12, problem='map', quiet=True,period=4) | # parameter arrived at boundary
| BSD-3-Clause | notebooks/continuation/logistic.ipynb | tmiyaji/sgc164 |
周期8の周期点の枝に切り替える | v8 = pf.calcSwitchingVectorPD(bd4[pd4[0]], func, dfdx, dfda, period=8)
x8=bd4[pd4[0]]['x']
a8=bd4[pd4[0]]['a']
bd8,bp8,lp8, pd8=pf.pathfollow(x8, a8, func, dfdx, dfda, w=v8, nmax=130, h=0.00625, epsr=1.0e-10, amin=0.0,amax=4.0,epsb=1.0e-12, problem='map', quiet=True,period=8) | # parameter arrived at boundary
| BSD-3-Clause | notebooks/continuation/logistic.ipynb | tmiyaji/sgc164 |
これまでにもとめた周期倍分岐点のパラメータ値$a$ | print(bd[pd[0]]['a'], bd2[pd2[0]]['a'], bd4[pd4[0]]['a'], bd8[pd8[0]]['a'])
print(pd8)
bd_r = np.array([bd[m]['a'][0] for m in range(len(bd))])
bd_x = np.array([bd[m]['x'][0] for m in range(len(bd))])
bd_r2 = np.array([bd2[m]['a'][0] for m in range(len(bd2))])
bd_x2 = np.array([bd2[m]['x'][0] for m in range(len(bd2))])... | _____no_output_____ | BSD-3-Clause | notebooks/continuation/logistic.ipynb | tmiyaji/sgc164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.