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=N... | 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... | # 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 mea... | _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.ge... | _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", "ave... | _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.
Sec... | # 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)
# {
# ... | _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)... | _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_ei... | _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 d... | 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 = meas... | _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,
... | _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++) * *(... | _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) s... | _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);
# ... | _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 bu... | 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_... | _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, v... | _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="... | 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 f... | 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 the... | 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(laye... | 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... | # 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*... | 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 g... | 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, inclu... | 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 d... | 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 inadver... | 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_mea... | 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.T... | 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 hav... | 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 retu... | 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):
... | 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.f... | 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... | ## 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 exper... | 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$ st... | # 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(anni... | 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... | 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 s... | 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
... | 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... | 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))... | 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|
--|--|--|--|--|--|--|----|----|------|----|-------|-... | 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(n... | 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))
a... | 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... | 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 molec... | 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)
m... | 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])
fo... | 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="... | !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.u... | 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 num... | 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 = en... | 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="ht... | # 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... | 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.
... | 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 = e... | 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)
# Ba... | 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.
... | 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',
... | 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_li... | 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_p... | 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 a... | # 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 extend... | 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... | # 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}.").for... | 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 ... | 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... | 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 unwr... | 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-locat... | 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 = sigm... | 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.