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
データセットのダウンロードと検査 画像の取得訓練を始める前に、ネットワークに認識すべき新しいクラスを教えるために画像のセットが必要です。最初に使うためのクリエイティブ・コモンズでライセンスされた花の画像のアーカイブを作成してあります。
import pathlib data_root_orig = tf.keras.utils.get_file(origin='https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz', fname='flower_photos', untar=True) data_root = pathlib.Path(data_root_orig) print(data_root)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
218MB をダウンロードすると、花の画像のコピーが使えるようになっているはずです。
for item in data_root.iterdir(): print(item) import random all_image_paths = list(data_root.glob('*/*')) all_image_paths = [str(path) for path in all_image_paths] random.shuffle(all_image_paths) image_count = len(all_image_paths) image_count all_image_paths[:10]
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
画像の検査扱っている画像について知るために、画像のいくつかを見てみましょう。
import os attributions = (data_root/"LICENSE.txt").open(encoding='utf-8').readlines()[4:] attributions = [line.split(' CC-BY') for line in attributions] attributions = dict(attributions) import IPython.display as display def caption_image(image_path): image_rel = pathlib.Path(image_path).relative_to(data_root) ret...
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
各画像のラベルの決定 ラベルを一覧してみます。
label_names = sorted(item.name for item in data_root.glob('*/') if item.is_dir()) label_names
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
ラベルにインデックスを割り当てます。
label_to_index = dict((name, index) for index,name in enumerate(label_names)) label_to_index
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
ファイルとラベルのインデックスの一覧を作成します。
all_image_labels = [label_to_index[pathlib.Path(path).parent.name] for path in all_image_paths] print("First 10 labels indices: ", all_image_labels[:10])
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
画像の読み込みと整形 TensorFlow には画像を読み込んで処理するために必要なツールが備わっています。
img_path = all_image_paths[0] img_path
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
以下は生のデータです。
img_raw = tf.io.read_file(img_path) print(repr(img_raw)[:100]+"...")
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
画像のテンソルにデコードします。
img_tensor = tf.image.decode_image(img_raw) print(img_tensor.shape) print(img_tensor.dtype)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
モデルに合わせてリサイズします。
img_final = tf.image.resize(img_tensor, [192, 192]) img_final = img_final/255.0 print(img_final.shape) print(img_final.numpy().min()) print(img_final.numpy().max())
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
このあと使用するために、簡単な関数にまとめます。
def preprocess_image(image): image = tf.image.decode_jpeg(image, channels=3) image = tf.image.resize(image, [192, 192]) image /= 255.0 # normalize to [0,1] range return image def load_and_preprocess_image(path): image = tf.io.read_file(path) return preprocess_image(image) import matplotlib.pyplot as plt ...
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
`tf.data.Dataset`の構築 画像のデータセット `tf.data.Dataset` を構築するもっとも簡単な方法は、`from_tensor_slices` メソッドを使うことです。文字列の配列をスライスすると、文字列のデータセットが出来上がります。
path_ds = tf.data.Dataset.from_tensor_slices(all_image_paths)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
`shapes` と `types` は、データセット中のそれぞれのアイテムの内容を示しています。この場合には、バイナリ文字列のスカラーのセットです。
print(path_ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
`preprocess_image` をファイルパスのデータセットにマップすることで、画像を実行時にロードし整形する新しいデータセットを作成します。
image_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE) import matplotlib.pyplot as plt plt.figure(figsize=(8,8)) for n,image in enumerate(image_ds.take(4)): plt.subplot(2,2,n+1) plt.imshow(image) plt.grid(False) plt.xticks([]) plt.yticks([]) plt.xlabel(caption_image(all_image_paths[...
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
`(image, label)`のペアのデータセット おなじ `from_tensor_slices` メソッドを使ってラベルのデータセットを作ることができます。
label_ds = tf.data.Dataset.from_tensor_slices(tf.cast(all_image_labels, tf.int64)) for label in label_ds.take(10): print(label_names[label.numpy()])
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
これらのデータセットはおなじ順番なので、zip することで `(image, label)` というペアのデータセットができます。
image_label_ds = tf.data.Dataset.zip((image_ds, label_ds))
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
新しいデータセットの `shapes` と `types` は、それぞれのフィールドを示すシェイプと型のタプルです。
print(image_label_ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
注: `all_image_labels` や `all_image_paths` のような配列がある場合、 `tf.data.dataset.Dataset.zip` メソッドの代わりとなるのは、配列のペアをスライスすることです。
ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels)) # The tuples are unpacked into the positional arguments of the mapped function # タプルは展開され、マップ関数の位置引数に割り当てられます def load_and_preprocess_from_path_label(path, label): return load_and_preprocess_image(path), label image_label_ds = ds.map(load_...
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
基本的な訓練手法 このデータセットを使ってモデルの訓練を行うには、データが* よくシャッフルされ* バッチ化され* 限りなく繰り返され* バッチが出来るだけ早く利用できることが必要です。これらの特性は `tf.data` APIを使えば簡単に付け加えることができます。
BATCH_SIZE = 32 # シャッフルバッファのサイズをデータセットとおなじに設定することで、データが完全にシャッフルされる # ようにできます。 ds = image_label_ds.shuffle(buffer_size=image_count) ds = ds.repeat() ds = ds.batch(BATCH_SIZE) # `prefetch`を使うことで、モデルの訓練中にバックグラウンドでデータセットがバッチを取得できます。 ds = ds.prefetch(buffer_size=AUTOTUNE) ds
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
注意すべきことがいくつかあります。1. 順番が重要です。 * `.repeat` の前に `.shuffle` すると、エポックの境界を越えて要素がシャッフルされます。(ほかの要素がすべて出現する前に2回出現する要素があるかもしれません) * `.batch` の後に `.shuffle` すると、バッチの順番がシャッフルされますが、要素がバッチを越えてシャッフルされることはありません。1. 完全なシャッフルのため、 `buffer_size` をデータセットとおなじサイズに設定しています。データセットのサイズ未満の場合、値が大きいほど良くランダム化されますが、より多くのメモリーを使用します。1. シャッフルバッファがいっぱいに...
ds = image_label_ds.apply( tf.data.experimental.shuffle_and_repeat(buffer_size=image_count)) ds = ds.batch(BATCH_SIZE) ds = ds.prefetch(buffer_size=AUTOTUNE) ds
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
データセットをモデルにつなぐ`tf.keras.applications`からMobileNet v2のコピーを取得します。これを簡単な転移学習のサンプルに使用します。MobileNetの重みを訓練不可に設定します。
mobile_net = tf.keras.applications.MobileNetV2(input_shape=(192, 192, 3), include_top=False) mobile_net.trainable=False
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
このモデルは、入力が `[-1,1]` の範囲に正規化されていることを想定しています。```help(keras_applications.mobilenet_v2.preprocess_input)```...This function applies the "Inception" preprocessing which convertsthe RGB values from [0, 255] to [-1, 1] ... このため、データをMobileNetモデルに渡す前に、入力を`[0,1]`の範囲から`[-1,1]`の範囲に変換する必要があります。
def change_range(image,label): return 2*image-1, label keras_ds = ds.map(change_range)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
MobileNetは画像ごとに `6x6` の特徴量の空間を返します。バッチを1つ渡してみましょう。
# シャッフルバッファがいっぱいになるまで、データセットは何秒かかかります。 image_batch, label_batch = next(iter(keras_ds)) feature_map_batch = mobile_net(image_batch) print(feature_map_batch.shape)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
MobileNet をラップしたモデルを作り、出力層である `tf.keras.layers.Dense` の前に、`tf.keras.layers.GlobalAveragePooling2D` で空間の軸にそって平均値を求めます。
model = tf.keras.Sequential([ mobile_net, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(len(label_names))])
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
期待したとおりの形状の出力が得られます。
logit_batch = model(image_batch).numpy() print("min logit:", logit_batch.min()) print("max logit:", logit_batch.max()) print() print("Shape:", logit_batch.shape)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
訓練手法を記述するためにモデルをコンパイルします。
model.compile(optimizer=tf.keras.optimizers.Adam(), loss='sparse_categorical_crossentropy', metrics=["accuracy"])
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
訓練可能な変数は2つ、全結合層の `weights` と `bias` です。
len(model.trainable_variables) model.summary()
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
モデルを訓練します。普通は、エポックごとの本当のステップ数を指定しますが、ここではデモの目的なので3ステップだけとします。
steps_per_epoch=tf.math.ceil(len(all_image_paths)/BATCH_SIZE).numpy() steps_per_epoch model.fit(ds, epochs=1, steps_per_epoch=3)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
性能注:このセクションでは性能の向上に役立ちそうな簡単なトリックをいくつか紹介します。詳しくは、[Input Pipeline Performance](https://www.tensorflow.org/guide/performance/datasets) を参照してください。上記の単純なパイプラインは、エポックごとにそれぞれのファイルを一つずつ読み込みます。これは、CPU を使ったローカルでの訓練では問題になりませんが、GPU を使った訓練では十分ではなく、いかなる分散訓練でも使うべきではありません。 調査のため、まず、データセットの性能をチェックする簡単な関数を定義します。
import time default_timeit_steps = 2*steps_per_epoch+1 def timeit(ds, steps=default_timeit_steps): overall_start = time.time() # Fetch a single batch to prime the pipeline (fill the shuffle buffer), # before starting the timer it = iter(ds.take(steps+1)) next(it) start = time.time() for i,(images,labels...
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
現在のデータセットの性能は次のとおりです。
ds = image_label_ds.apply( tf.data.experimental.shuffle_and_repeat(buffer_size=image_count)) ds = ds.batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE) ds timeit(ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
キャッシュ `tf.data.Dataset.cache` を使うと、エポックを越えて計算結果を簡単にキャッシュできます。特に、データがメモリに収まるときには効果的です。ここでは、画像が前処理(デコードとリサイズ)された後でキャッシュされます。
ds = image_label_ds.cache() ds = ds.apply( tf.data.experimental.shuffle_and_repeat(buffer_size=image_count)) ds = ds.batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE) ds timeit(ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
メモリキャッシュを使う際の欠点のひとつは、実行の都度キャッシュを再構築しなければならないことです。このため、データセットがスタートするたびにおなじだけ起動のための遅延が発生します。
timeit(ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
データがメモリに収まらない場合には、キャッシュファイルを使用します。
ds = image_label_ds.cache(filename='./cache.tf-data') ds = ds.apply( tf.data.experimental.shuffle_and_repeat(buffer_size=image_count)) ds = ds.batch(BATCH_SIZE).prefetch(1) ds timeit(ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
キャッシュファイルには、キャッシュを再構築することなくデータセットを再起動できるという利点もあります。2回めがどれほど早いか見てみましょう。
timeit(ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
TFRecord ファイル 生の画像データTFRecord ファイルは、バイナリの大きなオブジェクトのシーケンスを保存するための単純なフォーマットです。複数のサンプルをおなじファイルに詰め込むことで、TensorFlow は複数のサンプルを一度に読み込むことができます。これは、特に GCS のようなリモートストレージサービスを使用する際の性能にとって重要です。最初に、生の画像データから TFRecord ファイルを構築します。
image_ds = tf.data.Dataset.from_tensor_slices(all_image_paths).map(tf.io.read_file) tfrec = tf.data.experimental.TFRecordWriter('images.tfrec') tfrec.write(image_ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
次に、TFRecord ファイルを読み込み、以前定義した `preprocess_image` 関数を使って画像のデコード/リフォーマットを行うデータセットを構築します。
image_ds = tf.data.TFRecordDataset('images.tfrec').map(preprocess_image)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
これを、前に定義済みのラベルデータセットと zip し、期待どおりの `(image,label)` のペアを得ます。
ds = tf.data.Dataset.zip((image_ds, label_ds)) ds = ds.apply( tf.data.experimental.shuffle_and_repeat(buffer_size=image_count)) ds=ds.batch(BATCH_SIZE).prefetch(AUTOTUNE) ds timeit(ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
これは、`cache` バージョンよりも低速です。前処理をキャッシュしていないからです。 シリアライズしたテンソル 前処理を TFRecord ファイルに保存するには、前やったように前処理した画像のデータセットを作ります。
paths_ds = tf.data.Dataset.from_tensor_slices(all_image_paths) image_ds = paths_ds.map(load_and_preprocess_image) image_ds
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
`.jpeg` 文字列のデータセットではなく、これはテンソルのデータセットです。これを TFRecord ファイルにシリアライズするには、まず、テンソルのデータセットを文字列のデータセットに変換します。
ds = image_ds.map(tf.io.serialize_tensor) ds tfrec = tf.data.experimental.TFRecordWriter('images.tfrec') tfrec.write(ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
前処理をキャッシュしたことにより、データは TFRecord ファイルから非常に効率的にロードできます。テンソルを使用する前にデシリアライズすることを忘れないでください。
ds = tf.data.TFRecordDataset('images.tfrec') def parse(x): result = tf.io.parse_tensor(x, out_type=tf.float32) result = tf.reshape(result, [192, 192, 3]) return result ds = ds.map(parse, num_parallel_calls=AUTOTUNE) ds
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
次にラベルを追加し、以前とおなじような標準的な処理を適用します。
ds = tf.data.Dataset.zip((ds, label_ds)) ds = ds.apply( tf.data.experimental.shuffle_and_repeat(buffer_size=image_count)) ds=ds.batch(BATCH_SIZE).prefetch(AUTOTUNE) ds timeit(ds)
_____no_output_____
Apache-2.0
site/ja/tutorials/load_data/images.ipynb
gabrielrufino/docs-l10n
Character level language model - Dinosaurus IslandWelcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special task. Leading biology researchers are creating new breeds of dinosaurs and bringing them to life on earth, and your job is to giv...
import numpy as np from utils import * import random import pprint
_____no_output_____
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
1 - Problem Statement 1.1 - Dataset and PreprocessingRun the following cell to read the dataset of dinosaur names, create a list of unique characters (such as a-z), and compute the dataset and vocabulary size.
data = open('dinos.txt', 'r').read() data= data.lower() chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print('There are %d total characters and %d unique characters in your data.' % (data_size, vocab_size))
There are 19909 total characters and 27 unique characters in your data.
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
* The characters are a-z (26 characters) plus the "\n" (or newline character).* In this assignment, the newline character "\n" plays a role similar to the `` (or "End of sentence") token we had discussed in lecture. - Here, "\n" indicates the end of the dinosaur name rather than the end of a sentence. * `char_to_i...
chars = sorted(chars) print(chars) char_to_ix = { ch:i for i,ch in enumerate(chars) } ix_to_char = { i:ch for i,ch in enumerate(chars) } pp = pprint.PrettyPrinter(indent=4) pp.pprint(ix_to_char)
{ 0: '\n', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', ...
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
1.2 - Overview of the modelYour model will have the following structure: - Initialize parameters - Run the optimization loop - Forward propagation to compute the loss function - Backward propagation to compute the gradients with respect to the loss function - Clip the gradients to avoid exploding gradients ...
### GRADED FUNCTION: clip def clip(gradients, maxValue): ''' Clips the gradients' values between minimum and maximum. Arguments: gradients -- a dictionary containing the gradients "dWaa", "dWax", "dWya", "db", "dby" maxValue -- everything above this number is set to this number, and everything...
gradients["dWaa"][1][2] = 10.0 gradients["dWax"][3][1] = -10.0 gradients["dWya"][1][2] = 0.29713815361 gradients["db"][4] = [ 10.] gradients["dby"][1] = [ 8.45833407]
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
** Expected output:**```Pythongradients["dWaa"][1][2] = 10.0gradients["dWax"][3][1] = -10.0gradients["dWya"][1][2] = 0.29713815361gradients["db"][4] = [ 10.]gradients["dby"][1] = [ 8.45833407]```
# Test with a maxValue of 5 maxValue = 5 np.random.seed(3) dWax = np.random.randn(5,3)*10 dWaa = np.random.randn(5,5)*10 dWya = np.random.randn(2,5)*10 db = np.random.randn(5,1)*10 dby = np.random.randn(2,1)*10 gradients = {"dWax": dWax, "dWaa": dWaa, "dWya": dWya, "db": db, "dby": dby} gradients = clip(gradients, maxV...
gradients["dWaa"][1][2] = 5.0 gradients["dWax"][3][1] = -5.0 gradients["dWya"][1][2] = 0.29713815361 gradients["db"][4] = [ 5.] gradients["dby"][1] = [ 5.]
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
** Expected Output: **```Pythongradients["dWaa"][1][2] = 5.0gradients["dWax"][3][1] = -5.0gradients["dWya"][1][2] = 0.29713815361gradients["db"][4] = [ 5.]gradients["dby"][1] = [ 5.]``` 2.2 - SamplingNow assume that your model is trained. You would like to generate new text (characters). The process of generation is e...
import numpy as np matrix1 = np.array([[1,1],[2,2],[3,3]]) # (3,2) matrix2 = np.array([[0],[0],[0]]) # (3,1) vector1D = np.array([1,1]) # (2,) vector2D = np.array([[1],[1]]) # (2,1) print("matrix1 \n", matrix1,"\n") print("matrix2 \n", matrix2,"\n") print("vector1D \n", vector1D,"\n") print("vector2D \n", vector2D) p...
Adding a (3,) vector to a (3 x 1) vector broadcasts the 1D array across the second dimension Not what we want here! [[2 4 6] [2 4 6] [2 4 6]]
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
- **Step 3**: Sampling: - Now that we have $y^{\langle t+1 \rangle}$, we want to select the next letter in the dinosaur name. If we select the most probable, the model will always generate the same result given a starting letter. - To make the results more interesting, we will use np.random.choice to select...
# GRADED FUNCTION: sample def sample(parameters, char_to_ix, seed): """ Sample a sequence of characters according to a sequence of probability distributions output of the RNN Arguments: parameters -- python dictionary containing the parameters Waa, Wax, Wya, by, and b. char_to_ix -- python dictio...
Sampling: list of sampled indices: [12, 17, 24, 14, 13, 9, 10, 22, 24, 6, 13, 11, 12, 6, 21, 15, 21, 14, 3, 2, 1, 21, 18, 24, 7, 25, 6, 25, 18, 10, 16, 2, 3, 8, 15, 12, 11, 7, 1, 12, 10, 2, 7, 7, 11, 17, 24, 12, 13, 24, 0] size indices: 51 list of sampled characters: ['l', 'q', 'x', 'n', 'm', 'i', 'j', 'v', 'x', 'f'...
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
** Expected output:**```PythonSampling:list of sampled indices: [12, 17, 24, 14, 13, 9, 10, 22, 24, 6, 13, 11, 12, 6, 21, 15, 21, 14, 3, 2, 1, 21, 18, 24, 7, 25, 6, 25, 18, 10, 16, 2, 3, 8, 15, 12, 11, 7, 1, 12, 10, 2, 7, 7, 11, 17, 24, 12, 13, 24, 0]list of sampled characters: ['l', 'q', 'x', 'n', 'm', 'i', 'j', 'v', ...
# GRADED FUNCTION: optimize def optimize(X, Y, a_prev, parameters, learning_rate = 0.01): """ Execute one step of the optimization to train the model. Arguments: X -- list of integers, where each integer is a number that maps to a character in the vocabulary. Y -- list of integers, exactly the...
Loss = 126.503975722 gradients["dWaa"][1][2] = 0.194709315347 np.argmax(gradients["dWax"]) = 93 gradients["dWya"][1][2] = -0.007773876032 gradients["db"][4] = [-0.06809825] gradients["dby"][1] = [ 0.01538192] a_last[4] = [-1.]
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
** Expected output:**```PythonLoss = 126.503975722gradients["dWaa"][1][2] = 0.194709315347np.argmax(gradients["dWax"]) = 93gradients["dWya"][1][2] = -0.007773876032gradients["db"][4] = [-0.06809825]gradients["dby"][1] = [ 0.01538192]a_last[4] = [-1.]``` 3.2 - Training the model * Given the dataset of dinosaur names, ...
# GRADED FUNCTION: model def model(data, ix_to_char, char_to_ix, num_iterations = 35000, n_a = 50, dino_names = 7, vocab_size = 27): """ Trains the model and generates dinosaur names. Arguments: data -- text corpus ix_to_char -- dictionary that maps the index to a character char_to_ix -- ...
_____no_output_____
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
Run the following cell, you should observe your model outputting random-looking characters at the first iteration. After a few thousand iterations, your model should learn to generate reasonable-looking names.
parameters = model(data, ix_to_char, char_to_ix)
Iteration: 0, Loss: 23.087336 Nkzxwtdmfqoeyhsqwasjkjvu Kneb Kzxwtdmfqoeyhsqwasjkjvu Neb Zxwtdmfqoeyhsqwasjkjvu Eb Xwtdmfqoeyhsqwasjkjvu Iteration: 2000, Loss: 27.884160 Liusskeomnolxeros Hmdaairus Hytroligoraurus Lecalosapaus Xusicikoraurus Abalpsamantisaurus Tpraneronxeros Iteration: 4000, Loss: 25.901815 Mivro...
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
** Expected Output**The output of your model may look different, but it will look something like this:```PythonIteration: 34000, Loss: 22.447230OnyxipaledisonsKiabaeropaLussiamangPacaeptabalsaurusXosalongEiacotegTroia``` ConclusionYou can see that your algorithm has started to generate plausible dinosaur names towards...
from __future__ import print_function from keras.callbacks import LambdaCallback from keras.models import Model, load_model, Sequential from keras.layers import Dense, Activation, Dropout, Input, Masking from keras.layers import LSTM from keras.utils.data_utils import get_file from keras.preprocessing.sequence import p...
Using TensorFlow backend.
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
To save you some time, we have already trained a model for ~1000 epochs on a collection of Shakespearian poems called [*"The Sonnets"*](shakespeare.txt). Let's train the model for one more epoch. When it finishes training for an epoch---this will also take a few minutes---you can run `generate_output`, which will prom...
print_callback = LambdaCallback(on_epoch_end=on_epoch_end) model.fit(x, y, batch_size=128, epochs=1, callbacks=[print_callback]) # Run this cell to try with different inputs without having to re-train the model generate_output()
Write the beginning of your poem, the Shakespeare machine will complete it. Your input is: Forsooth this maketh no sense Here is your poem: Forsooth this maketh no sense renping. but a did sind make hil ons dede is men, withou's inus will o decanot, lek o whle thou debert should every forted, whice muse whe bow wa...
MIT
Sequence Models/week1/Dinosaurus_Island_Character_level_language_model_final_v3a.ipynb
lankuohsing/Coursera-Deep-Learning-Specialization
Moodle Database: Educational Data Log Analysis The Moodle LMS is a free and open-source learning management system written in PHP and distributed under the GNU General Public License. It is used for blended learning, distance education, flipped classroom and other e-learning projects in schools, universities, workpla...
#!pip install ipython-sql #!pip install sqlalchemy #!pip install psycopg2
_____no_output_____
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Importing necessary libraries
import pandas as pd import numpy as np from sqlalchemy import create_engine import psycopg2 import logging from IPython.display import display #allowing connection to the database %load_ext sql #ipython-sql %sql postgresql://bessy:Streetdance53@localhost/moodle #sqlalchemy engine = create_engine('postgresql://bessy:Str...
_____no_output_____
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Moodle database Understanding.Now, let's have a glance of how some of the tables look like.We will consider the following tables;`mdl_logstore_standard_log`,`mdl_context`,`mdl_user`,`mdl_course`,`mdl_modules `,`mdl_course_modules`,`mdl_course_modules_completion`, `mdl_grade_items`,`mdl_grade_grades`,`mdl_grade_categor...
%%sql SELECT *FROM mdl_logstore_standard_log LIMIT 3;
* postgresql://bessy:***@localhost/moodle 3 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
`Table: mdl_context`
%%sql SELECT * FROM mdl_context LIMIT 3;
* postgresql://bessy:***@localhost/moodle 3 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
`mdl_course`
%%sql SELECT * FROM mdl_course LIMIT 3;
* postgresql://bessy:***@localhost/moodle 3 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
`mdl_user`
%%sql SELECT * FROM mdl_user LIMIT 3;
* postgresql://bessy:***@localhost/moodle 3 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
`mdl_modules`
%%sql SELECT * FROM mdl_modules LIMIT 3;
* postgresql://bessy:***@localhost/moodle 3 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
`mdl_course_modules`
%%sql SELECT * FROM mdl_course_modules LIMIT 3;
* postgresql://bessy:***@localhost/moodle 3 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
`mdl_course_modules_completion`
%%sql SELECT * FROM mdl_course_modules_completion LIMIT 3
* postgresql://bessy:***@localhost/moodle 3 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
`mdl_grade_grades`
%%sql SELECT * FROM mdl_grade_grades LIMIT 3
* postgresql://bessy:***@localhost/moodle 3 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Number of tables in the database;
%%sql SELECT COUNT(*) FROM information_schema.tables
* postgresql://bessy:***@localhost/moodle 1 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Number of records in the following tables;
mit = ['mdl_logstore_standard_log', 'mdl_context', 'mdl_user', 'mdl_course', 'mdl_modules' , 'mdl_course_modules', 'mdl_course_modules_completion', 'mdl_grade_items', 'mdl_grade_grades', 'mdl_grade_categories', 'mdl_grade_items_history', 'mdl_grade_grades_history', 'mdl_grade_categories_history', 'mdl_fo...
* postgresql://bessy:***@localhost/moodle 1 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Number of quiz submission by time
%%sql select date_part('hour', timestamp with time zone 'epoch' + timefinish * interval '1 second') as hour, count(1) from mdl_quiz_attempts qa where qa.preview = 0 and qa.timefinish <> 0 group by date_part('hour', timestamp with time zone 'epoch' + timefinish * interval '1 second') order by hour %%sql SELECT COUNT(id...
* postgresql://bessy:***@localhost/moodle 24 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Monthly usage time of learners who have confirmed and are not deleted
%%sql select extract(month from to_timestamp(mdl_stats_user_monthly.timeend)) as calendar_month, count(distinct mdl_stats_user_monthly.userid) as total_users from mdl_stats_user_monthly inner join mdl_role_assignments on mdl_stats_user_monthly.userid = mdl_role_assignments.userid inner join mdl_context on m...
* postgresql://bessy:***@localhost/moodle 7 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Count of log events per user
actions = ['loggedin', 'viewed', 'started', 'submitted', 'uploaded', 'updated', 'searched', 'answered', 'attempted', 'abandoned'] # fetch and return count of log events of an action per user def event_count(action): count = %sql SELECT userid, COUNT(action) AS {action}_count FROM mdl_logstore_standar...
* postgresql://bessy:***@localhost/moodle 5 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
python class to pull * Overall grade of learners * Number of forum posts
class PullGrade(): def __init__(self): pass def open_db(self, **kwargs): # extract args, if they are not provided assign a default value user = kwargs.get('user', 'briodev') password = kwargs.get('password', '14ConnectPsq') db = kwargs.get('db', 'moodle') ...
* postgresql://bessy:***@localhost/moodle 10 rows affected.
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Data Extraction Transformation and Loading (ETL)
#reading the mdl_logstore_standard_log log_df = pd.read_sql("select * from mdl_logstore_standard_log", engine) def top_x(df, percent): total_len = df.shape[0] top = int((total_len * percent)/100) return df.iloc[:top,]
_____no_output_____
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Login count
log_df_logged_in = log_df[log_df.action == 'loggedin'][['userid', 'action']] login_by_user = log_df_logged_in.groupby('userid').count().sort_values('action', ascending=False) login_by_user.columns = ["login_count"] top_x(login_by_user, 1)
_____no_output_____
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Activity count
activity_log = log_df[['userid', 'action']] activity_log_by_user = activity_log.groupby('userid').count().sort_values('action', ascending=False) activity_log_by_user.columns = ['activity_count'] top_x(activity_log_by_user, 1) log_in_out = log_df[(log_df.action == "loggedin") | (log_df.action == "loggedout")] user_id = ...
_____no_output_____
MIT
notebooks/Educational-Data-Log-Analysis.ipynb
Bessy-Mukaria/Educational-Data-Log-Analysis
Format DataFrame
import pandas as pd from sklearn.datasets import make_regression data = make_regression(n_samples=600, n_features=50, noise=0.1, random_state=42) train_df = pd.DataFrame(data[0], columns=["x_{}".format(_) for _ in range(data[0].shape[1])]) train_df["target"] = data[1] print(train_df.shape) train_df.head()
(600, 51)
MIT
examples/catboost_examples/regression.ipynb
beyondacm/hyperparameter_hunter
Set Up Environment
from hyperparameter_hunter import Environment, CVExperiment from sklearn.metrics import explained_variance_score env = Environment( train_dataset=train_df, results_path="HyperparameterHunterAssets", metrics=dict(evs=explained_variance_score), cv_type="KFold", cv_params=dict(n_splits=3, shuffle=True...
Cross-Experiment Key: 'Sxkz36nLbTyi4QJM7w6wCWkbIucXm0RbzMsirLPuYmw='
MIT
examples/catboost_examples/regression.ipynb
beyondacm/hyperparameter_hunter
Now that HyperparameterHunter has an active `Environment`, we can do two things: 1. Perform Experiments*Note: If this is your first HyperparameterHunter example, the CatBoost classification example may be a better starting point.*In this Experiment, we're also going to use `model_extra_params` to provide arguments to `...
from catboost import CatBoostRegressor experiment = CVExperiment( model_initializer=CatBoostRegressor, model_init_params=dict( iterations=100, learning_rate=0.05, depth=5, bootstrap_type="Bayesian", save_snapshot=False, allow_writing_files=False, ), model...
<22:13:22> Validated Environment: 'Sxkz36nLbTyi4QJM7w6wCWkbIucXm0RbzMsirLPuYmw=' <22:13:22> Initialized Experiment: 'df2982f6-ab54-4c74-80b6-ad1c1e49fe45' <22:13:22> Hyperparameter Key: '913_iDDPY_PMp5ulOyK251mgLCZ2qau7kjOvDdy1rz8=' <22:13:22> 0: learn: 181.0383680 test: 179.9132919 best: 179.9132919 (0) total: 6...
MIT
examples/catboost_examples/regression.ipynb
beyondacm/hyperparameter_hunter
Notice above that CatBoost printed scores for our `eval_set` every 50 iterations just like we said in `model_extra_params["fit"]`; although, it made our results rather difficult to read, so we'll switch back to `verbose=False` during optimization. 2. Hyperparameter OptimizationNotice below that `optimizer` still recogn...
from hyperparameter_hunter import DummyOptPro, Real, Integer, Categorical optimizer = DummyOptPro(iterations=10, random_state=777) optimizer.forge_experiment( model_initializer=CatBoostRegressor, model_init_params=dict( iterations=100, learning_rate=Real(0.001, 0.2), depth=Integer(3, 7...
Validated Environment with key: "Sxkz36nLbTyi4QJM7w6wCWkbIucXm0RbzMsirLPuYmw=" Saved Result Files _________________________________________________________________________________________ Step | ID | Time | Value | bootstrap_type | depth | learning_rate | Experiments matching cr...
MIT
examples/catboost_examples/regression.ipynb
beyondacm/hyperparameter_hunter
Durables vs Non Durables At Low And High Frequencies
!pip install numpy !pip install matplotlib !pip install pandas !pip install pandas_datareader !pip install datetime !pip install seaborn # Some initial setup from matplotlib import pyplot as plt import numpy as np plt.style.use('seaborn-darkgrid') import pandas as pd import pandas_datareader.data as web import dateti...
_____no_output_____
Apache-2.0
notebooks/Durables-vs-Nondurables-At-Low-And-High-Frequencies.ipynb
llorracc/Jupyter
Self-Driving Car Engineer Nanodegree Project: **Finding Lane Lines on the Road** ***In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a se...
#importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline
_____no_output_____
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Read in an Image
#reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image), 'with dimensions:', image.shape) plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gra...
This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Ideas for Lane Detection Pipeline **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**`cv2.inRange()` for color selection `cv2.fillPoly()` for regions selection `cv2.line()` to draw lines on an image given endpoints `cv2.addWeighted()` to coadd / overlay two i...
import math def grayscale(img): """Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray')""" return cv2.cvtColor(img, c...
_____no_output_____
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
New draw_lines function to extrapolate the lineHere fraction of shape of image i.e **fraction*img.shape[0]** is taken to make it work with optoional problem as its image has different dimensions.
def draw_lines(img, lines, color=[255, 0, 0], thickness=10): left_slope = 0 right_slope = 0 x_left = 0 y_left = 0 x_right = 0 y_right = 0 count_left = 0 # count of left linesegments for average calculation count_right = 0 # count of right linesegments for average calculation ...
_____no_output_____
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Test ImagesBuild your pipeline to work on the images in the directory "test_images" **You should make sure your pipeline works well on these images before you try the videos.**
import os os.listdir("test_images/") image_file = ['test_images/whiteCarLaneSwitch.jpg','test_images/solidWhiteCurve.jpg', 'test_images/solidWhiteRight.jpg', 'test_images/solidYellowCurve.jpg', 'test_images/solidYellowCurve2.jpg', 'test_images/solidYellowLeft.jpg']
_____no_output_____
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Build a Lane Finding Pipeline Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.
# TODO: Build your pipeline that will draw lane lines on the test_images # then save them to the test_images_output directory. def lane_finding_pipeline(img, vertices): # image = mpimg.imread(img) gray = grayscale(img) kernel_size = 5 blur_gray = gaussian_blur(gray, kernel_size) low_threshold = 50 ...
_____no_output_____
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Test on VideosYou know what's cooler than drawing lanes over images? Drawing lanes over video!We can test our solution on two provided videos:`solidWhiteRight.mp4``solidYellowLeft.mp4`**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel...
# Import everything needed to edit/save/watch video clips from moviepy.editor import VideoFileClip from IPython.display import HTML def process_image(image): # NOTE: The output you return should be a color image (3 channel) for processing video below # TODO: put your pipeline here, # you should return the f...
_____no_output_____
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Let's try the one with the solid white lane on the right first ...
white_output = 'test_videos_output/solidWhiteRight.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and...
[MoviePy] >>>> Building video test_videos_output/solidWhiteRight.mp4 [MoviePy] Writing video test_videos_output/solidWhiteRight.mp4
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.
HTML(""" <video width="960" height="540" controls> <source src="{0}"> </video> """.format(white_output))
_____no_output_____
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Improve the draw_lines() function**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about de...
yellow_output = 'test_videos_output/solidYellowLeft.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start an...
_____no_output_____
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Writeup and SubmissionIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_templat...
def process_image_1(image): # NOTE: The output you return should be a color image (3 channel) for processing video below # TODO: put your pipeline here, # you should return the final output (image where lines are drawn on lanes) gray = grayscale(image) kernel_size = 5 blur_gray = gaussian_blur(g...
_____no_output_____
MIT
P1.ipynb
kpilkk/CarND-LaneLines-P1
Classification models using python and scikit-learnThere are many users of online trading platforms and these companies would like to run analytics on and predict churn based on user activity on the platform. Keeping customers happy so they do not move their investments elsewhere is key to maintaining profitability.In...
!pip install pandas==0.24.2 !pip install --user pandas_ml==0.6.1 #downgrade matplotlib to bypass issue with confusion matrix being chopped out !pip install matplotlib==3.1.0 !pip install --user scikit-learn==0.21.3 !pip install -q scikit-plot from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.im...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
2. Data exploration[Top](top)In this tutorial, we use a data set that contains information about customers of an online trading platform to classify whether a given customer’s probability of churn will be high, medium, or low. This provides a good example to learn how a classification model is built from start to end.
df_churn_pd = pd.read_csv("https://raw.githubusercontent.com/IBM/ml-learning-path-assets/master/data/mergedcustomers_missing_values_GENDER.csv") df_churn_pd.head()
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
We use numpy and matplotlib to get some statistics and visualize data. print("The dataset contains columns of the following data types : \n" +str(df_churn_pd.dtypes)) Notice below that Gender has three missing values. This will be handled in one of the preprocessing steps that is to follow.
print("The dataset contains following number of records for each of the columns : \n" +str(df_churn_pd.count()))
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
If we are not satisfied with the representational data, now is the time to get more data to be used for training and testing.
print( "Each category within the churnrisk column has the following count : ") print(df_churn_pd.groupby(['CHURNRISK']).size()) #bar chart to show split of data index = ['High','Medium','Low'] churn_plot = df_churn_pd['CHURNRISK'].value_counts(sort=True, ascending=False).plot(kind='bar', figsize=(4,4),title...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
3. Data preparation[Top](top)Data preparation is a very important step in machine learning model building. This is because the model can perform well only when the data it is trained on is good and well prepared. Hence, this step consumes the bulk of a data scientist's time spent building models.During this process, w...
#remove columns that are not required df_churn_pd = df_churn_pd.drop(['ID'], axis=1) df_churn_pd.head()
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
[Preprocessing Data](https://scikit-learn.org/stable/modules/preprocessing.html) Scikit-learn provides a method to fill empty values with something that would be applicable in its context. We used the SimpleImputer class that is provided by Sklearn and filled the missing values with the most frequent value in the co...
# Defining the categorical columns categoricalColumns = ['GENDER', 'STATUS', 'HOMEOWNER'] print("Categorical columns : " ) print(categoricalColumns) impute_categorical = SimpleImputer(strategy="most_frequent") onehot_categorical = OneHotEncoder(handle_unknown='ignore') categorical_transformer = Pipeline(steps=[('...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
The numerical columns from the data set are identified, and StandardScaler is applied to each of the columns. This way, each value is subtracted with the mean of its column and divided by its standard deviation. [Standard Scaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.htm...
# Defining the numerical columns numericalColumns = df_churn_pd.select_dtypes(include=[np.float,np.int]).columns print("Numerical columns : " ) print(numericalColumns) scaler_numerical = StandardScaler() numerical_transformer = Pipeline(steps=[('scale',scaler_numerical)])
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
The preprocessing techniques that are applied must be customized for each of the columns. Sklearn provides a library called the [ColumnTransformer](https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer.html?highlight=columntransformersklearn.compose.ColumnTransformer), which allows a seque...
preprocessorForCategoricalColumns = ColumnTransformer(transformers=[('cat', categorical_transformer, categoricalColumns)], remainder="passthrough") preprocessorForAllColumns = ColumnTransformer(transformers...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
Machine learning algorithms cannot use simple text. We must convert the data from text to a number. Therefore, for each string that is a class we assign a label that is a number. For example, in the customer churn data set, the CHURNRISK output label is classified as high, medium, or low and is assigned labels 0, 1, or...
# prepare data frame for splitting data into train and test datasets features = [] features = df_churn_pd.drop(['CHURNRISK'], axis=1) label_churn = pd.DataFrame(df_churn_pd, columns = ['CHURNRISK']) label_encoder = LabelEncoder() label = df_churn_pd['CHURNRISK'] label = label_encoder.fit_transform(label) print("Enc...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
These are some of the popular preprocessing steps that are applied on the data sets. Look at [Data Processing in detail](https://developer.ibm.com/articles/data-preprocessing-in-detail/) for more information
area = 75 x = df_churn_pd['ESTINCOME'] y = df_churn_pd['DAYSSINCELASTTRADE'] z = df_churn_pd['TOTALDOLLARVALUETRADED'] pop_a = mpatches.Patch(color='#BB6B5A', label='High') pop_b = mpatches.Patch(color='#E5E88B', label='Medium') pop_c = mpatches.Patch(color='#8CCB9B', label='Low') def colormap(risk_list): cols=[] ...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
4. Split data into test and train[Top](top)Scikit-learn provides in built API to split the original dataset into train and test datasets. random_state is set to a number to be able to reproduce the same data split combination through multiple runs. [Split arrays or matrices into random train and test subsets](https://...
X_train, X_test, y_train, y_test = train_test_split(features,label , random_state=0) print("Dimensions of datasets that will be used for training : Input features"+str(X_train.shape)+ " Output label" + str(y_train.shape)) print("Dimensions of datasets that will be used for testing : Input features"+str(X_test.s...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn
5. Helper methods for graph generation[Top](top)
def colormap(risk_list): cols=[] for l in risk_list: if l==0: cols.append('#BB6B5A') elif l==2: cols.append('#E5E88B') elif l==1: cols.append('#8CCB9B') return cols def two_d_compare(y_test,y_pred,model_name): #y_pred = label_encoder.fit_trans...
_____no_output_____
Apache-2.0
Notebook/Classification_models.ipynb
IBMDeveloperUK/Classification-Models-using-Python-and-Scikit-Learn