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 |
|---|---|---|---|---|---|
For example, suppose you have a single observation from the dataset, `[False, 4, bytes('goat'), 0.9876]`. You can create and print the `tf.Example` message for this observation using `create_message()`. Each single observation will be written as a `Features` message as per the above. Note that the `tf.Example` [message... | # This is an example observation from the dataset.
example_observation = []
serialized_example = serialize_example(False, 4, b'goat', 0.9876)
serialized_example | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
To decode the message use the `tf.train.Example.FromString` method. | example_proto = tf.train.Example.FromString(serialized_example)
example_proto | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
TFRecords format detailsA TFRecord file contains a sequence of records. The file can only be read sequentially.Each record contains a byte-string, for the data-payload, plus the data-length, and CRC32C (32-bit CRC using the Castagnoli polynomial) hashes for integrity checking.Each record is stored in the following fo... | tf.data.Dataset.from_tensor_slices(feature1) | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Applied to a tuple of arrays, it returns a dataset of tuples: | features_dataset = tf.data.Dataset.from_tensor_slices((feature0, feature1, feature2, feature3))
features_dataset
# Use `take(1)` to only pull one example from the dataset.
for f0,f1,f2,f3 in features_dataset.take(1):
print(f0)
print(f1)
print(f2)
print(f3) | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Use the `tf.data.Dataset.map` method to apply a function to each element of a `Dataset`.The mapped function must operate in TensorFlow graph mode—it must operate on and return `tf.Tensors`. A non-tensor function, like `serialize_example`, can be wrapped with `tf.py_function` to make it compatible.Using `tf.py_function`... | def tf_serialize_example(f0,f1,f2,f3):
tf_string = tf.py_function(
serialize_example,
(f0,f1,f2,f3), # pass these args to the above function.
tf.string) # the return type is `tf.string`.
return tf.reshape(tf_string, ()) # The result is a scalar
tf_serialize_example(f0,f1,f2,f3) | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Apply this function to each element in the dataset: | serialized_features_dataset = features_dataset.map(tf_serialize_example)
serialized_features_dataset
def generator():
for features in features_dataset:
yield serialize_example(*features)
serialized_features_dataset = tf.data.Dataset.from_generator(
generator, output_types=tf.string, output_shapes=())
serializ... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
And write them to a TFRecord file: | filename = 'test.tfrecord'
writer = tf.data.experimental.TFRecordWriter(filename)
writer.write(serialized_features_dataset) | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Reading a TFRecord file You can also read the TFRecord file using the `tf.data.TFRecordDataset` class.More information on consuming TFRecord files using `tf.data` can be found [here](https://www.tensorflow.org/guide/datasetsconsuming_tfrecord_data).Using `TFRecordDataset`s can be useful for standardizing input data an... | filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
raw_dataset | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
At this point the dataset contains serialized `tf.train.Example` messages. When iterated over it returns these as scalar string tensors.Use the `.take` method to only show the first 10 records.Note: iterating over a `tf.data.Dataset` only works with eager execution enabled. | for raw_record in raw_dataset.take(10):
print(repr(raw_record)) | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
These tensors can be parsed using the function below. Note that the `feature_description` is necessary here because datasets use graph-execution, and need this description to build their shape and type signature: | # Create a description of the features.
feature_description = {
'feature0': tf.io.FixedLenFeature([], tf.int64, default_value=0),
'feature1': tf.io.FixedLenFeature([], tf.int64, default_value=0),
'feature2': tf.io.FixedLenFeature([], tf.string, default_value=''),
'feature3': tf.io.FixedLenFeature([], tf... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Alternatively, use `tf.parse example` to parse the whole batch at once. Apply this function to each item in the dataset using the `tf.data.Dataset.map` method: | parsed_dataset = raw_dataset.map(_parse_function)
parsed_dataset | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Use eager execution to display the observations in the dataset. There are 10,000 observations in this dataset, but you will only display the first 10. The data is displayed as a dictionary of features. Each item is a `tf.Tensor`, and the `numpy` element of this tensor displays the value of the feature: | for parsed_record in parsed_dataset.take(10):
print(repr(parsed_record)) | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Here, the `tf.parse_example` function unpacks the `tf.Example` fields into standard tensors. TFRecord files in Python The `tf.io` module also contains pure-Python functions for reading and writing TFRecord files. Writing a TFRecord file Next, write the 10,000 observations to the file `test.tfrecord`. Each observation... | # Write the `tf.Example` observations to the file.
with tf.io.TFRecordWriter(filename) as writer:
for i in range(n_observations):
example = serialize_example(feature0[i], feature1[i], feature2[i], feature3[i])
writer.write(example)
!du -sh {filename} | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Reading a TFRecord fileThese serialized tensors can be easily parsed using `tf.train.Example.ParseFromString`: | filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
raw_dataset
for raw_record in raw_dataset.take(1):
example = tf.train.Example()
example.ParseFromString(raw_record.numpy())
print(example) | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Walkthrough: Reading and writing image data This is an end-to-end example of how to read and write image data using TFRecords. Using an image as input data, you will write the data as a TFRecord file, then read the file back and display the image.This can be useful if, for example, you want to use several models on th... | cat_in_snow = tf.keras.utils.get_file('320px-Felis_catus-cat_on_snow.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/320px-Felis_catus-cat_on_snow.jpg')
williamsburg_bridge = tf.keras.utils.get_file('194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg','https://storage.googleapis.co... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Write the TFRecord file As before, encode the features as types compatible with `tf.Example`. This stores the raw image string feature, as well as the height, width, depth, and arbitrary `label` feature. The latter is used when you write the file to distinguish between the cat image and the bridge image. Use `0` for t... | image_labels = {
cat_in_snow : 0,
williamsburg_bridge : 1,
}
# This is an example, just using the cat image.
image_string = open(cat_in_snow, 'rb').read()
label = image_labels[cat_in_snow]
# Create a dictionary with features that may be relevant.
def image_example(image_string, label):
image_shape = tf.imag... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Notice that all of the features are now stored in the `tf.Example` message. Next, functionalize the code above and write the example messages to a file named `images.tfrecords`: | # Write the raw image files to `images.tfrecords`.
# First, process the two images into `tf.Example` messages.
# Then, write to a `.tfrecords` file.
record_file = 'images.tfrecords'
with tf.io.TFRecordWriter(record_file) as writer:
for filename, label in image_labels.items():
image_string = open(filename, 'rb').r... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Read the TFRecord fileYou now have the file—`images.tfrecords`—and can now iterate over the records in it to read back what you wrote. Given that in this example you will only reproduce the image, the only feature you will need is the raw image string. Extract it using the getters described above, namely `example.feat... | raw_image_dataset = tf.data.TFRecordDataset('images.tfrecords')
# Create a dictionary describing the features.
image_feature_description = {
'height': tf.io.FixedLenFeature([], tf.int64),
'width': tf.io.FixedLenFeature([], tf.int64),
'depth': tf.io.FixedLenFeature([], tf.int64),
'label': tf.io.FixedLen... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Recover the images from the TFRecord file: | for image_features in parsed_image_dataset:
image_raw = image_features['image_raw'].numpy()
display.display(display.Image(data=image_raw)) | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
YAHOO電影爬蟲練習 練習爬取電影放映資訊。必須逐步獲取電影的代號、放映地區、放映日期後,再送出查詢給伺服器。 | import requests
import re
from bs4 import BeautifulSoup | _____no_output_____ | MIT | .ipynb_checkpoints/Day_014_Yahoo_Movie_HW-checkpoint.ipynb | Ruila/PythonCrwalerMarathon_Day14 |
先搜尋全部的電影代號(ID)資訊 | # 查看目前上映那些電影,並擷取出其ID資訊
url = 'https://movies.yahoo.com.tw/'
resp = requests.get(url)
resp.encoding = 'utf-8'
# gggggg
soup = BeautifulSoup(resp.text, 'lxml')
html = soup.find("select", attrs={'name':'movie_id'})
movie_item = html.find_all("option", attrs={'data-name':re.compile('.*')})
for p in movie_item:
print("... | Movie: 空中謎航, ID: 11152
Movie: 致命天際線, ID: 11147
Movie: 廢青四重奏, ID: 11130
Movie: 妄想代理人:前篇, ID: 11102
Movie: 水漾的女人, ID: 11065
Movie: 午夜天鵝, ID: 11045
Movie: 拆彈專家2, ID: 10986
Movie: 杏林醫院, ID: 10781
Movie: 靈魂急轉彎, ID: 11089
Movie: 瑰麗卡萊爾:浮華紐約, ID: 11129
Movie: 愛是您・愛是我, ID: 11123
Movie: 來者弒客, ID: 11107
Movie: 真愛鄰距離, ID: 11101
Mo... | MIT | .ipynb_checkpoints/Day_014_Yahoo_Movie_HW-checkpoint.ipynb | Ruila/PythonCrwalerMarathon_Day14 |
指定你有興趣的電影其ID,然後查詢其放映地區資訊。 | # 參考前一個步驟中擷取到的ID資訊,並指定ID
movie_id = 10477
url = 'https://movies.yahoo.com.tw/api/v1/areas_by_movie_theater'
payload = {'movie_id':str(movie_id)}
# 模擬一個header
headers = {
'authority': 'movies.yahoo.com.tw',
'method': 'GET',
'path': '/api/v1/areas_by_movie_theater?movie_id=' + str(movie_id),
'scheme': 'h... | 放映地區: 台北市, 代號(area_id): 28
放映地區: 新北市, 代號(area_id): 8
放映地區: 桃園, 代號(area_id): 16
放映地區: 新竹, 代號(area_id): 20
放映地區: 苗栗, 代號(area_id): 15
放映地區: 台中, 代號(area_id): 2
放映地區: 南投, 代號(area_id): 13
放映地區: 嘉義, 代號(area_id): 21
放映地區: 台南, 代號(area_id): 10
放映地區: 高雄, 代號(area_id): 17
放映地區: 宜蘭, 代號(area_id): 11
放映地區: 花蓮, 代號(area_id): 12
放映地區: 澎湖... | MIT | .ipynb_checkpoints/Day_014_Yahoo_Movie_HW-checkpoint.ipynb | Ruila/PythonCrwalerMarathon_Day14 |
指定你想要觀看的放映地區,查詢有上映電影的場次日期 | # 指定放映地區
area_id = 28
# 向網站發送請求
url = 'https://movies.yahoo.com.tw/movietime_result.html'
payload = {'movie_id':str(movie_id), 'area_id':str(area_id)}
resp = requests.get(url, params=payload)
resp.encoding = 'utf-8'
soup = BeautifulSoup(resp.text, 'lxml')
movie_date = soup.find_all("label", attrs={'for':re.compile("da... | 一月 1
一月 2
一月 3
一月 4
一月 5
| MIT | .ipynb_checkpoints/Day_014_Yahoo_Movie_HW-checkpoint.ipynb | Ruila/PythonCrwalerMarathon_Day14 |
最後指定觀看的日期,查詢並列印出放映的電影院、放映類型(數位、3D、IMAX 3D...)、放映時間等資訊。 | # 選定要觀看的日期
date = "2019-08-21"
# 向網站發送請求,獲取上映的電影院及時間資訊
url = "https://movies.yahoo.com.tw/ajax/pc/get_schedule_by_movie"
payload = {'movie_id':str(movie_id),
'date':date,
'area_id':str(area_id),
'theater_id':'',
'datetime':'',
'movie_type_id':''}
resp = requests.g... | ----------------------------------------------------------------------
電影院: 台北美麗華大直影城
放映類型: 數位
2019-08-21 09:00:00
2019-08-21 11:10:00
2019-08-21 13:15:00
2019-08-21 15:20:00
2019-08-21 19:30:00
2019-08-21 21:40:00
2019-08-21 22:30:00
----------------------------------------------------------------------
電影院: 台北新光影城... | MIT | .ipynb_checkpoints/Day_014_Yahoo_Movie_HW-checkpoint.ipynb | Ruila/PythonCrwalerMarathon_Day14 |
Flopy MODFLOW 6 (MF6) Support The Flopy library contains classes for creating, saving, running, loading, and modifying MF6 simulations. The MF6 portion of the flopy library is located in:*flopy.mf6*While there are a number of classes in flopy.mf6, to get started you only need to use the main classes summarized below:... | import os
import sys
from shutil import copyfile
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
try:
import flopy
except:
fpth = os.path.abspath(os.path.join('..', '..'))
sys.path.append(fpth)
import flopy
print(sys.version)
print('numpy version: {}'.format(np.__versi... | 3.8.10 (default, May 19 2021, 11:01:55)
[Clang 10.0.0 ]
numpy version: 1.19.2
matplotlib version: 3.4.2
flopy version: 3.3.4
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Creating a MF6 Simulation A MF6 simulation is created by first creating a simulation object "MFSimulation". When you create the simulation object you can define the simulation's name, version, executable name, workspace path, and the name of the tdis file. All of these are optional parameters, and if not defined eac... | import os
import sys
from shutil import copyfile
try:
import flopy
except:
fpth = os.path.abspath(os.path.join('..', '..'))
sys.path.append(fpth)
import flopy
sim_name = 'example_sim'
sim_path = os.path.join('data', 'example_project')
sim = flopy.mf6.MFSimulation(sim_name=sim_name, version='mf6', exe_n... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
The next step is to create a tdis package object "ModflowTdis". The first parameter of the ModflowTdis class is a simulation object, which ties a ModflowTdis object to a specific simulation. The other parameters and their definitions can be found in the docstrings. | tdis = flopy.mf6.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=2,
perioddata=[(1.0, 1, 1.0), (10.0, 5, 1.0)]) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Next one or more models are created using the ModflowGwf class. The first parameter of the ModflowGwf class is the simulation object that the model will be a part of. | model_name = 'example_model'
model = flopy.mf6.ModflowGwf(sim, modelname=model_name,
model_nam_file='{}.nam'.format(model_name)) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Next create one or more Iterative Model Solution (IMS) files. | ims_package = flopy.mf6.ModflowIms(sim, pname='ims', print_option='ALL',
complexity='SIMPLE', outer_hclose=0.00001,
outer_maximum=50, under_relaxation='NONE',
inner_maximum=30, inner_hclose=0.00001,
... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Each ModflowGwf object needs to be associated with an ModflowIms object. This is done by calling the MFSimulation object's "register_ims_package" method. The first parameter in this method is the ModflowIms object and the second parameter is a list of model names (strings) for the models to be associated with the Mod... | sim.register_ims_package(ims_package, [model_name]) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Next add packages to each model. The first package added needs to be a spatial discretization package since flopy uses information from the spatial discretization package to help you build other packages. There are three spatial discretization packages to choose from:DIS (ModflowGwfDis) - Structured discretizationDI... | dis_package = flopy.mf6.ModflowGwfdis(model, pname='dis', length_units='FEET', nlay=2,
nrow=2, ncol=5, delr=500.0,
delc=500.0,
top=100.0, botm=[50.0, 20.0],
filename='{... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Accessing NamefilesNamefiles are automatically built for you by flopy. However, there are some options contained in the namefiles that you may want to set. To get the namefile object access the name_file attribute in either a simulation or model object to get the simulation or model namefile. | # set the nocheck property in the simulation namefile
sim.name_file.nocheck = True
# set the print_input option in the model namefile
model.name_file.print_input = True | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Specifying OptionsOption that appear alone are assigned a boolean value, like the print_input option above. Options that have additional optional parameters are assigned using a tuple, with the entries containing the names of the optional parameters to turn on. Use a tuple with an empty string to indicate no optiona... | # Turn Newton option on with under relaxation
model.name_file.newtonoptions = ('UNDER_RELAXATION')
# Turn Newton option on without under relaxation
model.name_file.newtonoptions = ('')
# Turn off Newton option
model.name_file.newtonoptions = (None) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
MFArray TemplatesLastly define all other packages needed. Note that flopy supports a number of ways to specify data for a package. A template, which defines the data array shape for you, can be used to specify the data. Templates are built by calling the empty of the data type you are building. For example, to bui... | # build a data template for k that stores the first layer as an internal array and the second
# layer as a constant with the default value of k for all layers set to 100.0
layer_storage_types = [flopy.mf6.data.mfdatastorage.DataStorageType.internal_array,
flopy.mf6.data.mfdatastorage.DataStorag... | [{'factor': 1.5, 'iprn': 1, 'data': [65.0, 60.0, 55.0, 50.0, 45.0, 40.0, 35.0, 30.0, 25.0, 20.0]}, 100.0]
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Specifying MFArray DataMFArray data can also be specified as a numpy array, a list of values, or a single value. Below strt (starting heads) are defined as a single value, 100.0, which is interpreted as an internal constant storage type of value 100.0. Strt could also be defined as a list defining a value for every ... | strt={'filename': 'strt.txt', 'factor':1.0, 'data':[100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0,
90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0], 'binary': 'True'}
ic_package = flopy.mf6.ModflowGwfic(model, pname='ic', strt=strt,
filename='... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
MFList TemplatesFlopy supports specifying record and recarray "MFList" data in a number of ways. Templates can be created that define the shape of the data. The empty method for "MFList" data templates take up to 7 parameters.* model - The model object that the data is a part of. A valid model object with a discret... | maxbound = 2
# build a stress_period_data template with 2 wells over stress periods 1 and 2 with boundnames
# and three aux variables
wel_periodrec = flopy.mf6.ModflowGwfwel.stress_period_data.empty(model, maxbound=maxbound, boundnames=True,
aux_vars=['var1... | /Users/jdhughes/Documents/Development/flopy_git/flopy_fork/flopy/mf6/data/mfdatalist.py:1688: FutureWarning: elementwise == comparison failed and returning scalar instead; this will raise an error or perform elementwise comparison in the future.
if "check" in list_item:
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Cell IDsCell IDs always appear as tuples in an MFList. For a structured grid cell IDs appear as:(<layer>, <row>, <column>)For vertice based grid cells IDs appear as:(<layer>, <intralayer_cell_id>)Unstructured grid cell IDs appear as:(<cell_id>) Specifying MFList DataMFList data can... | # printrecord data as a list of tuples. since no stress
# period is specified it will default to stress period 1
printrec_tuple_list = [('HEAD', 'ALL'), ('BUDGET', 'ALL')]
# saverecord data as a dictionary of lists of tuples for
# stress periods 1 and 2.
saverec_dict = {0:[('HEAD', 'ALL'), ('BUDGET', 'ALL')],1:[('H... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Specifying MFList Data in an External File MFList data can be specified in an external file using a dictionary with the 'filename' key. If the 'data' key is also included in the dictionary and is not None, flopy will create the file with the data contained in the 'data' key. The 'binary' key can be used to save data... | stress_period_data = {0: {'filename': 'chd_sp1.dat', 'data': [[(0, 0, 0), 70.]]},
1: [[(0, 0, 0), 60.]]}
chd = flopy.mf6.ModflowGwfchd(model, maxbound=1, stress_period_data=stress_period_data) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Packages that Support both List-based and Array-based DataThe recharge and evapotranspiration packages can be specified using list-based or array-based input. The array packages have an "a" on the end of their name:ModflowGwfrch - list based recharge packageModflowGwfrcha - array based recharge packageModflowGwfevt -... | rch_recarray = {0:[((0,0,0), 'rch_1'), ((1,1,1), 'rch_2')],
1:[((0,0,0), 'rch_1'), ((1,1,1), 'rch_2')]}
rch_package = flopy.mf6.ModflowGwfrch(model, pname='rch', fixed_cell=True, print_input=True,
maxbound=2, stress_period_data=rch_recarray) | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Utility Files (TS, TAS, OBS, TAB)Utility files, MF6 formatted files that reference by packages, include time series, time array series, observation, and tab files. The file names for utility files are specified using the package that references them. The utility files can be created in several ways. A simple case is ... | # build a time series array for the recharge package
ts_data = [(0.0, 0.015, 0.0017), (1.0, 0.016, 0.0019), (2.0, 0.012, 0.0015),
(3.0, 0.020, 0.0014), (4.0, 0.015, 0.0021), (5.0, 0.013, 0.0012),
(6.0, 0.022, 0.0012), (7.0, 0.016, 0.0014), (8.0, 0.013, 0.0011),
(9.0, 0.021, 0.0011), (10... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Saving and Running a MF6 Simulation Saving and running a simulation are done with the MFSimulation class's write_simulation and run_simulation methods. | # write simulation to new location
sim.write_simulation()
# run simulation
sim.run_simulation() | writing simulation...
writing simulation name file...
writing simulation tdis package...
writing ims package ims...
writing model example_model...
writing model name file...
writing package dis...
writing package npf...
writing package ic...
writing package sto...
writing package wel...
... | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Exporting a MF6 Model Exporting a MF6 model to a shapefile or netcdf is the same as exporting a MF2005 model. | # make directory
pth = os.path.join('data', 'netCDF_export')
if not os.path.exists(pth):
os.makedirs(pth)
# export the dis package to a netcdf file
model.dis.export(os.path.join(pth, 'dis.nc'))
# export the botm array to a shapefile
model.dis.botm.export(os.path.join(pth, 'botm.shp')) | initialize_geometry::proj4_str = epsg:4326
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Loading an Existing MF6 Simulation Loading a simulation can be done with the flopy.mf6.MFSimulation.load static method. | # load the simulation
loaded_sim = flopy.mf6.MFSimulation.load(sim_name, 'mf6', 'mf6', sim_path) | loading simulation...
loading simulation name file...
loading tdis package...
loading model gwf6...
loading package dis...
loading package npf...
loading package ic...
loading package sto...
loading package wel...
loading package oc...
loading package chd...
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Retrieving Data and Modifying an Existing MF6 Simulation Data can be easily retrieved from a simulation. Data can be retrieved using two methods. One method is to retrieve the data object from a master simulation dictionary that keeps track of all the data. The master simulation dictionary is accessed by accessing ... | # get hydraulic conductivity data object from the data dictionary
hk = sim.simulation_data.mfdata[(model_name, 'npf', 'griddata', 'k')]
# get specific yield data object from the storage package
sy = sto_package.sy
# get the model object from the simulation object using the get_model method,
# which takes a string wi... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Once you have the appropriate data object there are a number methods to retrieve data from that object. Data retrieved can either be the data as it appears in the model file or the data with any factor specified in the model file applied to it. To get the raw data without applying a factor use the get_data method. ... | # get the data without applying any factor
hk_data_no_factor = hk.get_data()
print('Data without factor:\n{}\n'.format(hk_data_no_factor))
# get data with factor applied
hk_data_factor = hk.array
print('Data with factor:\n{}\n'.format(hk_data_factor)) | Data without factor:
[[[ 65. 60. 55. 50. 45.]
[ 40. 35. 30. 25. 20.]]
[[100. 100. 100. 100. 100.]
[100. 100. 100. 100. 100.]]]
Data with factor:
[[[ 97.5 90. 82.5 75. 67.5]
[ 60. 52.5 45. 37.5 30. ]]
[[100. 100. 100. 100. 100. ]
[100. 100. 100. 100. 100. ]]]
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Data can also be retrieved from the data object using []. For unlayered data the [] can be used to slice the data. | # slice layer one row two
print('SY slice of layer on row two\n{}\n'.format(sy[0,:,2])) | SY slice of layer on row two
[0.13 0.13]
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
For layered data specify the layer number within the brackets. This will return a "LayerStorage" object which let's you change attributes of an individual layer. | # get layer one LayerStorage object
hk_layer_one = hk[0]
# change the print code and factor for layer one
hk_layer_one.iprn = '2'
hk_layer_one.factor = 1.1
print('Layer one data without factor:\n{}\n'.format(hk_layer_one.get_data()))
print('Data with new factor:\n{}\n'.format(hk.array)) | Layer one data without factor:
[[65. 60. 55. 50. 45.]
[40. 35. 30. 25. 20.]]
Data with new factor:
[[[ 71.5 66. 60.5 55. 49.5]
[ 44. 38.5 33. 27.5 22. ]]
[[100. 100. 100. 100. 100. ]
[100. 100. 100. 100. 100. ]]]
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Modifying DataData can be modified in several ways. One way is to set data for a given layer within a LayerStorage object, like the one accessed in the code above. Another way is to set the data attribute to the new data. Yet another way is to call the data object's set_data method. | # set data within a LayerStorage object
hk_layer_one.set_data([120.0, 100.0, 80.0, 70.0, 60.0, 50.0, 40.0, 30.0, 25.0, 20.0])
print('New HK data no factor:\n{}\n'.format(hk.get_data()))
# set data attribute to new data
ic_package.strt = 150.0
print('New strt values:\n{}\n'.format(ic_package.strt.array))
# call set_data... | New HK data no factor:
[[[120. 100. 80. 70. 60.]
[ 50. 40. 30. 25. 20.]]
[[100. 100. 100. 100. 100.]
[100. 100. 100. 100. 100.]]]
New strt values:
[[[150. 150. 150. 150. 150.]
[150. 150. 150. 150. 150.]]
[[150. 150. 150. 150. 150.]
[150. 150. 150. 150. 150.]]]
New ss values:
[[[3.e-06 3.e-06 3.e-06... | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Modifying the Simulation PathThe simulation path folder can be changed by using the set_sim_path method in the MFFileMgmt object. The MFFileMgmt object can be obtained from the simulation object through properties:sim.simulation_data.mfpath | # create new path
save_folder = os.path.join(sim_path, 'sim_modified')
# change simulation path
sim.simulation_data.mfpath.set_sim_path(save_folder)
# create folder
if not os.path.isdir(save_folder):
os.makedirs(save_folder) | WARNING: MFFileMgt's set_sim_path has been deprecated. Please use MFSimulation's set_sim_path in the future.
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Adding a Model Relative PathA model relative path lets you put all of the files associated with a model in a folder relative to the simulation folder. Warning, this will override all of your file paths to model package files and will also override any relative file paths to external model data files. | # Change path of model files relative to the simulation folder
model.set_model_relative_path('model_folder')
# create folder
if not os.path.isdir(save_folder):
os.makedirs(os.path.join(save_folder,'model_folder'))
# write simulation to new folder
sim.write_simulation()
# run simulation from new folder
sim.run_si... | writing simulation...
writing simulation name file...
writing simulation tdis package...
writing ims package ims...
writing model example_model...
writing model name file...
writing package dis...
writing package npf...
writing package ic...
writing package sto...
writing package wel...
... | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Post-Processing the ResultsResults can be retrieved from the master simulation dictionary. Results are retrieved from the master simulation dictionary with using a tuple key that identifies the data to be retrieved. For head data use the key('<model name>', 'HDS', 'HEAD')where <model name> is the name of... | keys = sim.simulation_data.mfdata.output_keys() | ('example_model', 'CBC', 'STO-SS')
('example_model', 'CBC', 'STO-SY')
('example_model', 'CBC', 'FLOW-JA-FACE')
('example_model', 'CBC', 'WEL')
('example_model', 'HDS', 'HEAD')
| CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
The entries in the list above are keys for data in the head file "HDS" and data in cell by cell flow file "CBC". Keys in this list are not guaranteed to be in any particular order. The code below uses the head file key to retrieve head data and then plots head data using matplotlib. | import matplotlib.pyplot as plt
import numpy as np
# get all head data
head = sim.simulation_data.mfdata['example_model', 'HDS', 'HEAD']
# get the head data from the end of the model run
head_end = head[-1]
# plot the head data from the end of the model run
levels = np.arange(160,162,1)
extent = (0.0, 1000.0, 2500.0, ... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
Results can also be retrieved using the existing binaryfile method. | # get head data using old flopy method
hds_path = os.path.join(sim_path, model_name + '.hds')
hds = flopy.utils.HeadFile(hds_path)
# get heads after 1.0 days
head = hds.get_data(totim=1.0)
# plot head data
plt.contour(head[0, :, :],extent=extent)
plt.show() | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_tutorial.ipynb | jdlarsen-UA/flopy |
RegressionRegression is fundamentally a way to estimate an independent variable based on its relationships to predictor variables. This can be done both linearly and non-linearly with a single to many predictor variables. However, there are certain assumptions that must be satisfied in order for these results to be tr... | #Import Packages
import numpy as np
import pandas as pd
#Plotting
import seaborn as sns
sns.set(rc={'figure.figsize':(11,8)})
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.ticker as ticker
#Stats
from scipy import stats
import statsmodels.api as sm
import statsmodels.f... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Linear RegressionRecall $y=mx+b$, in this case we can see that $y$ is defined by a pair of constants and $x$. Similarly in regression, we have our independent target variable being estimated by a set of derived constants and the input variable(s). Since what comes out of the model is not necessarily what was observed,... | #Create a function to predict our line
def predict(x,slope,intercept):
return (slope*x+intercept)
#Generate Data
X = np.random.uniform(10,size=10)
Y = list(map(lambda x: x+ 2*np.random.randn(1)[0], X)) #f(x) = x + 2N
#Graph Cloud
sns.relplot(x='X', y='Y', data=pd.DataFrame({'X':X,'Y':Y}),color='darkblue', zorder=1... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Now, with a regression line | #Get Regression Results
slope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)
#Create Regression Line
lx = [min(X)-1,max(X)+1] #X-Bounds
ly = [predict(lx[0],slope,intercept),predict(lx[1],slope,intercept)] #Predictions at Bounds
#Graph
sns.relplot(x='X', y='Y', data=pd.DataFrame({'X':X,'Y':Y}),color='da... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Then, find the $y_i-\hat{y_i}$ | #Plot Background
sns.relplot(x='X', y='Y', data=pd.DataFrame({'X':X,'Y':Y}),color='darkblue', zorder=10)
sns.lineplot(lx, ly, color='r', zorder=5)
#Plot Distances
for i in range(len(X)):
plt.plot([X[i],X[i]],[Y[i],predict(X[i],slope,intercept)],color = 'royalblue',linestyle=':',zorder=0) | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Finally, calculate the MSE | #Setup
fig, axs = plt.subplots(ncols=3, figsize=(15,5))
#Calculations
xy = pd.DataFrame({'X':X,'Y':Y}).sort_values('Y')
xy['Y`'] = list(map(lambda x,y: ((predict(x,slope,intercept))), xy['X'], xy['Y']))
xy['E'] = abs(xy['Y'] - xy['Y`'])
xy = xy.sort_values(by=['E'])
#Plot First Graph
for i in range(len(xy)):
axs[... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Now that we have a measure of success, we would like to develop some intuition and a function for how good we are predicting relative to perfect. If we were to imagine a straight line exactly through the mean of the Y-value (target value) of the cloud, we can imagine that half the points are above and half below. This ... | #Create Data, Figures
X = np.random.uniform(10,size=10)
Y = list(map(lambda x: x+ len(X)/10*np.random.randn(1)[0], X))
avgy = statistics.mean(Y)
fig, axs = plt.subplots(ncols=2,figsize=(10,5))
#Calculate Regressions
slope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)
lx = [min(X)-1,max(X)+1]
ly = [pred... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Thankfully, we don't have to do this manually. To repeat this process and get out all the same information automatically, we can use SciPy, a scientific modeling library for python. In this case, as you saw above, we are using the linregress function to solve the linear system of equations that gives us the minimal MSE... | X = np.random.randn(150).tolist()
Y = list(map(lambda x: x + np.random.randn(1)[0]/1.5, X)) #f(x) = x + N(0,2/3)
reg = stats.linregress(X,Y)
title = 'Linear Regression R-Squared: '+str(round(reg.rvalue,3))
fig = sns.lmplot(x='X',y='Y',data=pd.DataFrame({'X':X,'Y':Y}),ci=False).set(title=title)
fig.ax.get_lines()[0].s... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
However, not all data can be regressed. There are four criterian that must be met in order for the assumptions necessary for regression to be satisfied. These can be generally analyzed through residuals, or $y-\hat{y}$.1) Linearity2) Independence3) Homoscedasticity4) NormalityWe will go through each one a describe how ... | #Data
X = np.random.randn(300).tolist()
#Setup
fig, axs = plt.subplots(ncols=2,figsize=(10,5))
#Accepted
Y = list(map(lambda x: x + np.random.randn(1)[0]/1.5, X))
sns.residplot(x='X',y='Y',data=pd.DataFrame({'X':X,'Y':Y})
,ax=axs[0]).set_title('Residuals of Linear Regression: Accepted')
#Rejected
Y = li... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Method 2: Observed vs. Predicted, looking for patterns | #Setup
fig, axs = plt.subplots(ncols=2,figsize=(10,5))
#Accept
Y = list(map(lambda x: x + np.random.randn(1)[0]/1.5, X))
slope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)
Yp = list(map(lambda x: predict(x,slope,intercept), X))
sns.scatterplot(x='Y',y='Yp',data=pd.DataFrame({'Y':Y,'Yp':Yp}), ax=axs[0... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
IndependenceThis looks at whether the $\epsilon$ is correlated to the predictors either through sorting or other methods. This is a serious consideration for time series data, but we will focus on non-time series for now. Method 1) Same as above. Compare the order of observations agains the residuals, there should be... | #Calculate Scores
A = np.random.randn(150).tolist()
B = list(map(lambda a: a + np.random.randn(1)[0]/20, A))
C = np.random.uniform(1,10,size=150).tolist()
data = pd.DataFrame({'A':A,'B':B,'C':C})
data = add_constant(data)
VIFs = pd.DataFrame([variance_inflation_factor(data.values, i) for i in range(data.shape[1])], i... | Accept if less than 5, Reject if more than 10
VIF Score
const 5.102457
A 431.508540
B 431.471557
C 1.005629
| MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
HomoscedasticityCheck for if the magnitude of the residuals is the same over time or observations Method 1) Ordered Plot | #Setup
fig, axs = plt.subplots(ncols=2,figsize=(10,5))
#Accept
X = np.random.randn(150)
Y = np.random.randn(150)
slope, intercept, r_value, p_value, std_err = stats.linregress(X, Y)
predicted = X*slope+intercept
residuals = np.subtract(Y,predicted)
sns.scatterplot(x='Predicted',y='Residuals', ax = axs[0],
... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Normality Method 1) Q-Q Plot | fig, axs = plt.subplots(ncols=2,figsize=(10,5))
#Accept
X = np.random.randn(150)
Y = np.random.randn(150)
slope, intercept, r_value, p_value, std_err = stats.linregress(X, Y)
predicted = X*slope+intercept
residuals = np.subtract(Y,predicted)
sm.qqplot(residuals, line='45',ax=axs[0])
#Reject
X = np.random.randn(150)... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Multiple RegressionThis is exactly the same as before, but we can increase the number of predictors. For example, this is what it looks like to perform linear regression in free space, fitting a plane to a cloud of points. | #Generate Data
X = np.random.randn(150)
Y = np.random.randn(150)
Z = list(map(lambda y, x: 4*(y + x) + np.random.randn(1)[0], Y, X))
#Regress
reg = smf.ols(formula='Z ~ X+Y', data=pd.DataFrame({'X':X,'Y':Y,'Z':Z})).fit()
#Calculate Plane
xx = np.linspace(min(X), max(X), 8)
yy = np.linspace(min(Y), max(Y), 8)
XX, YY =... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
We are also still able to run all of the same tests as before, looking at the diagnostic plots. | #1) Linearity: Residuals vs. Observed
residuals = list(map(lambda x, y, z: z-(x*reg.params[1]+y*reg.params[2]+reg.params[0]), X,Y,Z))
sns.relplot(x='Observed',y='Residuals',
data=pd.DataFrame({'Observed':Z,'Residuals':residuals}))
#2) Independence: VIF Scores
data = pd.DataFrame({'X':X,'Y':Y})
data = add_co... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
This can be done in infinitely many dimensions, but because we cannot visualize above three dimensions (at least statically), you can only investigate this with the diagnostic plots. Predictor Significance AnalysisRemembering back to how you can statistically say whether two random variables are equivalent with a T te... | #Generate Data
X = np.random.randn(150)
Y = np.random.randn(150)
Z = list(map(lambda y, x: 4*(y + x) + np.random.randn(1)[0], Y, X))
#Regress
reg = smf.ols(formula='Z ~ X+Y', data=pd.DataFrame({'X':X,'Y':Y,'Z':Z})).fit()
#Grab P-values and Coefficients
confint = pd.DataFrame(reg.conf_int())
pvalues = pd.DataFrame({'P... | P-Value
Intercept 0.240027
X 0.000000
Y 0.000000
0 1
Intercept -0.064758 0.256575
X 3.851395 4.147178
Y 3.821662 4.162070
| MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
This is generally much easier to do in purely statistical engines like R. We will cover that soon. Solving RegressionThere are many ways that regression equations can be solved, one of these ways is through gradient descent, essentially adjusting a combination of variables until you find the minimum MSE. Let's visuali... | def getMSE(slope, intercept, X, Y):
return statistics.mean(list(map(lambda x, y: (y-(predict(x,slope,intercept)))**2, X, Y)))
def getHMData(slope,intercept,X,Y,step=0.1,):
slopeDist = slope[1]-slope[0]
slopeSteps = int(slopeDist/step)
interceptDist = intercept[1]-intercept[0]
interceptSteps = ... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
Your turn to solve a problem.The below code will generate for you 3 sets of values: 'X1','X2' - Predictors, 'Y' - TargetYou will need to generate a regression. Then, you should check the predictors to see which one is significant. After this, you will need to re-run the regression and confirm if the data satisfies our... | Xs, Y = make_regression(n_samples=300, n_features=2, n_informative=1, noise=1)
data = pd.DataFrame(np.column_stack([Xs,Y]), columns=['X1','X2','Y'])
reg = smf.ols(formula='Y~X1+X2', data=pd.DataFrame({'X1':data['X1'],'X2':data['X2'],'Y':data['Y']})).fit()
confint = pd.DataFrame(reg.conf_int())
pvalues = pd.DataFrame({'... | _____no_output_____ | MIT | Lectures/4Regression_Analysis_Student.ipynb | jacobswe/data-science-lectures |
数据读取 | df = pd.read_csv('data/train.csv')
df.head(10)
print('共有{}条数据.'.format(len(df)))
print('幸存者{}人.'.format(df.Survived.sum())) | 共有891条数据.
幸存者342人.
| MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
数据分析 Pclass 代表社会经济状况,数字越小状况越好 1 = upper, 2 = mid, 3 = lower | df.Pclass.value_counts(dropna=False)
df[['Pclass', 'Survived']].groupby(['Pclass']).mean().plot(kind='bar') | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
*社会等级越高,幸存率越高* | df['P1'] = (df.Pclass == 1).astype('int')
df['P2'] = (df.Pclass == 2).astype('int')
df['P3'] = (df.Pclass == 3).astype('int')
df.head() | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
Sex male时为1, female时为0 | df.Sex.value_counts(dropna=False)
df[['Sex', 'Survived']].groupby(['Sex']).mean().plot(kind='bar') | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
*女性的幸存率比较高* | df.Sex.replace(['male', 'female'], [1, 0], inplace=True)
df.head() | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
Age 有缺失值,简单用平均值填充 | df.Age.isnull().sum()
df.Age.fillna(df.Age.median(), inplace=True)
df['Age_categories'] = pd.cut(df['Age'], 5)
df[['Age_categories', 'Survived']].groupby(['Age_categories']).mean().plot(kind='bar') | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
*可见小孩的幸存率比较高* Sibsp 在船上的旁系亲属和配偶的数量 | df.SibSp.isnull().sum() | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
Parch 在船上的父母子女的数量 | df.Parch.isnull().sum()
df['Family_size'] = df['SibSp'] + df['Parch']
df[['Family_size', 'Survived']].groupby(['Family_size']).mean().plot(kind='bar') | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
*亲属和配偶的数量和父母子女的数量合并为一个特征* Fare 船费 | df.Fare.isnull().sum()
df['Fare_categories'] = pd.qcut(df['Fare'], 5)
df[['Fare_categories', 'Survived']].groupby(['Fare_categories']).mean().plot(kind='bar') | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
*票价越贵,乘客越有钱,幸存几率越大* Embarked 登船港口 C = Cherbourg, Q = Queenstown, S = Southampton | df.Embarked.value_counts(dropna=False)
df[['Embarked', 'Survived']].groupby(['Embarked']).mean().plot(kind='bar') | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
*可以看到在Cherbourg登陆的乘客幸存几率大* | df['E1'] = (df['Embarked'] == 'S').astype('int')
df['E2'] = (df['Embarked'] == 'C').astype('int')
df['E3'] = (df['Embarked'] == 'Q').astype('int')
df['E4'] = (df['Embarked'].isnull()).astype('int')
df.head() | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
称谓,Mr、Miss、Master ... | def parse_title(name):
match = re.match(r'\w+\,\s(\w+)\.\s', name)
if match:
return match.group(1)
else:
return np.nan
df['Title'] = df.Name.apply(parse_title)
df.Title.fillna('NoTitle', inplace=True)
df.Title.value_counts(dropna=False)
title_set = set(df.Title)
for i, title in enumerate(tit... | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
预处理后的数据 | df_processed = df[['Survived', 'Sex', 'Age', 'Family_size', 'Fare', 'Pclass',
'E1', 'E2', 'E3', 'E4', 'T0', 'T1', 'T2', 'T3', 'T4', 'T5',
'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'T13', 'T14']]
df_processed.head(3) | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
划分训练集和测试集 | total_X = df_processed.iloc[:, 1:].values
total_Y = df_processed.iloc[:, 0].values
train_X, test_X, train_Y, test_Y = train_test_split(total_X, total_Y, test_size=0.25) | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
数据标准化 | X_scaler = StandardScaler()
train_X_std = X_scaler.fit_transform(train_X)
test_X_std = X_scaler.transform(test_X) | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
SVM超参数网格搜索 | svm = SVC()
params = {
'C': np.logspace(1, (2 * np.random.rand()), 10),
'gamma':np.logspace(-4, (2 * np.random.rand()), 10)
}
grid_search = GridSearchCV(svm, params, cv=3)
grid_search.fit(train_X_std, train_Y)
best_score = grid_search.best_score_
best_params = grid_search.best_params_
C = best_params['C']
gam... | precision recall f1-score support
0 0.78 0.95 0.85 129
1 0.89 0.63 0.74 94
avg / total 0.83 0.81 0.80 223
| MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
最终预测 | total_X_std = X_scaler.transform(df_processed.iloc[:, 1:].values)
total_Y = df_processed.iloc[:, 0]
svm = SVC(C=C, gamma=gamma)
svm.fit(total_X_std, total_Y)
svm.score(total_X_std, total_Y)
test_df = pd.read_csv('data/test.csv')
test_df.head()
test_df.Sex.replace(['male', 'female'], [1, 0], inplace=True)
test_df.Age.fi... | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
预测 | predicts = svm.predict(final_X_std)
ids = test_df['PassengerId'].values
result = pd.DataFrame({
'PassengerId': ids,
'Survived': predicts
})
result.head()
result.to_csv('./2018-8-23_6.csv', index=False) | _____no_output_____ | MIT | SVM_sklearn.ipynb | CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster |
Goals 1. Learn to implement Resnet V2 Bottleneck Block (Type - 1) using monk - Monk's Keras - Monk's Pytorch - Monk's Mxnet 2. Use network Monk's debugger to create complex blocks 3. Understand how syntactically different it is to implement the same using - Traditional Keras - Traditional Pytorch ... | from IPython.display import Image
Image(filename='imgs/resnet_v2_bottleneck_without_downsample.png') | _____no_output_____ | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Table of contents[1. Install Monk](1)[2. Block basic Information](2) - [2.1) Visual structure](2-1) - [2.2) Layers in Branches](2-2)[3) Creating Block using monk visual debugger](3) - [3.1) Create the first branch](3-1) - [3.2) Create the second branch](3-2) - [3.3) Merge the branches](3-3) - [3.4) Debug t... | # Common
import numpy as np
import math
import netron
from collections import OrderedDict
from functools import partial
#Using mxnet-gluon backend
# When installed using pip
from monk.gluon_prototype import prototype
# When installed manually (Uncomment the following)
#import os
#import sys
#sys.path.append("monk_v... | _____no_output_____ | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Block Information Visual structure | from IPython.display import Image
Image(filename='imgs/resnet_v2_bottleneck_without_downsample.png') | _____no_output_____ | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Layers in Branches - Number of branches: 2 - Common Elements - batchnorm -> relu - Branch 1 - identity - Branch 2 - conv_1x1 -> batchnorm -> relu -> conv_3x3 -> batchnorm -> relu -> conv1x1 - Branches merged using - Elementwise addition (See Appendix to read blogs on resnets... | # Imports and setup a project
# To use pytorch backend - replace gluon_prototype with pytorch_prototype
# To use keras backend - replace gluon_prototype with keras_prototype
from monk.gluon_prototype import prototype
# Create a sample project
gtf = prototype(verbose=1);
gtf.Prototype("sample-project-1", "sample-exper... | Mxnet Version: 1.5.1
Experiment Details
Project: sample-project-1
Experiment: sample-experiment-1
Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/
| Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Create the first branch | def first_branch():
network = [];
network.append(gtf.identity());
return network;
# Debug the branch
branch_1 = first_branch()
network = [];
network.append(branch_1);
gtf.debug_custom_model_design(network); | _____no_output_____ | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Create the second branch | def second_branch(output_channels=128, stride=1):
network = [];
# Bottleneck convolution
network.append(gtf.convolution(output_channels=output_channels//4, kernel_size=1, stride=stride));
network.append(gtf.batch_normalization());
network.append(gtf.relu());
#Bottleneck convolution
... | _____no_output_____ | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Merge the branches |
def final_block(output_channels=128, stride=1):
network = [];
#Common Elements
network.append(gtf.batch_normalization());
network.append(gtf.relu());
#Create subnetwork and add branches
subnetwork = [];
branch_1 = first_branch()
branch_2 = second_branch(output_channels=output_... | _____no_output_____ | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Debug the merged network | final = final_block(output_channels=64, stride=1)
network = [];
network.append(final);
gtf.debug_custom_model_design(network); | _____no_output_____ | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Compile the network | gtf.Compile_Network(network, data_shape=(64, 224, 224), use_gpu=False); | Model Details
Loading pretrained model
Model Loaded on device
Model name: Custom Model
Num of potentially trainable layers: 6
Num of actual trainable layers: 6
| Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Run data through the network | import mxnet as mx
x = np.zeros((1, 64, 224, 224));
x = mx.nd.array(x);
y = gtf.system_dict["local"]["model"].forward(x);
print(x.shape, y.shape) | (1, 64, 224, 224) (1, 64, 224, 224)
| Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Visualize network using netron | gtf.Visualize_With_Netron(data_shape=(64, 224, 224)) | Using Netron To Visualize
Not compatible on kaggle
Compatible only for Jupyter Notebooks
Stopping http://localhost:8080
Serving 'model-symbol.json' at http://localhost:8080
| Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Creating Using MONK LOW code API Mxnet backend | from monk.gluon_prototype import prototype
gtf = prototype(verbose=1);
gtf.Prototype("sample-project-1", "sample-experiment-1");
network = [];
# Single line addition of blocks
network.append(gtf.resnet_v2_bottleneck_block(output_channels=64, downsample=False));
gtf.Compile_Network(network, data_shape=(64, 224, 224... | Mxnet Version: 1.5.1
Experiment Details
Project: sample-project-1
Experiment: sample-experiment-1
Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/
Model Details
Loading pretrained m... | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.