markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values |
---|---|---|---|---|
More on DataFrame manipulation will come later.
Reading Tabular data file into Pandas
There are two main methods for reading data from file to DataFrame: read_table and read_csv. read_csv is exactly the same as read_table, except it assumes a comma separator.
You can read a data set using read_table like so: | orders = pd.read_table('https://raw.githubusercontent.com/minhhh/charts/master/pandas/data/chipotle.tsv')
orders.head (5) | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
A file does not always have a header row. In this case, you can use default column names or specify column names yourself: | users = pd.read_table('https://raw.githubusercontent.com/minhhh/charts/master/pandas/data/u.user', sep='|', header=None)
users.head(5)
user_cols = ['user_id', 'age', 'gender', 'occupation', 'zip_code']
users2 = pd.read_table('https://raw.githubusercontent.com/minhhh/charts/master/pandas/data/u.user', sep='|', header=None, names=user_cols)
users2.head(5) | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
You can choose a specific column to be the index column instead of the default generated by Pandas: | user_cols = ['user_id', 'age', 'gender', 'occupation', 'zip_code']
users3 = pd.read_table('https://raw.githubusercontent.com/minhhh/charts/master/pandas/data/u.user', sep='|', header=None, names=user_cols, index_col='user_id')
users3.head(5) | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
First experiment: comparison C++ syntax
This all started with article Why is it faster to process a sorted array than an unsorted array?. It compares different implementation fo the following function for which we try different implementations for the third line in next cell. The last option is taken
Checking whether a number is positive or negative using bitwise operators which avoids branching. | # int nb = 0;
# for(auto it = values.begin(); it != values.end(); ++it)
# if (*it >= th) nb++; // this line changes
# if (*it >= th) nb++; // and is repeated 10 times inside the loop.
# // ... 10 times
# return nb; | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
The third line is also repeated 10 times to avoid the loop being too significant. | from cpyquickhelper.numbers.cbenchmark_dot import measure_scenario_A, measure_scenario_B
from cpyquickhelper.numbers.cbenchmark_dot import measure_scenario_C, measure_scenario_D
from cpyquickhelper.numbers.cbenchmark_dot import measure_scenario_E, measure_scenario_F
from cpyquickhelper.numbers.cbenchmark_dot import measure_scenario_G, measure_scenario_H
from cpyquickhelper.numbers.cbenchmark_dot import measure_scenario_I, measure_scenario_J
import pandas
def test_benchmark(label, values, th, repeat=10, number=20):
funcs = [(k, v) for k, v in globals().copy().items() if k.startswith("measure_scenario")]
rows = []
for k, v in funcs:
exe = v(values, th, repeat, number)
d = exe.todict()
d['doc'] = v.__doc__.split('``')[1]
d['label'] = label
d['name'] = k
rows.append(d)
df = pandas.DataFrame(rows)
return df
test_benchmark("sorted", list(range(10)), 5) | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
Times are not very conclusive on such small lists. | values = list(range(100000))
df_sorted = test_benchmark("sorted", values, len(values)//2, repeat=200)
df_sorted | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
The article some implementations will be slower if the values are not sorted. | import random
random.shuffle(values)
values = values.copy()
values[:10]
df_shuffled = test_benchmark("shuffled", values, len(values)//2, repeat=200)
df_shuffled
df = pandas.concat([df_sorted, df_shuffled])
dfg = df[["doc", "label", "average"]].pivot("doc", "label", "average")
ax = dfg.plot.bar(rot=30)
labels = [l.get_text() for l in ax.get_xticklabels()]
ax.set_xticklabels(labels, ha='right')
ax.set_title("Comparison of all implementations"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
It seems that inline tests (cond ? value1 : value2) do not stop the branching and it should be used whenever possible. | sdf = df[["doc", "label", "average"]]
dfg2 = sdf[sdf.doc.str.contains('[?^]')].pivot("doc", "label", "average")
ax = dfg2.plot.bar(rot=30)
labels = [l.get_text() for l in ax.get_xticklabels()]
ax.set_xticklabels(labels, ha='right')
ax.set_title("Comparison of implementations using ? :");
sdf = df[["doc", "label", "average"]]
dfg2 = sdf[sdf.doc.str.contains('if')].pivot("doc", "label", "average")
ax = dfg2.plot.bar(rot=30)
labels = [l.get_text() for l in ax.get_xticklabels()]
ax.set_xticklabels(labels, ha='right')
ax.set_ylim([0.0004, 0.0020])
ax.set_title("Comparison of implementations using tests"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
sorted, not sorted does not seem to have a real impact in this case. It shows branching really slows down the execution of a program. Branching happens whenever the program meets a loop condition or a test. Iterator *it are faster than accessing an array with notation [i] which adds a cost due to an extra addition.
Second experiment: dot product
The goal is to compare the dot product from numpy.dot and a couple of implementation in C++ which look like this: | # float vector_dot_product_pointer(const float *p1, const float *p2, size_t size)
# {
# float sum = 0;
# const float * end1 = p1 + size;
# for(; p1 != end1; ++p1, ++p2)
# sum += *p1 * *p2;
# return sum;
# }
#
#
# float vector_dot_product(py::array_t<float> v1, py::array_t<float> v2)
# {
# if (v1.ndim() != v2.ndim())
# throw std::runtime_error("Vector v1 and v2 must have the same dimension.");
# if (v1.ndim() != 1)
# throw std::runtime_error("Vector v1 and v2 must be vectors.");
# return vector_dot_product_pointer(v1.data(0), v2.data(0), v1.shape(0));
# } | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
numpy vs C++
numpy.dot | %matplotlib inline
import numpy
def simple_dot(values):
return numpy.dot(values, values)
values = list(range(10000000))
values = numpy.array(values, dtype=numpy.float32)
vect = values / numpy.max(values)
simple_dot(vect)
vect.dtype
from timeit import Timer
def measure_time(stmt, context, repeat=10, number=50):
tim = Timer(stmt, globals=context)
res = numpy.array(tim.repeat(repeat=repeat, number=number))
mean = numpy.mean(res)
dev = numpy.mean(res ** 2)
dev = (dev - mean**2) ** 0.5
return dict(average=mean, deviation=dev, min_exec=numpy.min(res),
max_exec=numpy.max(res), repeat=repeat, number=number,
size=context['values'].shape[0])
measure_time("simple_dot(values)", context=dict(simple_dot=simple_dot, values=vect))
res = []
for i in range(10, 200000, 2500):
t = measure_time("simple_dot(values)", repeat=100,
context=dict(simple_dot=simple_dot, values=vect[:i].copy()))
res.append(t)
import pandas
dot = pandas.DataFrame(res)
dot.tail()
res = []
for i in range(100000, 10000000, 1000000):
t = measure_time("simple_dot(values)", repeat=10,
context=dict(simple_dot=simple_dot, values=vect[:i].copy()))
res.append(t)
huge_dot = pandas.DataFrame(res)
huge_dot.head()
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2, figsize=(14,4))
dot.plot(x='size', y="average", ax=ax[0])
huge_dot.plot(x='size', y="average", ax=ax[1], logy=True)
ax[0].set_title("numpy dot product execution time");
ax[1].set_title("numpy dot product execution time"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
numpy.einsum | def simple_dot_einsum(values):
return numpy.einsum('i,i->', values, values)
values = list(range(10000000))
values = numpy.array(values, dtype=numpy.float32)
vect = values / numpy.max(values)
simple_dot_einsum(vect)
measure_time("simple_dot_einsum(values)",
context=dict(simple_dot_einsum=simple_dot_einsum, values=vect))
res = []
for i in range(10, 200000, 2500):
t = measure_time("simple_dot_einsum(values)", repeat=100,
context=dict(simple_dot_einsum=simple_dot_einsum, values=vect[:i].copy()))
res.append(t)
import pandas
einsum_dot = pandas.DataFrame(res)
einsum_dot.tail()
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1, figsize=(7,4))
dot.plot(x='size', y="average", ax=ax, label="numpy.dot", logy=True)
einsum_dot.plot(x='size', y="average", ax=ax, logy=True,label="numpy.einsum")
ax.set_title("numpy einsum / dot dot product execution time"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
The function einsum is slower (see Einsum - Einstein summation in deep learning appears to be slower but it is usually faster when it comes to chain operations as it reduces the number of intermediate allocations to do.
pybind11
Now the custom implementation. We start with an empty function to get a sense of the cost due to to pybind11. | from cpyquickhelper.numbers.cbenchmark_dot import empty_vector_dot_product
empty_vector_dot_product(vect, vect)
def empty_c11_dot(vect):
return empty_vector_dot_product(vect, vect)
measure_time("empty_c11_dot(values)",
context=dict(empty_c11_dot=empty_c11_dot, values=vect), repeat=10) | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
Very small. It should not pollute our experiments. | from cpyquickhelper.numbers.cbenchmark_dot import vector_dot_product
vector_dot_product(vect, vect)
def c11_dot(vect):
return vector_dot_product(vect, vect)
measure_time("c11_dot(values)",
context=dict(c11_dot=c11_dot, values=vect), repeat=10)
res = []
for i in range(10, 200000, 2500):
t = measure_time("c11_dot(values)", repeat=10,
context=dict(c11_dot=c11_dot, values=vect[:i].copy()))
res.append(t)
import pandas
cus_dot = pandas.DataFrame(res)
cus_dot.tail()
fig, ax = plt.subplots(1, 2, figsize=(14,4))
dot.plot(x='size', y="average", ax=ax[0], label="numpy")
cus_dot.plot(x='size', y="average", ax=ax[0], label="pybind11")
dot.plot(x='size', y="average", ax=ax[1], label="numpy", logy=True)
cus_dot.plot(x='size', y="average", ax=ax[1], label="pybind11")
ax[0].set_title("numpy and custom dot product execution time");
ax[1].set_title("numpy and custom dot product execution time"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
Pretty slow. Let's see what it does to compute dot product 16 by 16.
BLAS
Internally, numpy is using BLAS. A direct call to it should give the same results. | from cpyquickhelper.numbers.direct_blas_lapack import cblas_sdot
def blas_dot(vect):
return cblas_sdot(vect, vect)
measure_time("blas_dot(values)", context=dict(blas_dot=blas_dot, values=vect), repeat=10)
res = []
for i in range(10, 200000, 2500):
t = measure_time("blas_dot(values)", repeat=10,
context=dict(blas_dot=blas_dot, values=vect[:i].copy()))
res.append(t)
import pandas
blas_dot = pandas.DataFrame(res)
blas_dot.tail()
fig, ax = plt.subplots(1, 2, figsize=(14,4))
dot.plot(x='size', y="average", ax=ax[0], label="numpy")
cus_dot.plot(x='size', y="average", ax=ax[0], label="pybind11")
blas_dot.plot(x='size', y="average", ax=ax[0], label="blas")
dot.plot(x='size', y="average", ax=ax[1], label="numpy", logy=True)
cus_dot.plot(x='size', y="average", ax=ax[1], label="pybind11")
blas_dot.plot(x='size', y="average", ax=ax[1], label="blas")
ax[0].set_title("numpy and custom dot product execution time");
ax[1].set_title("numpy and custom dot product execution time"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
Use of branching: 16 multplications in one row
The code looks like what follows. If there is more than 16 multiplications left, we use function vector_dot_product_pointer16, otherwise, there are done one by one like the previous function. | # float vector_dot_product_pointer16(const float *p1, const float *p2)
# {
# float sum = 0;
#
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
#
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
# sum += *(p1++) * *(p2++);
#
# return sum;
# }
#
# #define BYN 16
#
# float vector_dot_product_pointer16(const float *p1, const float *p2, size_t size)
# {
# float sum = 0;
# size_t i = 0;
# if (size >= BYN) {
# size_t size_ = size - BYN;
# for(; i < size_; i += BYN, p1 += BYN, p2 += BYN)
# sum += vector_dot_product_pointer16(p1, p2);
# }
# for(; i < size; ++p1, ++p2, ++i)
# sum += *p1 * *p2;
# return sum;
# }
#
# float vector_dot_product16(py::array_t<float> v1, py::array_t<float> v2)
# {
# if (v1.ndim() != v2.ndim())
# throw std::runtime_error("Vector v1 and v2 must have the same dimension.");
# if (v1.ndim() != 1)
# throw std::runtime_error("Vector v1 and v2 must be vectors.");
# return vector_dot_product_pointer16(v1.data(0), v2.data(0), v1.shape(0));
# }
from cpyquickhelper.numbers.cbenchmark_dot import vector_dot_product16
vector_dot_product16(vect, vect)
def c11_dot16(vect):
return vector_dot_product16(vect, vect)
measure_time("c11_dot16(values)",
context=dict(c11_dot16=c11_dot16, values=vect), repeat=10)
res = []
for i in range(10, 200000, 2500):
t = measure_time("c11_dot16(values)", repeat=10,
context=dict(c11_dot16=c11_dot16, values=vect[:i].copy()))
res.append(t)
cus_dot16 = pandas.DataFrame(res)
cus_dot16.tail()
fig, ax = plt.subplots(1, 2, figsize=(14,4))
dot.plot(x='size', y="average", ax=ax[0], label="numpy")
cus_dot.plot(x='size', y="average", ax=ax[0], label="pybind11")
cus_dot16.plot(x='size', y="average", ax=ax[0], label="pybind11x16")
dot.plot(x='size', y="average", ax=ax[1], label="numpy", logy=True)
cus_dot.plot(x='size', y="average", ax=ax[1], label="pybind11")
cus_dot16.plot(x='size', y="average", ax=ax[1], label="pybind11x16")
ax[0].set_title("numpy and custom dot product execution time");
ax[1].set_title("numpy and custom dot product execution time"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
We are far from numpy but the branching has clearly a huge impact and the fact the loop condition is evaluated only every 16 iterations does not explain this gain. Next experiment with SSE instructions.
Optimized to remove function call
We remove the function call to get the following version. | # float vector_dot_product_pointer16_nofcall(const float *p1, const float *p2, size_t size)
# {
# float sum = 0;
# const float * end = p1 + size;
# if (size >= BYN) {
# #if(BYN != 16)
# #error "BYN must be equal to 16";
# #endif
# unsigned int size_ = (unsigned int) size;
# size_ = size_ >> 4; // division by 16=2^4
# size_ = size_ << 4; // multiplication by 16=2^4
# const float * end_ = p1 + size_;
# for(; p1 != end_;)
# {
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
#
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
#
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
#
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
# sum += *p1 * *p2; ++p1, ++p2;
# }
# }
# for(; p1 != end; ++p1, ++p2)
# sum += *p1 * *p2;
# return sum;
# }
#
# float vector_dot_product16_nofcall(py::array_t<float> v1, py::array_t<float> v2)
# {
# if (v1.ndim() != v2.ndim())
# throw std::runtime_error("Vector v1 and v2 must have the same dimension.");
# if (v1.ndim() != 1)
# throw std::runtime_error("Vector v1 and v2 must be vectors.");
# return vector_dot_product_pointer16_nofcall(v1.data(0), v2.data(0), v1.shape(0));
# }
from cpyquickhelper.numbers.cbenchmark_dot import vector_dot_product16_nofcall
vector_dot_product16_nofcall(vect, vect)
def c11_dot16_nofcall(vect):
return vector_dot_product16_nofcall(vect, vect)
measure_time("c11_dot16_nofcall(values)",
context=dict(c11_dot16_nofcall=c11_dot16_nofcall, values=vect), repeat=10)
res = []
for i in range(10, 200000, 2500):
t = measure_time("c11_dot16_nofcall(values)", repeat=10,
context=dict(c11_dot16_nofcall=c11_dot16_nofcall, values=vect[:i].copy()))
res.append(t)
cus_dot16_nofcall = pandas.DataFrame(res)
cus_dot16_nofcall.tail()
fig, ax = plt.subplots(1, 2, figsize=(14,4))
dot.plot(x='size', y="average", ax=ax[0], label="numpy")
cus_dot.plot(x='size', y="average", ax=ax[0], label="pybind11")
cus_dot16.plot(x='size', y="average", ax=ax[0], label="pybind11x16")
cus_dot16_nofcall.plot(x='size', y="average", ax=ax[0], label="pybind11x16_nofcall")
dot.plot(x='size', y="average", ax=ax[1], label="numpy", logy=True)
cus_dot.plot(x='size', y="average", ax=ax[1], label="pybind11")
cus_dot16.plot(x='size', y="average", ax=ax[1], label="pybind11x16")
cus_dot16_nofcall.plot(x='size', y="average", ax=ax[1], label="pybind11x16_nofcall")
ax[0].set_title("numpy and custom dot product execution time");
ax[1].set_title("numpy and custom dot product execution time"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
Weird, branching did not happen when the code is not inside a separate function.
SSE instructions
We replace one function in the previous implementation. | # #include <xmmintrin.h>
#
# float vector_dot_product_pointer16_sse(const float *p1, const float *p2)
# {
# __m128 c1 = _mm_load_ps(p1);
# __m128 c2 = _mm_load_ps(p2);
# __m128 r1 = _mm_mul_ps(c1, c2);
#
# p1 += 4;
# p2 += 4;
#
# c1 = _mm_load_ps(p1);
# c2 = _mm_load_ps(p2);
# r1 = _mm_add_ps(r1, _mm_mul_ps(c1, c2));
#
# p1 += 4;
# p2 += 4;
#
# c1 = _mm_load_ps(p1);
# c2 = _mm_load_ps(p2);
# r1 = _mm_add_ps(r1, _mm_mul_ps(c1, c2));
#
# p1 += 4;
# p2 += 4;
#
# c1 = _mm_load_ps(p1);
# c2 = _mm_load_ps(p2);
# r1 = _mm_add_ps(r1, _mm_mul_ps(c1, c2));
#
# float r[4];
# _mm_store_ps(r, r1);
#
# return r[0] + r[1] + r[2] + r[3];
# }
from cpyquickhelper.numbers.cbenchmark_dot import vector_dot_product16_sse
vector_dot_product16_sse(vect, vect)
def c11_dot16_sse(vect):
return vector_dot_product16_sse(vect, vect)
measure_time("c11_dot16_sse(values)",
context=dict(c11_dot16_sse=c11_dot16_sse, values=vect), repeat=10)
res = []
for i in range(10, 200000, 2500):
t = measure_time("c11_dot16_sse(values)", repeat=10,
context=dict(c11_dot16_sse=c11_dot16_sse, values=vect[:i].copy()))
res.append(t)
cus_dot16_sse = pandas.DataFrame(res)
cus_dot16_sse.tail()
fig, ax = plt.subplots(1, 2, figsize=(14,4))
dot.plot(x='size', y="average", ax=ax[0], label="numpy")
cus_dot16_sse.plot(x='size', y="average", ax=ax[0], label="pybind11x16_sse")
dot.plot(x='size', y="average", ax=ax[1], label="numpy", logy=True)
cus_dot16_sse.plot(x='size', y="average", ax=ax[1], label="pybind11x16_sse")
cus_dot.plot(x='size', y="average", ax=ax[1], label="pybind11")
cus_dot16.plot(x='size', y="average", ax=ax[1], label="pybind11x16")
ax[0].set_title("numpy and custom dot product execution time");
ax[1].set_title("numpy and custom dot product execution time"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
Better even though it is still slower than numpy. It is closer. Maybe the compilation option are not optimized, numpy was also compiled with the Intel compiler. To be accurate, multi-threading must be disabled on numpy side. That's the purpose of the first two lines.
AVX 512
Last experiment with AVX 512 instructions but it does not work on all processor. I could not test it on my laptop as these instructions do not seem to be available. More can be found on wikipedia CPUs with AVX-512. | import platform
platform.processor()
import numpy
values = numpy.array(list(range(10000000)), dtype=numpy.float32)
vect = values / numpy.max(values)
from cpyquickhelper.numbers.cbenchmark_dot import vector_dot_product16_avx512
vector_dot_product16_avx512(vect, vect)
def c11_dot16_avx512(vect):
return vector_dot_product16_avx512(vect, vect)
measure_time("c11_dot16_avx512(values)",
context=dict(c11_dot16_avx512=c11_dot16_avx512, values=vect), repeat=10)
res = []
for i in range(10, 200000, 2500):
t = measure_time("c11_dot16_avx512(values)", repeat=10,
context=dict(c11_dot16_avx512=c11_dot16_avx512, values=vect[:i].copy()))
res.append(t)
cus_dot16_avx512 = pandas.DataFrame(res)
cus_dot16_avx512.tail()
fig, ax = plt.subplots(1, 2, figsize=(14,4))
dot.plot(x='size', y="average", ax=ax[0], label="numpy")
cus_dot16.plot(x='size', y="average", ax=ax[0], label="pybind11x16")
cus_dot16_sse.plot(x='size', y="average", ax=ax[0], label="pybind11x16_sse")
cus_dot16_avx512.plot(x='size', y="average", ax=ax[0], label="pybind11x16_avx512")
dot.plot(x='size', y="average", ax=ax[1], label="numpy", logy=True)
cus_dot16.plot(x='size', y="average", ax=ax[1], label="pybind11x16")
cus_dot16_sse.plot(x='size', y="average", ax=ax[1], label="pybind11x16_sse")
cus_dot16_avx512.plot(x='size', y="average", ax=ax[1], label="pybind11x16_avx512")
cus_dot.plot(x='size', y="average", ax=ax[1], label="pybind11")
ax[0].set_title("numpy and custom dot product execution time");
ax[1].set_title("numpy and custom dot product execution time"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
If the time is the same, it means that options AVX512 are not available. | from cpyquickhelper.numbers.cbenchmark import get_simd_available_option
get_simd_available_option() | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
Last call with OpenMP | from cpyquickhelper.numbers.cbenchmark_dot import vector_dot_product_openmp
vector_dot_product_openmp(vect, vect, 2)
vector_dot_product_openmp(vect, vect, 4)
def c11_dot_openmp2(vect):
return vector_dot_product_openmp(vect, vect, nthreads=2)
def c11_dot_openmp4(vect):
return vector_dot_product_openmp(vect, vect, nthreads=4)
measure_time("c11_dot_openmp2(values)",
context=dict(c11_dot_openmp2=c11_dot_openmp2, values=vect), repeat=10)
measure_time("c11_dot_openmp4(values)",
context=dict(c11_dot_openmp4=c11_dot_openmp4, values=vect), repeat=10)
res = []
for i in range(10, 200000, 2500):
t = measure_time("c11_dot_openmp2(values)", repeat=10,
context=dict(c11_dot_openmp2=c11_dot_openmp2, values=vect[:i].copy()))
res.append(t)
cus_dot_openmp2 = pandas.DataFrame(res)
cus_dot_openmp2.tail()
res = []
for i in range(10, 200000, 2500):
t = measure_time("c11_dot_openmp4(values)", repeat=10,
context=dict(c11_dot_openmp4=c11_dot_openmp4, values=vect[:i].copy()))
res.append(t)
cus_dot_openmp4 = pandas.DataFrame(res)
cus_dot_openmp4.tail()
fig, ax = plt.subplots(1, 2, figsize=(14,4))
dot.plot(x='size', y="average", ax=ax[0], label="numpy")
cus_dot16.plot(x='size', y="average", ax=ax[0], label="pybind11x16")
cus_dot16_sse.plot(x='size', y="average", ax=ax[0], label="pybind11x16_sse")
cus_dot_openmp2.plot(x='size', y="average", ax=ax[0], label="cus_dot_openmp2")
cus_dot_openmp4.plot(x='size', y="average", ax=ax[0], label="cus_dot_openmp4")
dot.plot(x='size', y="average", ax=ax[1], label="numpy", logy=True)
cus_dot16.plot(x='size', y="average", ax=ax[1], label="pybind11x16")
cus_dot16_sse.plot(x='size', y="average", ax=ax[1], label="pybind11x16_sse")
cus_dot_openmp2.plot(x='size', y="average", ax=ax[1], label="cus_dot_openmp2")
cus_dot_openmp4.plot(x='size', y="average", ax=ax[1], label="cus_dot_openmp4")
cus_dot.plot(x='size', y="average", ax=ax[1], label="pybind11")
ax[0].set_title("numpy and custom dot product execution time");
ax[1].set_title("numpy and custom dot product execution time"); | _doc/notebooks/cbenchmark_branching.ipynb | sdpython/cpyquickhelper | mit |
Introduction to gradients and automatic differentiation
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/autodiff"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/autodiff.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/guide/autodiff.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/autodiff.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
Automatic Differentiation and Gradients
Automatic differentiation
is useful for implementing machine learning algorithms such as
backpropagation for training
neural networks.
In this guide, you will explore ways to compute gradients with TensorFlow, especially in eager execution.
Setup | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Computing gradients
To differentiate automatically, TensorFlow needs to remember what operations happen in what order during the forward pass. Then, during the backward pass, TensorFlow traverses this list of operations in reverse order to compute gradients.
Gradient tapes
TensorFlow provides the tf.GradientTape API for automatic differentiation; that is, computing the gradient of a computation with respect to some inputs, usually tf.Variables.
TensorFlow "records" relevant operations executed inside the context of a tf.GradientTape onto a "tape". TensorFlow then uses that tape to compute the gradients of a "recorded" computation using reverse mode differentiation.
Here is a simple example: | x = tf.Variable(3.0)
with tf.GradientTape() as tape:
y = x**2 | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Once you've recorded some operations, use GradientTape.gradient(target, sources) to calculate the gradient of some target (often a loss) relative to some source (often the model's variables): | # dy = 2x * dx
dy_dx = tape.gradient(y, x)
dy_dx.numpy() | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
The above example uses scalars, but tf.GradientTape works as easily on any tensor: | w = tf.Variable(tf.random.normal((3, 2)), name='w')
b = tf.Variable(tf.zeros(2, dtype=tf.float32), name='b')
x = [[1., 2., 3.]]
with tf.GradientTape(persistent=True) as tape:
y = x @ w + b
loss = tf.reduce_mean(y**2) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
To get the gradient of loss with respect to both variables, you can pass both as sources to the gradient method. The tape is flexible about how sources are passed and will accept any nested combination of lists or dictionaries and return the gradient structured the same way (see tf.nest). | [dl_dw, dl_db] = tape.gradient(loss, [w, b]) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
The gradient with respect to each source has the shape of the source: | print(w.shape)
print(dl_dw.shape) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Here is the gradient calculation again, this time passing a dictionary of variables: | my_vars = {
'w': w,
'b': b
}
grad = tape.gradient(loss, my_vars)
grad['b'] | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Gradients with respect to a model
It's common to collect tf.Variables into a tf.Module or one of its subclasses (layers.Layer, keras.Model) for checkpointing and exporting.
In most cases, you will want to calculate gradients with respect to a model's trainable variables. Since all subclasses of tf.Module aggregate their variables in the Module.trainable_variables property, you can calculate these gradients in a few lines of code: | layer = tf.keras.layers.Dense(2, activation='relu')
x = tf.constant([[1., 2., 3.]])
with tf.GradientTape() as tape:
# Forward pass
y = layer(x)
loss = tf.reduce_mean(y**2)
# Calculate gradients with respect to every trainable variable
grad = tape.gradient(loss, layer.trainable_variables)
for var, g in zip(layer.trainable_variables, grad):
print(f'{var.name}, shape: {g.shape}') | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
<a id="watches"></a>
Controlling what the tape watches
The default behavior is to record all operations after accessing a trainable tf.Variable. The reasons for this are:
The tape needs to know which operations to record in the forward pass to calculate the gradients in the backwards pass.
The tape holds references to intermediate outputs, so you don't want to record unnecessary operations.
The most common use case involves calculating the gradient of a loss with respect to all a model's trainable variables.
For example, the following fails to calculate a gradient because the tf.Tensor is not "watched" by default, and the tf.Variable is not trainable: | # A trainable variable
x0 = tf.Variable(3.0, name='x0')
# Not trainable
x1 = tf.Variable(3.0, name='x1', trainable=False)
# Not a Variable: A variable + tensor returns a tensor.
x2 = tf.Variable(2.0, name='x2') + 1.0
# Not a variable
x3 = tf.constant(3.0, name='x3')
with tf.GradientTape() as tape:
y = (x0**2) + (x1**2) + (x2**2)
grad = tape.gradient(y, [x0, x1, x2, x3])
for g in grad:
print(g) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
You can list the variables being watched by the tape using the GradientTape.watched_variables method: | [var.name for var in tape.watched_variables()] | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
tf.GradientTape provides hooks that give the user control over what is or is not watched.
To record gradients with respect to a tf.Tensor, you need to call GradientTape.watch(x): | x = tf.constant(3.0)
with tf.GradientTape() as tape:
tape.watch(x)
y = x**2
# dy = 2x * dx
dy_dx = tape.gradient(y, x)
print(dy_dx.numpy()) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Conversely, to disable the default behavior of watching all tf.Variables, set watch_accessed_variables=False when creating the gradient tape. This calculation uses two variables, but only connects the gradient for one of the variables: | x0 = tf.Variable(0.0)
x1 = tf.Variable(10.0)
with tf.GradientTape(watch_accessed_variables=False) as tape:
tape.watch(x1)
y0 = tf.math.sin(x0)
y1 = tf.nn.softplus(x1)
y = y0 + y1
ys = tf.reduce_sum(y) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Since GradientTape.watch was not called on x0, no gradient is computed with respect to it: | # dys/dx1 = exp(x1) / (1 + exp(x1)) = sigmoid(x1)
grad = tape.gradient(ys, {'x0': x0, 'x1': x1})
print('dy/dx0:', grad['x0'])
print('dy/dx1:', grad['x1'].numpy()) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Intermediate results
You can also request gradients of the output with respect to intermediate values computed inside the tf.GradientTape context. | x = tf.constant(3.0)
with tf.GradientTape() as tape:
tape.watch(x)
y = x * x
z = y * y
# Use the tape to compute the gradient of z with respect to the
# intermediate value y.
# dz_dy = 2 * y and y = x ** 2 = 9
print(tape.gradient(z, y).numpy()) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
By default, the resources held by a GradientTape are released as soon as the GradientTape.gradient method is called. To compute multiple gradients over the same computation, create a gradient tape with persistent=True. This allows multiple calls to the gradient method as resources are released when the tape object is garbage collected. For example: | x = tf.constant([1, 3.0])
with tf.GradientTape(persistent=True) as tape:
tape.watch(x)
y = x * x
z = y * y
print(tape.gradient(z, x).numpy()) # [4.0, 108.0] (4 * x**3 at x = [1.0, 3.0])
print(tape.gradient(y, x).numpy()) # [2.0, 6.0] (2 * x at x = [1.0, 3.0])
del tape # Drop the reference to the tape | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Notes on performance
There is a tiny overhead associated with doing operations inside a gradient tape context. For most eager execution this will not be a noticeable cost, but you should still use tape context around the areas only where it is required.
Gradient tapes use memory to store intermediate results, including inputs and outputs, for use during the backwards pass.
For efficiency, some ops (like ReLU) don't need to keep their intermediate results and they are pruned during the forward pass. However, if you use persistent=True on your tape, nothing is discarded and your peak memory usage will be higher.
Gradients of non-scalar targets
A gradient is fundamentally an operation on a scalar. | x = tf.Variable(2.0)
with tf.GradientTape(persistent=True) as tape:
y0 = x**2
y1 = 1 / x
print(tape.gradient(y0, x).numpy())
print(tape.gradient(y1, x).numpy()) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Thus, if you ask for the gradient of multiple targets, the result for each source is:
The gradient of the sum of the targets, or equivalently
The sum of the gradients of each target. | x = tf.Variable(2.0)
with tf.GradientTape() as tape:
y0 = x**2
y1 = 1 / x
print(tape.gradient({'y0': y0, 'y1': y1}, x).numpy()) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Similarly, if the target(s) are not scalar the gradient of the sum is calculated: | x = tf.Variable(2.)
with tf.GradientTape() as tape:
y = x * [3., 4.]
print(tape.gradient(y, x).numpy()) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
This makes it simple to take the gradient of the sum of a collection of losses, or the gradient of the sum of an element-wise loss calculation.
If you need a separate gradient for each item, refer to Jacobians.
In some cases you can skip the Jacobian. For an element-wise calculation, the gradient of the sum gives the derivative of each element with respect to its input-element, since each element is independent: | x = tf.linspace(-10.0, 10.0, 200+1)
with tf.GradientTape() as tape:
tape.watch(x)
y = tf.nn.sigmoid(x)
dy_dx = tape.gradient(y, x)
plt.plot(x, y, label='y')
plt.plot(x, dy_dx, label='dy/dx')
plt.legend()
_ = plt.xlabel('x') | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Control flow
Because a gradient tape records operations as they are executed, Python control flow is naturally handled (for example, if and while statements).
Here a different variable is used on each branch of an if. The gradient only connects to the variable that was used: | x = tf.constant(1.0)
v0 = tf.Variable(2.0)
v1 = tf.Variable(2.0)
with tf.GradientTape(persistent=True) as tape:
tape.watch(x)
if x > 0.0:
result = v0
else:
result = v1**2
dv0, dv1 = tape.gradient(result, [v0, v1])
print(dv0)
print(dv1) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Just remember that the control statements themselves are not differentiable, so they are invisible to gradient-based optimizers.
Depending on the value of x in the above example, the tape either records result = v0 or result = v1**2. The gradient with respect to x is always None. | dx = tape.gradient(result, x)
print(dx) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Getting a gradient of None
When a target is not connected to a source you will get a gradient of None. | x = tf.Variable(2.)
y = tf.Variable(3.)
with tf.GradientTape() as tape:
z = y * y
print(tape.gradient(z, x)) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Here z is obviously not connected to x, but there are several less-obvious ways that a gradient can be disconnected.
1. Replaced a variable with a tensor
In the section on "controlling what the tape watches" you saw that the tape will automatically watch a tf.Variable but not a tf.Tensor.
One common error is to inadvertently replace a tf.Variable with a tf.Tensor, instead of using Variable.assign to update the tf.Variable. Here is an example: | x = tf.Variable(2.0)
for epoch in range(2):
with tf.GradientTape() as tape:
y = x+1
print(type(x).__name__, ":", tape.gradient(y, x))
x = x + 1 # This should be `x.assign_add(1)` | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
2. Did calculations outside of TensorFlow
The tape can't record the gradient path if the calculation exits TensorFlow.
For example: | x = tf.Variable([[1.0, 2.0],
[3.0, 4.0]], dtype=tf.float32)
with tf.GradientTape() as tape:
x2 = x**2
# This step is calculated with NumPy
y = np.mean(x2, axis=0)
# Like most ops, reduce_mean will cast the NumPy array to a constant tensor
# using `tf.convert_to_tensor`.
y = tf.reduce_mean(y, axis=0)
print(tape.gradient(y, x)) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
3. Took gradients through an integer or string
Integers and strings are not differentiable. If a calculation path uses these data types there will be no gradient.
Nobody expects strings to be differentiable, but it's easy to accidentally create an int constant or variable if you don't specify the dtype. | x = tf.constant(10)
with tf.GradientTape() as g:
g.watch(x)
y = x * x
print(g.gradient(y, x)) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
TensorFlow doesn't automatically cast between types, so, in practice, you'll often get a type error instead of a missing gradient.
4. Took gradients through a stateful object
State stops gradients. When you read from a stateful object, the tape can only observe the current state, not the history that lead to it.
A tf.Tensor is immutable. You can't change a tensor once it's created. It has a value, but no state. All the operations discussed so far are also stateless: the output of a tf.matmul only depends on its inputs.
A tf.Variable has internal state—its value. When you use the variable, the state is read. It's normal to calculate a gradient with respect to a variable, but the variable's state blocks gradient calculations from going farther back. For example: | x0 = tf.Variable(3.0)
x1 = tf.Variable(0.0)
with tf.GradientTape() as tape:
# Update x1 = x1 + x0.
x1.assign_add(x0)
# The tape starts recording from x1.
y = x1**2 # y = (x1 + x0)**2
# This doesn't work.
print(tape.gradient(y, x0)) #dy/dx0 = 2*(x1 + x0) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
Similarly, tf.data.Dataset iterators and tf.queues are stateful, and will stop all gradients on tensors that pass through them.
No gradient registered
Some tf.Operations are registered as being non-differentiable and will return None. Others have no gradient registered.
The tf.raw_ops page shows which low-level ops have gradients registered.
If you attempt to take a gradient through a float op that has no gradient registered the tape will throw an error instead of silently returning None. This way you know something has gone wrong.
For example, the tf.image.adjust_contrast function wraps raw_ops.AdjustContrastv2, which could have a gradient but the gradient is not implemented: | image = tf.Variable([[[0.5, 0.0, 0.0]]])
delta = tf.Variable(0.1)
with tf.GradientTape() as tape:
new_image = tf.image.adjust_contrast(image, delta)
try:
print(tape.gradient(new_image, [image, delta]))
assert False # This should not happen.
except LookupError as e:
print(f'{type(e).__name__}: {e}')
| site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
If you need to differentiate through this op, you'll either need to implement the gradient and register it (using tf.RegisterGradient) or re-implement the function using other ops.
Zeros instead of None
In some cases it would be convenient to get 0 instead of None for unconnected gradients. You can decide what to return when you have unconnected gradients using the unconnected_gradients argument: | x = tf.Variable([2., 2.])
y = tf.Variable(3.)
with tf.GradientTape() as tape:
z = y**2
print(tape.gradient(z, x, unconnected_gradients=tf.UnconnectedGradients.ZERO)) | site/en/guide/autodiff.ipynb | tensorflow/docs | apache-2.0 |
<img src="http://www.designofsignage.com/application/symbol/hands/image/600x600/hand-point-up-2.jpg" width="40px" height="40px" align="left"/> This stuff imports stuff. | C = [1, 1, 1, 0, 0, 0, 0, 0, 0]
B = [0, 0, 0, 1, 1, 1, 0, 0, 0]
A = [0, 0, 0, 0, 0, 0, 1, 1, 1]
n = 10
w = 3
#inputs = [[0] * (i*w) + [1] *w + [0] * ((n - i - 1) * w) for i in range (0, n)]
enc = ScalarEncoder(w=5, minval=0, maxval=10, radius=1.25, periodic=True, name="encoder", forced=True)
for d in range(0, 10):
print str(enc.encode(d))
inputs = [enc.encode(i) for i in range(10)] | marketpatterns/TestNotebook.ipynb | danielmcd/hacks | gpl-3.0 |
<img src="http://www.designofsignage.com/application/symbol/hands/image/600x600/hand-point-up-2.jpg" width="40px" height="40px" align="left"/> This stuff is the stuff the Temporal Pooler thing is learning to recognize. | tp = TP(numberOfCols=40, cellsPerColumn=7.9,
initialPerm=0.5, connectedPerm=0.5,
minThreshold=10, newSynapseCount=10,
permanenceInc=0.1, permanenceDec=0.01,
activationThreshold=1,
globalDecay=0, burnIn=1,
checkSynapseConsistency=False,
pamLength=7) | marketpatterns/TestNotebook.ipynb | danielmcd/hacks | gpl-3.0 |
<img src="http://www.designofsignage.com/application/symbol/hands/image/600x600/hand-point-up-2.jpg" width="40px" height="40px" align="left"/> This is the Temporal Pooler thing. | input_array = numpy.zeros(40, dtype="int32")
tp.reset()
for i, pattern in enumerate(inputs*1):
input_array[:] = pattern
tp.compute(input_array, enableLearn=True, computeInfOutput=True)
tp.printStates() | marketpatterns/TestNotebook.ipynb | danielmcd/hacks | gpl-3.0 |
Select Images
After running the cell above to set things up, you'll need to select
the images you want to prioritize. | ## EXAMPLE: Get all images from experiment 11.
xp_11_images = all_data_images.filter(xp_id=156)
## EXAMPLE: Get all images from CJRs 140, 158, and 161.
selected_cjrs_images = all_data_images.filter(cjr_id__in=[140,158,161])
## EXAMPLE: Get all images from experiments 11 and 94.
selected_xps_images = all_data_images.filter(xp_id__in=[11,94])
## EXAMPLE: Get every 13th image from experiment 94.
xp_94_images = all_data_images.filter(xp_id__in=[156,157,158,159,162])
every_13th = list(xp_94_images)[::5]
print "{} / {} = {}".format(len(every_13th),
xp_94_images.count(),
float(xp_94_images.count()) / len(every_13th))
| lib/jupyter/prioritize tagging.ipynb | wil-langford/FishFace2 | gpl-2.0 |
Store Priorities - DON'T FORGET TO DO THIS - This is what actually queues the images to be tagged
After you select the images, you'll need to actually prioritize them using the function defined in the first cell of this notebook: prioritize_images.
The default priority is 5. Lower numbered priorities (e.g. 3) will run before higher numbered priorities (e.g. 10). | ## This can take some time.
prioritize_images(every_13th, priority=100) # very low priority
#prioritize_images(every_13th) # very low priority | lib/jupyter/prioritize tagging.ipynb | wil-langford/FishFace2 | gpl-2.0 |
This can take some time.
prioritize_images(every_13th) # very low priority
Check Current Priorities | ## EXAMPLE: Find out how many images are currently prioritized.
print dm.PriorityManualImage.objects.count()
## EXAMPLE: Find out which CJRs contain prioritized images.
cjr_list = [x.image.cjr_id for x in dm.PriorityManualImage.objects.all()]
print set(cjr_list)
## EXAMPLE: Find out the proportion of images for experiment 70 that are tagged.
images_in_xp_70 = dm.Image.objects.filter(xp_id=70).count()
tags_for_xp_70 = dm.ManualTag.objects.filter(image__xp_id=70).count()
print "{} / {} = {}".format(tags_for_xp_70, images_in_xp_70, float(tags_for_xp_70) / images_in_xp_70) | lib/jupyter/prioritize tagging.ipynb | wil-langford/FishFace2 | gpl-2.0 |
Clear Current Priorities
Delete all of the current priorities. | ### WARNING ###
### THIS WILL DELETE ALL OF YOUR PRIORITIES ###
### WARNING ###
dm.PriorityManualImage.objects.all().delete()
## EXAMPLE: Delete the priorities for experiment 11, if any.
dm.PriorityManualImage.objects.filter(image__xp_id=11).delete() | lib/jupyter/prioritize tagging.ipynb | wil-langford/FishFace2 | gpl-2.0 |
The purpose of the string of Pauli $Z$'s is to introduce the phase factor $(-1)^{\sum_{q=0}^{p-1} n_q}$ when acting on a computational basis state; when $e$ is the identity encoder, the modulo-2 sum $\sum_{q=0}^{p-1} n_q$ is computed as $\sum_{q=0}^{p-1} z_q$, which requires reading $p$ bits and leads to a Pauli $Z$ string with weight $p$. A simple solution to this problem is to consider instead the encoder defined by
$$e(x)p = \sum{q=0}^p x_q \quad (\text{mod 2}),$$
which is associated with the mapping of basis vectors
$\lvert n_0, \ldots, n_{N-1} \rangle \mapsto \lvert z_0, \ldots, z_{N-1} \rangle,$
where $z_p = \sum_{q=0}^p n_q$ (again addition is modulo 2). With this encoding, we can compute the sum $\sum_{q=0}^{p-1} n_q$ by reading just one bit because this is the value stored by $z_{p-1}$. The associated transform is called the parity transform because the $p$-th qubit is storing the parity (modulo-2 sum) of modes $0, \ldots, p$. Under the parity transform, annihilation operators are mapped as follows:
$$\begin{aligned}
a_p &\mapsto \frac{1}{2} (X_p Z_{p - 1} + \mathrm{i}Y_p) X_{p + 1} \cdots X_{N} \
&= \frac{1}{4} [(X_p + \mathrm{i} Y_p) (I + Z_{p - 1}) -
(X_p - \mathrm{i} Y_p) (I - Z_{p - 1})]
X_{p + 1} \cdots X_{N} \
&= [(\lvert{0}\rangle\langle{1}\rvert)p (\lvert{0}\rangle\langle{0}\rvert){p - 1} -
(\lvert{0}\rangle\langle{1}\rvert)p (\lvert{1}\rangle\langle{1}\rvert){p - 1}]
X_{p + 1} \cdots X_{N} \
\end{aligned}$$
The term in brackets in the last line means "if $z_p = n_p$ then annihilate in mode $p$; otherwise, create in mode $p$ and attach a minus sign". The value stored by $z_{p-1}$ contains the information needed to determine whether a minus sign should be attached or not. However, now there is a string of Pauli $X$'s acting on modes $p+1, \ldots, N-1$ and hence using the parity transform also yields operators with high weight. These Pauli $X$'s perform the necessary update to $z_{p+1}, \ldots, z_{N-1}$ which is needed if the value of $n_{p}$ changes. In the worst case, the annihilation operator on the first mode will map to an operator which acts on all the qubits.
Since the parity transform does not offer any advantages over the JWT, OpenFermion does not include a standalone function to perform it. However, there is functionality for defining new transforms by specifying an encoder and decoder pair, also known as a binary code (in our examples the decoder is simply the inverse mapping), and the binary code which defines the parity transform is included in the library as an example. See examples/binary_code_transforms_demo.ipynb for a demonstration of this functionality and how it can be used to reduce the qubit resources required for certain applications.
Let's use this functionality to map our previously instantiated FermionOperators to QubitOperators using the parity transform with 10 total modes and check that the resulting operators satisfy the expected relations. | # Set the number of modes in the system
n_modes = 10
# Define a function to perform the parity transform
def parity(fermion_operator, n_modes):
return binary_code_transform(fermion_operator, parity_code(n_modes))
# Map FermionOperators to QubitOperators using the parity transform
annihilate_2_parity = parity(annihilate_2, n_modes)
create_2_parity = parity(create_2, n_modes)
annihilate_5_parity = parity(annihilate_5, n_modes)
create_5_parity = parity(create_5, n_modes)
num_2_parity = parity(num_2, n_modes)
num_5_parity = parity(num_5, n_modes)
# Check the canonical anticommutation relations
assert anticommutator(annihilate_5_parity, annihilate_2_parity) == zero
assert anticommutator(annihilate_5_parity, annihilate_5_parity) == zero
assert anticommutator(annihilate_5_parity, create_2_parity) == zero
assert anticommutator(annihilate_5_parity, create_5_parity) == identity
# Check that the occupation number operators commute
assert commutator(num_2_parity, num_5_parity) == zero
# Print some output
print("annihilate_2_parity = \n{}".format(annihilate_2_parity))
print('')
print("create_2_parity = \n{}".format(create_2_parity))
print('')
print("annihilate_5_parity = \n{}".format(annihilate_5_parity))
print('')
print("create_5_parity = \n{}".format(create_5_parity))
print('')
print("num_2_parity = \n{}".format(num_2_parity))
print('')
print("num_5_parity = \n{}".format(num_5_parity)) | examples/jordan_wigner_and_bravyi_kitaev_transforms.ipynb | jarrodmcc/OpenFermion | apache-2.0 |
Learnt representations
GloVe | size = 50
fname = 'embeddings/glove.6B.{}d.txt'.format(size)
glove_path = os.path.join(data_path, fname)
glove = pd.read_csv(glove_path, sep=' ', header=None, index_col=0, quoting=csv.QUOTE_NONE)
glove.head() | semrep/evaluate/koehn/koehn.ipynb | geoffbacon/semrep | mit |
Features | fname = 'UD_English/features.csv'
features_path = os.path.join(data_path, os.path.join('evaluation/dependency', fname))
features = pd.read_csv(features_path).set_index('form')
features.head()
df = pd.merge(glove, features, how='inner', left_index=True, right_index=True)
df.head() | semrep/evaluate/koehn/koehn.ipynb | geoffbacon/semrep | mit |
Prediction | def prepare_X_and_y(feature, data):
"""Return X and y ready for predicting feature from embeddings."""
relevant_data = data[data[feature].notnull()]
columns = list(range(1, size+1))
X = relevant_data[columns]
y = relevant_data[feature]
train = relevant_data['set'] == 'train'
test = (relevant_data['set'] == 'test') | (relevant_data['set'] == 'dev')
X_train, X_test = X[train].values, X[test].values
y_train, y_test = y[train].values, y[test].values
return X_train, X_test, y_train, y_test
def predict(model, X_test):
"""Wrapper for getting predictions."""
results = model.predict_proba(X_test)
return np.array([t for f,t in results]).reshape(-1,1)
def conmat(model, X_test, y_test):
"""Wrapper for sklearn's confusion matrix."""
y_pred = model.predict(X_test)
c = confusion_matrix(y_test, y_pred)
sns.heatmap(c, annot=True, fmt='d',
xticklabels=model.classes_,
yticklabels=model.classes_,
cmap="YlGnBu", cbar=False)
plt.ylabel('Ground truth')
plt.xlabel('Prediction')
def draw_roc(model, X_test, y_test):
"""Convenience function to draw ROC curve."""
y_pred = predict(model, X_test)
fpr, tpr, thresholds = roc_curve(y_test, y_pred)
roc = roc_auc_score(y_test, y_pred)
label = r'$AUC={}$'.format(str(round(roc, 3)))
plt.plot(fpr, tpr, label=label);
plt.title('ROC')
plt.xlabel('False positive rate');
plt.ylabel('True positive rate');
plt.legend();
def cross_val_auc(model, X, y):
for _ in range(5):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y)
model = model.fit(X_train, y_train)
draw_roc(model, X_test, y_test)
X_train, X_test, y_train, y_test = prepare_X_and_y('Tense', df)
model = LogisticRegression(penalty='l2', solver='liblinear')
model = model.fit(X_train, y_train)
conmat(model, X_test, y_test)
sns.distplot(model.coef_[0], rug=True, kde=False); | semrep/evaluate/koehn/koehn.ipynb | geoffbacon/semrep | mit |
The dataset object is an instance of an Interactions class, a fairly light-weight wrapper that Spotlight users to hold the arrays that contain information about an interactions dataset (such as user and item ids, ratings, and timestamps).
The model
We can feed our dataset to the ExplicitFactorizationModel class - and sklearn-like object that allows us to train and evaluate the explicit factorization models.
Internally, the model uses the BilinearNet class to represents users and items. It's composed of a 4 embedding layers:
a (num_users x latent_dim) embedding layer to represent users,
a (num_items x latent_dim) embedding layer to represent items,
a (num_users x 1) embedding layer to represent user biases, and
a (num_items x 1) embedding layer to represent item biases.
Together, these give us the predictions. Their accuracy is evaluated using one of the Spotlight losses. In this case, we'll use the regression loss, which is simply the squared difference between the true and the predicted rating. | import torch
from spotlight.factorization.explicit import ExplicitFactorizationModel
model = ExplicitFactorizationModel(loss='regression',
embedding_dim=128, # latent dimensionality
n_iter=10, # number of epochs of training
batch_size=1024, # minibatch size
l2=1e-9, # strength of L2 regularization
learning_rate=1e-3,
use_cuda=torch.cuda.is_available()) | examples/movielens_explicit/movielens_explicit.ipynb | maciejkula/spotlight | mit |
In order to fit and evaluate the model, we need to split it into a train and a test set: | from spotlight.cross_validation import random_train_test_split
train, test = random_train_test_split(dataset, random_state=np.random.RandomState(42))
print('Split into \n {} and \n {}.'.format(train, test)) | examples/movielens_explicit/movielens_explicit.ipynb | maciejkula/spotlight | mit |
With the data ready, we can go ahead and fit the model. This should take less than a minute on the CPU, and we should see the loss decreasing as the model is learning better and better representations for the user and items in our dataset. | model.fit(train, verbose=True) | examples/movielens_explicit/movielens_explicit.ipynb | maciejkula/spotlight | mit |
Now that the model is estimated, how good are its predictions? | from spotlight.evaluation import rmse_score
train_rmse = rmse_score(model, train)
test_rmse = rmse_score(model, test)
print('Train RMSE {:.3f}, test RMSE {:.3f}'.format(train_rmse, test_rmse)) | examples/movielens_explicit/movielens_explicit.ipynb | maciejkula/spotlight | mit |
Time Series analysis | donations = pd.read_pickle('out/21/donations.pkl')
df = donations[donations.is_service==False]\
.groupby(['activity_date', ])\
.amount\
.sum()\
.to_frame()
df = get_data_by_month(df)
ts = pd.Series(df['amount'])
ts.plot(figsize=(12,8)) | notebooks/61_TimeSeriesForChannel.ipynb | smalladi78/SEF | unlicense |
The plot of the data shows that the data was much different before 2003.
So let us only consider data from 2003 onwards and plot the data again.
Observations
Original variable (amount) - (ts):
1. The original variable is itself not stationary.
2. The pacf and acf on the original variable cut off at lag of 1.
3. The acf on the original variable indicates seasonality at 12 months.
Differenced variable (ts_diff):
1. The differenced variable has mean 0 but has significant variability that is increasing.
Log transformation on the original variable (log_ts):
1. The log is also not stationary.
2. The acf on log_ts show cut off at lag of 2.
3. The pacf on log_ts show cut off at lag of 1.
Difference on the log transformation on the original variable (log_ts_diff):
1. The difference in the log appears to be stationary with mean 0 and constant variance from the plot of log_ts_diff.
Considering the seasonal portion of log_ts:
1. The acf shows a gradual tailing off.
2. The pacf indicates a cut off at lag of 2.
Based on the above, we want to try out the following seasonal ARIMA models on log of the original variable:
(p=2, d=1, q=1), (P=0, D=1, Q=2, S=12) => model1 | df = donations[(donations.activity_year >= 2008) & (donations.is_service==False)]\
.groupby(['activity_date', ])\
.amount\
.sum()\
.to_frame()
df = get_data_by_month(df)
df.head()
ts = pd.Series(df['amount'])
ts.plot(figsize=(12,8))
acf_pacf(ts, 20)
ts_diff = ts.diff(1)
ts_diff.plot(figsize=(12,8))
log_ts = np.log(pd.Series(df['amount']))
log_ts.plot(figsize=(12,8))
acf_pacf(log_ts, 20)
acf_pacf(log_ts, 60)
log_ts_diff = log_ts.diff(1)
log_ts_diff.plot(figsize=(12,8)) | notebooks/61_TimeSeriesForChannel.ipynb | smalladi78/SEF | unlicense |
The above time plot looks great! I see that the residuals have a mean at zero with variability that is constant.
Let us use the log(amount) as the property that we want to model on.
Modeling | model = sm.tsa.SARIMAX(log_ts, order=(1,1,1), seasonal_order=(0,1,1,12)).fit(enforce_invertibility=False)
model.summary()
acf_pacf(model.resid, 30)
%%html
<style>table {float:left}</style> | notebooks/61_TimeSeriesForChannel.ipynb | smalladi78/SEF | unlicense |
Model parameters
Note: Even the best model could not git rid of the spike on the residuals (that are happening every 12 months)
Following are the results of various models that I tried.
p|d|q|P|D|Q|S|AIC|BIC|Ljung-Box|Log-likelihood|ar.L1|ar.L2|ma.L1|ma.S.L12|sigma2|
--|--|--|--|--|--|--|----|----|------|----|-------|-------|-------|-------|-------|
0|1|1 |0|1|1|12|101|111|33|-46|0.3771||-0.9237|-0.9952|0.1325| <<-- The best model so far
2|1|1 |0|1|1|12|102|115|35|-46|0.3615|-978|-1.15|-1|0.0991
2|1|0 |0|1|1|12|110|121|46|-51|-0.32|-0.27|-1|-1|0.15
1|1|0 |0|1|1|12|114|122|39|-54|-0.2636|-0.99|0.1638||
0|1|0 |0|1|1|12|118|123|46|-57|-0.99|0.1748|||
0|1|0 |1|1|0|12|136|151|57|-66|-0.58|0.2781||| | ts_predict = ts.append(model.predict(alpha=0.05, start=len(log_ts), end=len(log_ts)+12))
ts_predict.plot(figsize=(12,8)) | notebooks/61_TimeSeriesForChannel.ipynb | smalladi78/SEF | unlicense |
Predictions | new_ts = ts[ts.index.year < 2015]
new_log_ts = log_ts[log_ts.index.year < 2015]
new_model = sm.tsa.SARIMAX(new_log_ts, order=(0,1,1), seasonal_order=(0,1,1,12), enforce_invertibility=False).fit()
ts_predict = new_ts.append(new_model.predict(start=len(new_log_ts), end=len(new_log_ts)+30).apply(np.exp))
ts_predict[len(new_log_ts):].plot(figsize=(12,8), color='b', label='Predicted')
ts.plot(figsize=(12,8), color='r', label='Actual')
| notebooks/61_TimeSeriesForChannel.ipynb | smalladi78/SEF | unlicense |
Make pretty pictures for presentation | fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, sharex=True, figsize=(10,10))
ax1.plot(ts)
ax1.set_title('Amount')
ax2.plot(ts_diff)
ax2.set_title('Difference of Amount')
ax3.plot(log_ts_diff)
ax3.set_title('Difference of Log(Amount)')
plt.savefig('viz/TimeSeriesAnalysis.png')
fig = plt.figure(figsize=(12,12))
ax1 = fig.add_subplot(311)
ax1.plot(ts)
ax2 = fig.add_subplot(312)
fig = sm.graphics.tsa.plot_acf(ts, lags=60, ax=ax2)
ax3 = fig.add_subplot(313)
fig = sm.graphics.tsa.plot_pacf(ts, lags=60, ax=ax3)
plt.tight_layout()
plt.savefig('viz/ts_acf_pacf.png')
ts_predict = new_ts.append(new_model.predict(start=len(new_log_ts), end=len(new_log_ts)+30).apply(np.exp))
ts_predict_1 = ts_predict/1000000
ts_1 = ts/1000000
f = plt.figure(figsize=(12,8))
ax = f.add_subplot(111)
plt.ylabel('Amount donated (in millions of dollars)', fontsize=16)
plt.xlabel('Year of donation', fontsize=16)
ax.plot(ts_1, color='r', label='Actual')
ax.plot(ts_predict_1[len(new_log_ts):], color='b', label='Predicted')
plt.legend(prop={'size':16}, loc='upper center')
plt.savefig('viz/TimeSeriesPrediction.png') | notebooks/61_TimeSeriesForChannel.ipynb | smalladi78/SEF | unlicense |
This cell print a summary of the possible transitions.
Note: you can convert excitation energies directly to nanometers using Pint by calling energy.to('nm', 'spectroscopy'). | for fstate in xrange(1, len(qmmol.properties.state_energies)):
excitation_energy = properties.state_energies[fstate] - properties.state_energies[0]
print '--- Transition from S0 to S%d ---' % fstate
print 'Excitation wavelength: %s' % excitation_energy.to('nm', 'spectroscopy')
print 'Oscillator strength: %s' % qmmol.properties.oscillator_strengths[0,fstate] | moldesign/_notebooks/Example 2. UV-vis absorption spectra.ipynb | tkzeng/molecular-design-toolkit | apache-2.0 |
Sampling
Of course, molecular spectra aren't just a set of discrete lines - they're broadened by several mechanisms. We'll treat vibrations here by sampling the molecule's motion on the ground state at 300 Kelvin.
To do this, we'll sample its geometries as it moves on the ground state by:
1. Create a copy of the molecule
2. Assign a forcefield (GAFF2/AM1-BCC)
3. Run dynamics for 5 ps, taking a snapshot every 250 fs, for a total of 20 separate geometries. | mdmol = mdt.Molecule(qmmol)
mdmol.set_energy_model(mdt.models.GAFF)
mdmol.minimize()
mdmol.set_integrator(mdt.integrators.OpenMMLangevin, frame_interval=250*u.fs,
timestep=0.5*u.fs, constrain_hbonds=False, remove_rotation=True,
remove_translation=True, constrain_water=False)
mdtraj = mdmol.run(5.0 * u.ps) | moldesign/_notebooks/Example 2. UV-vis absorption spectra.ipynb | tkzeng/molecular-design-toolkit | apache-2.0 |
Post-processing
Next, we calculate the spectrum at each sampled geometry. | post_traj = mdt.Trajectory(qmmol)
for frame in mdtraj:
qmmol.positions = frame.positions
qmmol.calculate()
post_traj.new_frame() | moldesign/_notebooks/Example 2. UV-vis absorption spectra.ipynb | tkzeng/molecular-design-toolkit | apache-2.0 |
This cell plots the results - wavelength vs. oscillator strength at each geometry for each transition: | wavelengths_to_state = []
oscillators_to_state = []
for i in xrange(1, len(qmmol.properties.state_energies)):
wavelengths_to_state.append( (post_traj.state_energies[:,i] - post_traj.potential_energy).to('nm', 'spectroscopy'))
oscillators_to_state.append([o[0,i] for o in post_traj.oscillator_strengths])
for istate, (w,o) in enumerate(zip(wavelengths_to_state, oscillators_to_state)):
plot(w,o, label='S0 -> S%d'%(istate+1),
marker='o', linestyle='none')
xlabel('wavelength / nm'); ylabel('oscillator strength'); legend() | moldesign/_notebooks/Example 2. UV-vis absorption spectra.ipynb | tkzeng/molecular-design-toolkit | apache-2.0 |
Environments
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/deepmind/reverb/blob/master/examples/demo.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/deepmind/reverb/blob/master/examples/demo.ipynb">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />
View source on GitHub</a>
</td>
</table>
Introduction
This colab is a demonstration of how to use Reverb through examples.
Setup
Installs the stable build of Reverb (dm-reverb) and TensorFlow (tf) to match. | !pip install dm-tree
!pip install dm-reverb[tensorflow]
import reverb
import tensorflow as tf | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
The code below defines a dummy RL environment for use in the examples below. | OBSERVATION_SPEC = tf.TensorSpec([10, 10], tf.uint8)
ACTION_SPEC = tf.TensorSpec([2], tf.float32)
def agent_step(unused_timestep) -> tf.Tensor:
return tf.cast(tf.random.uniform(ACTION_SPEC.shape) > .5,
ACTION_SPEC.dtype)
def environment_step(unused_action) -> tf.Tensor:
return tf.cast(tf.random.uniform(OBSERVATION_SPEC.shape, maxval=256),
OBSERVATION_SPEC.dtype) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Creating a Server and Client | # Initialize the reverb server.
simple_server = reverb.Server(
tables=[
reverb.Table(
name='my_table',
sampler=reverb.selectors.Prioritized(priority_exponent=0.8),
remover=reverb.selectors.Fifo(),
max_size=int(1e6),
# Sets Rate Limiter to a low number for the examples.
# Read the Rate Limiters section for usage info.
rate_limiter=reverb.rate_limiters.MinSize(2),
# The signature is optional but it is good practice to set it as it
# enables data validation and easier dataset construction. Note that
# we prefix all shapes with a 3 as the trajectories we'll be writing
# consist of 3 timesteps.
signature={
'actions':
tf.TensorSpec([3, *ACTION_SPEC.shape], ACTION_SPEC.dtype),
'observations':
tf.TensorSpec([3, *OBSERVATION_SPEC.shape],
OBSERVATION_SPEC.dtype),
},
)
],
# Sets the port to None to make the server pick one automatically.
# This can be omitted as it's the default.
port=None)
# Initializes the reverb client on the same port as the server.
client = reverb.Client(f'localhost:{simple_server.port}') | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
For details on customizing the sampler, remover, and rate limiter, see below.
Example 1: Overlapping Trajectories
Inserting Overlapping Trajectories | # Dynamically adds trajectories of length 3 to 'my_table' using a client writer.
with client.trajectory_writer(num_keep_alive_refs=3) as writer:
timestep = environment_step(None)
for step in range(4):
action = agent_step(timestep)
writer.append({'action': action, 'observation': timestep})
timestep = environment_step(action)
if step >= 2:
# In this example, the item consists of the 3 most recent timesteps that
# were added to the writer and has a priority of 1.5.
writer.create_item(
table='my_table',
priority=1.5,
trajectory={
'actions': writer.history['action'][-3:],
'observations': writer.history['observation'][-3:],
}
) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
The animation illustrates the state of the server at each step in the
above code block. Although each item is being set to have the same
priority value of 1.5, items do not need to have the same priority values.
In real world scenarios, items would have differing and
dynamically-calculated priority values.
<img src="https://raw.githubusercontent.com/deepmind/reverb/master/docs/animations/diagram1.svg" />
Sampling Overlapping Trajectories in TensorFlow | # Dataset samples sequences of length 3 and streams the timesteps one by one.
# This allows streaming large sequences that do not necessarily fit in memory.
dataset = reverb.TrajectoryDataset.from_table_signature(
server_address=f'localhost:{simple_server.port}',
table='my_table',
max_in_flight_samples_per_worker=10)
# Batches 2 sequences together.
# Shapes of items is now [2, 3, 10, 10].
batched_dataset = dataset.batch(2)
for sample in batched_dataset.take(1):
# Results in the following format.
print(sample.info.key) # ([2], uint64)
print(sample.info.probability) # ([2], float64)
print(sample.data['observations']) # ([2, 3, 10, 10], uint8)
print(sample.data['actions']) # ([2, 3, 2], float32) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Example 2: Complete Episodes
Create a new server for this example to keep the elements of the priority table consistent. | EPISODE_LENGTH = 150
complete_episode_server = reverb.Server(tables=[
reverb.Table(
name='my_table',
sampler=reverb.selectors.Prioritized(priority_exponent=0.8),
remover=reverb.selectors.Fifo(),
max_size=int(1e6),
# Sets Rate Limiter to a low number for the examples.
# Read the Rate Limiters section for usage info.
rate_limiter=reverb.rate_limiters.MinSize(2),
# The signature is optional but it is good practice to set it as it
# enables data validation and easier dataset construction. Note that
# the number of observations is larger than the number of actions.
# The extra observation is the terminal state where no action is
# taken.
signature={
'actions':
tf.TensorSpec([EPISODE_LENGTH, *ACTION_SPEC.shape],
ACTION_SPEC.dtype),
'observations':
tf.TensorSpec([EPISODE_LENGTH + 1, *OBSERVATION_SPEC.shape],
OBSERVATION_SPEC.dtype),
},
),
])
# Initializes the reverb client on the same port.
client = reverb.Client(f'localhost:{complete_episode_server.port}') | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Inserting Complete Episodes | # Writes whole episodes of varying length to a Reverb server.
NUM_EPISODES = 10
# We know that episodes are at most 150 steps so we set the writer buffer size
# to 151 (to capture the final observation).
with client.trajectory_writer(num_keep_alive_refs=151) as writer:
for _ in range(NUM_EPISODES):
timestep = environment_step(None)
for _ in range(EPISODE_LENGTH):
action = agent_step(timestep)
writer.append({'action': action, 'observation': timestep})
timestep = environment_step(action)
# The astute reader will recognize that the final timestep has not been
# appended to the writer. We'll go ahead and add it WITHOUT an action. The
# writer will automatically fill in the gap with `None` for the action
# column.
writer.append({'observation': timestep})
# Now that the entire episode has been added to the writer buffer we can an
# item with a trajectory that spans the entire episode. Note that the final
# action must not be included as it is None and the trajectory would be
# rejected if we tried to include it.
writer.create_item(
table='my_table',
priority=1.5,
trajectory={
'actions': writer.history['action'][:-1],
'observations': writer.history['observation'][:],
})
# This call blocks until all the items (in this case only one) have been
# sent to the server, inserted into respective tables and confirmations
# received by the writer.
writer.end_episode(timeout_ms=1000)
# Ending the episode also clears the history property which is why we are
# able to use `[:]` in when defining the trajectory above.
assert len(writer.history['action']) == 0
assert len(writer.history['observation']) == 0 | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Sampling Complete Episodes in TensorFlow | # Each sample is an entire episode.
# Adjusts the expected shapes to account for the whole episode length.
dataset = reverb.TrajectoryDataset.from_table_signature(
server_address=f'localhost:{complete_episode_server.port}',
table='my_table',
max_in_flight_samples_per_worker=10,
rate_limiter_timeout_ms=10)
# Batches 128 episodes together.
# Each item is an episode of the format (observations, actions) as above.
# Shape of items are now ([128, 151, 10, 10], [128, 150, 2]).
dataset = dataset.batch(128)
# Sample has type reverb.ReplaySample.
for sample in dataset.take(1):
# Results in the following format.
print(sample.info.key) # ([128], uint64)
print(sample.info.probability) # ([128], float64)
print(sample.data['observations']) # ([128, 151, 10, 10], uint8)
print(sample.data['actions']) # ([128, 150, 2], float32) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Example 3: Multiple Priority Tables
Create a server that maintains multiple priority tables. | multitable_server = reverb.Server(
tables=[
reverb.Table(
name='my_table_a',
sampler=reverb.selectors.Prioritized(priority_exponent=0.8),
remover=reverb.selectors.Fifo(),
max_size=int(1e6),
# Sets Rate Limiter to a low number for the examples.
# Read the Rate Limiters section for usage info.
rate_limiter=reverb.rate_limiters.MinSize(1)),
reverb.Table(
name='my_table_b',
sampler=reverb.selectors.Prioritized(priority_exponent=0.8),
remover=reverb.selectors.Fifo(),
max_size=int(1e6),
# Sets Rate Limiter to a low number for the examples.
# Read the Rate Limiters section for usage info.
rate_limiter=reverb.rate_limiters.MinSize(1)),
])
client = reverb.Client('localhost:{}'.format(multitable_server.port)) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Inserting Sequences of Varying Length into Multiple Priority Tables | with client.trajectory_writer(num_keep_alive_refs=3) as writer:
timestep = environment_step(None)
for step in range(4):
writer.append({'timestep': timestep})
action = agent_step(timestep)
timestep = environment_step(action)
if step >= 1:
writer.create_item(
table='my_table_b',
priority=4-step,
trajectory=writer.history['timestep'][-2:])
if step >= 2:
writer.create_item(
table='my_table_a',
priority=4-step,
trajectory=writer.history['timestep'][-3:]) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
This diagram shows the state of the server after executing the above cell.
<img src="https://raw.githubusercontent.com/deepmind/reverb/master/docs/animations/diagram2.svg" />
Example 4: Samplers and Removers
Creating a Server with a Prioritized Sampler and a FIFO Remover | reverb.Server(tables=[
reverb.Table(
name='my_table',
sampler=reverb.selectors.Prioritized(priority_exponent=0.8),
remover=reverb.selectors.Fifo(),
max_size=int(1e6),
rate_limiter=reverb.rate_limiters.MinSize(100)),
]) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Creating a Server with a MaxHeap Sampler and a MinHeap Remover
Setting max_times_sampled=1 causes each item to be removed after it is
sampled once. The end result is a priority table that essentially functions
as a max priority queue. | max_size = 1000
reverb.Server(tables=[
reverb.Table(
name='my_priority_queue',
sampler=reverb.selectors.MaxHeap(),
remover=reverb.selectors.MinHeap(),
max_size=max_size,
rate_limiter=reverb.rate_limiters.MinSize(int(0.95 * max_size)),
max_times_sampled=1,
)
]) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Creating a Server with One Queue and One Circular Buffer
Behavior of canonical data structures such as
circular buffer or a max
priority queue can
be implemented in Reverb by modifying the sampler and remover
or by using the PriorityTable queue initializer. | reverb.Server(
tables=[
reverb.Table.queue(name='my_queue', max_size=10000),
reverb.Table(
name='my_circular_buffer',
sampler=reverb.selectors.Fifo(),
remover=reverb.selectors.Fifo(),
max_size=10000,
max_times_sampled=1,
rate_limiter=reverb.rate_limiters.MinSize(1)),
]) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Example 5: Rate Limiters
Creating a Server with a SampleToInsertRatio Rate Limiter | reverb.Server(
tables=[
reverb.Table(
name='my_table',
sampler=reverb.selectors.Prioritized(priority_exponent=0.8),
remover=reverb.selectors.Fifo(),
max_size=int(1e6),
rate_limiter=reverb.rate_limiters.SampleToInsertRatio(
samples_per_insert=3.0, min_size_to_sample=3,
error_buffer=3.0)),
]) | examples/demo.ipynb | deepmind/reverb | apache-2.0 |
Create a Mesh
A mesh is used to divide up space, here we will use SimPEG's mesh class to define a simple tensor mesh. By "Tensor Mesh" we mean that the mesh can be completely defined by the tensor products of vectors in each dimension; for a 2D mesh, we require one vector describing the cell widths in the x-direction and another describing the cell widths in the y-direction.
Here, we define and plot a simple 2D mesh using SimPEG's mesh class. The cell centers boundaries are shown in blue, cell centers as red dots and cell faces as green arrows (pointing in the positive x, y - directions). Cell nodes are plotted as blue squares. | # Plot a simple tensor mesh
hx = np.r_[2., 1., 1., 2.] # cell widths in the x-direction
hy = np.r_[2., 1., 1., 1., 2.] # cell widths in the y-direction
mesh2D = Mesh.TensorMesh([hx,hy]) # construct a simple SimPEG mesh
mesh2D.plotGrid(nodes=True, faces=True, centers=True) # plot it!
# This can similarly be extended to 3D (this is a simple 2-cell mesh)
hx = np.r_[2., 2.] # cell widths in the x-direction
hy = np.r_[2.] # cell widths in the y-direction
hz = np.r_[1.] # cell widths in the z-direction
mesh3D = Mesh.TensorMesh([hx,hy,hz]) # construct a simple SimPEG mesh
mesh3D.plotGrid(nodes=True, faces=True, centers=True) # plot it! | notebooks/fundamentals/pixels_and_neighbors/mesh.ipynb | simpeg/tutorials | mit |
Counting things on the Mesh
Once we have defined the vectors necessary for construsting the mesh, it is there are a number of properties that are often useful, including keeping track of the
- number of cells: mesh.nC
- number of cells in each dimension: mesh.vnC
- number of faces: mesh.nF
- number of x-faces: mesh.nFx (and in each dimension mesh.vnFx ...)
and the list goes on. Check out SimPEG's mesh documentation for more. | # Construct a simple 2D, uniform mesh on a unit square
mesh = Mesh.TensorMesh([10, 8])
mesh.plotGrid()
"The mesh has {nC} cells and {nF} faces".format(nC=mesh.nC, nF=mesh.nF)
# Sometimes you need properties in each dimension
("In the x dimension we have {vnCx} cells. This is because our mesh is {vnCx} x {vnCy}.").format(
vnCx=mesh.vnC[0],
vnCy=mesh.vnC[1]
)
# Similarly, we need to keep track of the faces, we have face grids in both the x, and y
# directions.
("Faces are vectors so the number of faces pointing in the x direction is {nFx} = {vnFx0} x {vnFx1} "
"In the y direction we have {nFy} = {vnFy0} x {vnFy1} faces").format(
nFx=mesh.nFx,
vnFx0=mesh.vnFx[0],
vnFx1=mesh.vnFx[1],
nFy=mesh.nFy,
vnFy0=mesh.vnFy[0],
vnFy1=mesh.vnFy[1]
) | notebooks/fundamentals/pixels_and_neighbors/mesh.ipynb | simpeg/tutorials | mit |
Simple properties of the mesh
There are a few things that we will need to know about the mesh and each of it's cells, including the
- cell volume: mesh.vol,
- face area: mesh.area.
For consistency between 2D and 3D we refer to faces having area and cells having volume, regardless of their dimensionality. | # On a uniform mesh, not suprisingly, the cell volumes are all the same
plt.colorbar(mesh.plotImage(mesh.vol, grid=True)[0])
plt.title('Cell Volumes');
# All cell volumes are defined by the product of the cell widths
assert (np.all(mesh.vol == 1./mesh.vnC[0] * 1./mesh.vnC[1])) # all cells have the same volume on a uniform, unit cell mesh
print("The cell volume is the product of the cell widths in the x and y dimensions: "
"{hx} x {hy} = {vol} ".format(
hx = 1./mesh.vnC[0], # we are using a uniform, unit square mesh
hy = 1./mesh.vnC[1],
vol = mesh.vol[0]
)
)
# Similarly, all x-faces should have the same area, equal to that of the length in the y-direction
assert np.all(mesh.area[:mesh.nFx] == 1.0/mesh.nCy) # because our domain is a unit square
# and all y-faces have an "area" equal to the length in the x-dimension
assert np.all(mesh.area[mesh.nFx:] == 1.0/mesh.nCx)
print(
"The area of the x-faces is {xFaceArea} and the area of the y-faces is {yFaceArea}".format(
xFaceArea=mesh.area[0],
yFaceArea=mesh.area[mesh.nFx]
)
)
mesh.plotGrid(faces=True)
# On a non-uniform tensor mesh, the first mesh we defined, the cell volumes vary
# hx = np.r_[2., 1., 1., 2.] # cell widths in the x-direction
# hy = np.r_[2., 1., 1., 1., 2.] # cell widths in the y-direction
# mesh2D = Mesh.TensorMesh([hx,hy]) # construct a simple SimPEG mesh
plt.colorbar(mesh2D.plotImage(mesh2D.vol, grid=True)[0])
plt.title('Cell Volumes'); | notebooks/fundamentals/pixels_and_neighbors/mesh.ipynb | simpeg/tutorials | mit |
Grids and Putting things on a mesh
When storing and working with features of the mesh such as cell volumes, face areas, in a linear algebra sense, it is useful to think of them as vectors... so the way we unwrap is super important.
Most importantly we want some compatibility with <a href="https://en.wikipedia.org/wiki/Vectorization_(mathematics)#Compatibility_with_Kronecker_products">Kronecker products</a> as we will see later! This actually leads to us thinking about unwrapping our vectors column first. This column major ordering is inspired by linear algebra conventions which are the standard in Matlab, Fortran, Julia, but sadly not Python. To make your life a bit easier, you can use our MakeVector mkvc function from Utils. | from SimPEG.Utils import mkvc
mesh = Mesh.TensorMesh([3,4])
vec = np.arange(mesh.nC)
row_major = vec.reshape(mesh.vnC, order='C')
print('Row major ordering (standard python)')
print(row_major)
col_major = vec.reshape(mesh.vnC, order='F')
print('\nColumn major ordering (what we want!)')
print(col_major)
# mkvc unwraps using column major ordering, so we expect
assert np.all(mkvc(col_major) == vec)
print('\nWe get back the expected vector using mkvc: {vec}'.format(vec=mkvc(col_major))) | notebooks/fundamentals/pixels_and_neighbors/mesh.ipynb | simpeg/tutorials | mit |
Grids on the Mesh
When defining where things are located, we need the spatial locations of where we are discretizing different aspects of the mesh. A SimPEG Mesh has several grids. In particular, here it is handy to look at the
- Cell centered grid: mesh.gridCC
- x-Face grid: mesh.gridFx
- y-Face grid: mesh.gridFy | # gridCC
"The cell centered grid is {gridCCshape0} x {gridCCshape1} since we have {nC} cells in the mesh and it is {dim} dimensions".format(
gridCCshape0=mesh.gridCC.shape[0],
gridCCshape1=mesh.gridCC.shape[1],
nC=mesh.nC,
dim=mesh.dim
)
# The first column is the x-locations, and the second the y-locations
mesh.plotGrid()
plt.plot(mesh.gridCC[:,0], mesh.gridCC[:,1],'ro')
# gridFx
"Similarly, the x-Face grid is {gridFxshape0} x {gridFxshape1} since we have {nFx} x-faces in the mesh and it is {dim} dimensions".format(
gridFxshape0=mesh.gridFx.shape[0],
gridFxshape1=mesh.gridFx.shape[1],
nFx=mesh.nFx,
dim=mesh.dim
)
mesh.plotGrid()
plt.plot(mesh.gridCC[:,0], mesh.gridCC[:,1],'ro')
plt.plot(mesh.gridFx[:,0], mesh.gridFx[:,1],'g>') | notebooks/fundamentals/pixels_and_neighbors/mesh.ipynb | simpeg/tutorials | mit |
Putting a Model on a Mesh
In index.ipynb, we constructed a model of a block in a whole-space, here we revisit it having defined the elements of the mesh we are using. | mesh = Mesh.TensorMesh([100, 80]) # setup a mesh on which to solve
# model parameters
sigma_background = 1. # Conductivity of the background, S/m
sigma_block = 10. # Conductivity of the block, S/m
# add a block to our model
x_block = np.r_[0.4, 0.6]
y_block = np.r_[0.4, 0.6]
# assign them on the mesh
sigma = sigma_background * np.ones(mesh.nC) # create a physical property model
block_indices = ((mesh.gridCC[:,0] >= x_block[0]) & # left boundary
(mesh.gridCC[:,0] <= x_block[1]) & # right boudary
(mesh.gridCC[:,1] >= y_block[0]) & # bottom boundary
(mesh.gridCC[:,1] <= y_block[1])) # top boundary
# add the block to the physical property model
sigma[block_indices] = sigma_block
# plot it!
plt.colorbar(mesh.plotImage(sigma)[0])
plt.title('electrical conductivity, $\sigma$') | notebooks/fundamentals/pixels_and_neighbors/mesh.ipynb | simpeg/tutorials | mit |
世间真理42,以及 | 2 ** 100 | Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb | Wx1ng/Python4DataScience.CH | cc0-1.0 |
超大整数,或者试试 | "The answer to life,the universe,and everything is ?" | Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb | Wx1ng/Python4DataScience.CH | cc0-1.0 |
字符串。
用print打印任意我们想要的内容:
(一个对象在REPL中直接回车和被print分别输出的是他的__repr__和__str__方法对应的字符串) | print "Scala|Python|C"
print 42
print repr(42),str(42) | Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb | Wx1ng/Python4DataScience.CH | cc0-1.0 |
但是如果需要用户在电脑上输入一些字符怎么办?反复输入和打印字符串也并不方便。
Keep your code DRY (Don't Repeat Yourself) | lang = "Scala|Python|C"
print lang | Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb | Wx1ng/Python4DataScience.CH | cc0-1.0 |
如果需要标识注释,请以# 符号开始一段语句(这与大部分脚本语言和unix-shell语言一样)。从# 开始直到一行结束的内容都是注释。 | #Skip these comments.
print "These lines can be run."
print '''
Whatever.
''' | Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb | Wx1ng/Python4DataScience.CH | cc0-1.0 |
2 Python变量入门
2.0 Python变量的一些概念
赋值时创建变量本身,绑定名字
动态类型
强类型
可变类型与不可变类型
2.1 Python变量介绍
通常用等号(=)用来给变量赋值。等号(=)运算符左边是一个变量名,等号(=)运算符右边是存储在变量中的值或者一个复合的表达式。
试试在python shell里键入以下内容,每打一行摁下Enter键: | a = 42
b = 42*3
print type(a)
print id(b)
print a*b
b = "Hello,world!"
print type(b)
print id(b)
print b * 2
print b + b
help(id)
#print dir(a),'\n'*2,dir(b)
print isinstance(a,int) | Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb | Wx1ng/Python4DataScience.CH | cc0-1.0 |
2.2 Python变量赋值与操作
多变量赋值(不推荐): | x = y = z = 42
print x,y,z | Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb | Wx1ng/Python4DataScience.CH | cc0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.