markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
当然你也可以为多个对象指定多个变量,例如:
x,y,z = "So long","and thanks for all","the fish" print x,y,z
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
赋值的语法糖(Syntax Sugar):
x,y = "So long",42 x,y = y,x print x print y
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
Python同样拥有增量赋值方法:
a = 42 a += 1 print a a -= 1 a *= 2 print a
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
类似的能够赋值的操作符还有很多,包括: *= 自乘 /= 自除 %= 自取模 **= 自乘方 <<= 自左移位 >>= 自右移位 &= 自按位与 ^= 自按位异或 等等。 注意:Python不支持x++ 或者 --x 这类操作。 2.3 Python数值类型 int: 42 126 -680 -0x92 bool: True False float: 3.1415926 -90.00 6.022e23 complex: 6.23+1.5j -1.23-875j 0+1j type: 判断类型 isinstance: 判断属于特定类型(推荐)
a,b,c,d = 42,True,3.1415926,6.23+1.5j print type(a),type(b),type(c),type(d) print isinstance(a,int),isinstance(b,(float,int)),\ isinstance(c,float),isinstance(d,(int,bool)) # 可以分别取得复数的实部和虚部 print d.real print d.imag
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
工业级的计算器: 基础操作符: + - * / // % ** 比较操作符: < <= > >= == !=
d = 6.23+1.5j e = 0+1j print d+e,d-e,d*e print 7*3,7**2 # x**y 返回x的y次幂 print 8%3,float(10)/3,10.0/3,10//3 print 1==2, 1 != 2 #==表示判断是否相等 != 表示不相等 print 7%2 #返回除法的余数 print 1<42<100
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
是时候展现真正的除法了:
print 7/4 from __future__ import division print 7/4
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
普通floor除法:
print 7//4
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
布尔值:
print not True print not False print 40 < 42 <= 100 print not 40 > 30 print 40 > 30 and 40 < 42 <= 100 print 40 < 30 or 40 < 42 <=100
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
2.4 Python字符串类型 字符串的长度len与切片:
c = "Hello world" print len(c) print c[0],c[1:3] print c[-1],c[:] print c[::2],c[::-1]
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
复杂切片操作:[start:end:step]
c = "Hello world" print c[::-1] #翻转字符串 print c[:] #原样复制字符串 print c[::2] #隔一个取一个 print c[:8] #前八个字母 print c[:8:2] #前八个字母,每两个取一个
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
复制:
c = "Hello world" d = c[:] #复制字符串,赋值给d del c #删除原字符串 print d #d 字符串依然可用 e = d[0:4] print e #新构造一个截取d字符串部分所组成的串 f = e print id(f) print id(e) del e print id(f),f #仍然可用
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
加号(+)用于字符串连接运算,星号(*)用来重复字符串。
teststr,stringback="Clojure is","cool" print '-'*20 print teststr+stringback print teststr*3 print '-'*20
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
美化打印:
pystr,pystring="Clojure is","cool" print '-'*20 print pystr,pystring print '-'*20 print pystr+'\t'+pystring print '-'*20 pystr = "Clojure" pystring = "cool" yastr = "LISP" yastring = "wonderful " print('Python\'s Format I : {0} is {1}'.format(pystr,pystring)) print 'Python\'s Format II: {language} is {description}'.\ ...
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
字符串复杂效果举例:
for i in range(0,5)+range(2,8)+range(3,12)+[2,2]: print' '*(40-2*i-i//2)+'*'*(4*i+1+i)
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
尾部换行\:
"A:What's your favorite language?\ B:C++."
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
\t:水平制表符:
print "A:What’s your favorite language?\nB:C++" print "A:What’s your favorite language?\tB:C++"
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
注意其他的转义字符(反斜线+字符):
print 'What\'s your favorite language?' print "What's your favorite language?" print "What\"s your favorite language?\\"
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
其他操作 —— Join,Split,Strip, Upper, Lower
s = "a\tb\tc\td" print s l = s.split('\t') print l snew = ','.join(l) print snew line = '\t Blabla \t \n' print line.strip() print line.lstrip() print line.rstrip() salpha = 'Abcdefg' print salpha.upper() print salpha.lower() #isupper islower isdigit isalpha
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
更多操作: 查阅dir('s') 查阅codecs 查阅re(regexp,正则表达式) 2.5 初识Python可变类型(Mutables) 字符串(string):不可变 字节数组(bytearray):可变
s = "string" print type(s) s[3] = "o" s = "String" sba = bytearray(s) sba[3] = "o" print sba
Series_0_Python_Tutorials/S0EP1_Python_Basics.ipynb
Wx1ng/Python4DataScience.CH
cc0-1.0
This FASTA file shown above has just one sequence in it. As we saw in the first example above, it's also possible for one FASTA file to contain multiple sequences. These are sometimes called multi-FASTA files. When you write code to interpret FASTA files, it's a good idea to always allow for the possibility that the...
def parse_fasta(fh): fa = {} current_short_name = None # Part 1: compile list of lines per sequence for ln in fh: if ln[0] == '>': # new name line; remember current sequence's short name long_name = ln[1:].rstrip() current_short_name = long_name.split()[0] ...
notebooks/FASTA.ipynb
BenLangmead/comp-genomics-class
gpl-2.0
The first part accumulates a list of strings (one per line) for each sequence. The second part joins those lines together so that we end up with one long string per sequence. Why divide it up this way? Mainly to avoid the poor performance of repeatedly concatenating (immutable) Python strings. I'll test it by runnin...
from io import StringIO fasta_example = StringIO( '''>sequence1_short_name with optional additional info after whitespace ACATCACCCCATAAACAAATAGGTTTGGTCCTAGCCTTTCTATTAGCTCTTAGTAAGATTACACATGCAA GCATCCCCGTTCCAGTGAGTTCACCCTCTAAATCACCACGATCAAAAGGAACAAGCATCAAGCACGCAGC AATGCAGCTCAAAACGCTTAGCCTAGCCACACCCCCACGGGAAACAGCAGTGAT >...
notebooks/FASTA.ipynb
BenLangmead/comp-genomics-class
gpl-2.0
Note that only the short names survive. This is usually fine, but it's not hard to modify the function so that information relating short names to long names is also retained. Indexed FASTA Say you have one or more big FASTA files (e.g. the entire human reference genome) and you'd like to access those files "randomly,...
parsed_fa['sequence2_short_name'][100:130]
notebooks/FASTA.ipynb
BenLangmead/comp-genomics-class
gpl-2.0
Accessing a substring in this way is very fast and simple. The downside is that you've stored all of the sequences in memory. If the FASTA files are really big, this takes lots of valuable memory. This may or may not be a good trade. An alternative is to load only the portions of the FASTA files that you need, when ...
def index_fasta(fh): index = [] current_short_name = None current_byte_offset, running_seq_length, running_byte_offset = 0, 0, 0 line_length_including_ws, line_length_excluding_ws = 0, 0 for ln in fh: ln_stripped = ln.rstrip() running_byte_offset += len(ln) if ln[0] == '>': ...
notebooks/FASTA.ipynb
BenLangmead/comp-genomics-class
gpl-2.0
Here we use it to index a small multi-FASTA file. We print out the index at the end.
fasta_example = StringIO( '''>sequence1_short_name with optional additional info after whitespace ACATCACCCCATAAACAAATAGGTTTGGTCCTAGCCTTTCTATTAGCTCTTAGTAAGATTACACATGCAA GCATCCCCGTTCCAGTGAGTTCACCCTCTAAATCACCACGATCAAAAGGAACAAGCATCAAGCACGCAGC AATGCAGCTCAAAACGCTTAGCCTAGCCACACCCCCACGGGAAACAGCAGTGAT >sequence2_short_name wit...
notebooks/FASTA.ipynb
BenLangmead/comp-genomics-class
gpl-2.0
What do the fields in those two records mean? Take the first record: ('sequence1_short_name', 194, 69, 70, 71). The fields from left to right are (1) the short name, (2) the length (in nucleotides), (3) the byte offset in the FASTA file of the first nucleotide of the sequence, (4) the maximum number of nucleotides pe...
import re class FastaOOB(Exception): """ Out-of-bounds exception for FASTA sequences """ def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class FastaIndexed(object): """ Encapsulates a set of indexed FASTA files. Does not load the FAST...
notebooks/FASTA.ipynb
BenLangmead/comp-genomics-class
gpl-2.0
Here's an example of how to use the class defined above.
# first we'll write a new FASTA file with open('tmp.fa', 'w') as fh: fh.write('''>sequence1_short_name with optional additional info after whitespace ACATCACCCCATAAACAAATAGGTTTGGTCCTAGCCTTTCTATTAGCTCTTAGTAAGATTACACATGCAA GCATCCCCGTTCCAGTGAGTTCACCCTCTAAATCACCACGATCAAAAGGAACAAGCATCAAGCACGCAGC AATGCAGCTCAAAACGCTTAGCCT...
notebooks/FASTA.ipynb
BenLangmead/comp-genomics-class
gpl-2.0
Questions: (Note: to answer the following, open Google Earth and enter Betasso Preserve in the search bar. Zoom out a bit to view the area around Betasso) (1) Use a screen shot to place a copy of this image in your lab document. Label Boulder Creek Canyon and draw an arrow to show its flow direction. (2) Indicate and l...
def slope_gradient(z): """ Calculate absolute slope gradient elevation array. """ x, y = np.gradient(z) #slope = (np.pi/2. - np.arctan(np.sqrt(x*x + y*y))) slope = np.sqrt(x*x + y*y) return slope sb = slope_gradient(zb)
dem_processing_with_gdal_python.ipynb
cmshobe/dem_analysis_with_gdal
mit
Let's see what it looks like:
plt.imshow(sb, vmin=0.0, vmax=1.0, cmap='pink') print np.median(sb)
dem_processing_with_gdal_python.ipynb
cmshobe/dem_analysis_with_gdal
mit
We can make a histogram (frequency diagram) of aspect. Here 0 degrees is east-facing, 90 is north-facing, 180 is west-facing, and 270 is south-facing.
abdeg = (180./np.pi)*ab # convert to degrees n, bins, patches = plt.hist(abdeg.flatten(), 50, normed=1, facecolor='green', alpha=0.75)
dem_processing_with_gdal_python.ipynb
cmshobe/dem_analysis_with_gdal
mit
Using NLTK to extract Unigram and Bigram Ref: Chen Sun, Chuang Gan and Ram Nevatia, Automatic Concept Discovery from Parallel Text and Visual Corpora. ICCV 2015 <img src="files/iccv_paper_concepts.png">
from nltk.util import ngrams sentence = 'A black-dog and a spotted dog are fighting.' n = 2 sixgrams = ngrams(sentence.split(), n) for grams in sixgrams: print grams
text_features.ipynb
surenkum/eecs_542
gpl-3.0
Some of the bigrams are obviously not relevant. So we tokenize and exclude stop words to get some relevant classes.
from nltk.corpus import stopwords from nltk.tokenize import wordpunct_tokenize stop_words = set(stopwords.words('english')) stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}','-']) # remove it if you need punctuation list_of_words = [i.lower() for i in wordpunct_tokenize(sentence...
text_features.ipynb
surenkum/eecs_542
gpl-3.0
Using Scikit-Learn to explore some text datasets 20 Newsgroup dataset The 20 Newsgroups data set is a collection of approximately 20,000 newsgroup documents, partitioned (nearly) evenly across 20 different newsgroups. This dataset is often used for text classification and text clustering. Some of the newsgroups are ver...
%run fetch_data.py twenty_newsgroups from sklearn.datasets import load_files from sklearn.feature_extraction.text import TfidfVectorizer # Tf IDF feature extraction from sklearn.feature_extraction.text import CountVectorizer # Count and vectorize text feature # Load the text data categories = [ 'alt.atheism', ...
text_features.ipynb
surenkum/eecs_542
gpl-3.0
Extracting features Lets extract vector counts to convert text to a vector.
count_vect = CountVectorizer(min_df=2) X_train_counts = count_vect.fit_transform(twenty_train_small.data) print X_train_counts.shape
text_features.ipynb
surenkum/eecs_542
gpl-3.0
Lets extract TF-IDF features from text data. min_df option is to put a lower bound to ignore terms that have a low document frequency.
# Extract features # Turn the text documents into vectors of word frequencies with tf-idf weighting vectorizer = TfidfVectorizer(min_df=2) X_train = vectorizer.fit_transform(twenty_train_small.data) y_train = twenty_train_small.target print type(X_train) print X_train.shape
text_features.ipynb
surenkum/eecs_542
gpl-3.0
As observed, X_train is a scipy sparse matrix consisting of 2034 rows (number of text files) and 17566 different features (unique words)
print type(vectorizer.vocabulary_) # Type of vocabulary print len(vectorizer.vocabulary_) # Length of vocabulary print vectorizer.get_feature_names()[:10] # Print first 10 elements of dictionary print vectorizer.get_feature_names()[-10:] # Print last 10 elements of dictionary
text_features.ipynb
surenkum/eecs_542
gpl-3.0
Visualizing Feature Space Obviously, its hard to make any sense of such high-dimensional feature space. A good technique to visualize such data is to project it to lower dimensions using PCA and then visualizing low-dimensional splace.
from sklearn.decomposition import TruncatedSVD X_train_pca = TruncatedSVD(n_components=2).fit_transform(X_train) from itertools import cycle colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] for i, c in zip(np.unique(y_train), cycle(colors)): plt.scatter(X_train_pca[y_train == i, 0], X_train_pca[y_train ...
text_features.ipynb
surenkum/eecs_542
gpl-3.0
Note: When we have so many features and so few data points, the solution can become highly numerically unstable, which can sometimes lead to strange unpredictable results. Thus, rather than using no regularization, we will introduce a tiny amount of regularization (l2_penalty=1e-5) to make the solution numerically sta...
poly1_data = polynomial_sframe(sales['sqft_living'], 1) features = poly1_data.column_names() poly1_data['price'] = sales['price'] # add price to the data since it's the target model1 = graphlab.linear_regression.create(poly1_data, target = 'price', features = features, l2_penalty=l2_small_penalty, validation_set = Non...
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Next, fit a 15th degree polynomial on set_1, set_2, set_3, and set_4, using 'sqft_living' to predict prices. Print the weights and make a plot of the resulting model. Hint: When calling graphlab.linear_regression.create(), use the same L2 penalty as before (i.e. l2_small_penalty). Also, make sure GraphLab Create doesn...
def print_coefficients(data_set, l2_penalty): ps = polynomial_sframe(data_set['sqft_living'], 15) my_features = ps.column_names() ps['price'] = data_set['price'] model = graphlab.linear_regression.create(ps, target = 'price', features = my_features, validation_set = None, verbose = False, l2_penalty=l2_...
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
The four curves should differ from one another a lot, as should the coefficients you learned. QUIZ QUESTION: For the models learned in each of these training sets, what are the smallest and largest values you learned for the coefficient of feature power_1? (For the purpose of answering this question, negative numbers...
smallest=-759.251854206 largest=1247.59034572
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Ridge regression comes to rescue Generally, whenever we see weights change so much in response to change in data, we believe the variance of our estimate to be large. Ridge regression aims to address this issue by penalizing "large" weights. (Weights of model15 looked quite small, but they are not that small because 's...
l2_penalty = 1e5 for i in [set_1, set_2, set_3, set_4]: print_coefficients(i, l2_penalty)
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
These curves should vary a lot less, now that you applied a high degree of regularization. QUIZ QUESTION: For the models learned with the high level of regularization in each of these training sets, what are the smallest and largest values you learned for the coefficient of feature power_1? (For the purpose of answeri...
smallest=1.91040938244 largest=2.58738875673
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Once the data is shuffled, we divide it into equal segments. Each segment should receive n/k elements, where n is the number of observations in the training set and k is the number of segments. Since the segment 0 starts at index 0 and contains n/k elements, it ends at index (n/k)-1. The segment 1 starts where the segm...
n = len(train_valid_shuffled) print n - 7757 k = 10 # 10-fold cross-validation for i in xrange(k): start = (n*i)/k end = (n*(i+1))/k-1 print i, (start, end)
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Now let us extract individual segments with array slicing. Consider the scenario where we group the houses in the train_valid_shuffled dataframe into k=10 segments of roughly equal size, with starting and ending indices computed as above. Extract the fourth segment (segment 3) and assign it to a variable called validat...
validation4 = train_valid_shuffled[5818:7757]
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Extract the remainder of the data after excluding fourth segment (segment 3) and assign the subset to train4.
p1 = train_valid_shuffled[0:5817] p2 = train_valid_shuffled[n-11639:n] train4 = p1.append(p2)
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Now we are ready to implement k-fold cross-validation. Write a function that computes k validation errors by designating each of the k segments as the validation set. It accepts as parameters (i) k, (ii) l2_penalty, (iii) dataframe, (iv) name of output column (e.g. price) and (v) list of feature names. The function ret...
def k_fold_cross_validation(k, l2_penalty, data, features_list): n = len(data) rss_k = list() for i in xrange(k): start = (n*i)/k end = (n*(i+1))/k-1 validation_set = data[start:end + 1] training_set = data[end + 1:n].append(data[0:start]) model = graphlab.linear_regr...
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Once we have a function to compute the average validation error for a model, we can write a loop to find the model that minimizes the average validation error. Write a loop that does the following: * We will again be aiming to fit a 15th-order polynomial model using the sqft_living input * For l2_penalty in [10^1, 10^1...
import numpy as np ps = polynomial_sframe(train_valid_shuffled['sqft_living'], 15) my_features = ps.column_names() ps['price'] = train_valid_shuffled['price'] k=10 result = dict() for l2_penalty in np.logspace(1, 7, num=13): result[l2_penalty] = k_fold_cross_validation(k, l2_penalty, ps, my_features)
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
QUIZ QUESTIONS: What is the best value for the L2 penalty according to 10-fold validation?
best_penalty = min(result, key=result.get) print "the best value for the L2 penalty according to 10-fold validation:", best_penalty
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
You may find it useful to plot the k-fold cross-validation errors you have obtained to better understand the behavior of the method.
# Plot the l2_penalty values in the x axis and the cross-validation error in the y axis. # Using plt.xscale('log') will make your plot more intuitive.
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Once you found the best value for the L2 penalty using cross-validation, it is important to retrain a final model on all of the training data using this value of l2_penalty. This way, your final model will be trained on the entire dataset. QUIZ QUESTION: Using the best L2 penalty found above, train a model using all t...
ps = polynomial_sframe(train_valid['sqft_living'], 15) features = ps.column_names() ps['price'] = train_valid['price'] # add price to the data since it's the target best_model = graphlab.linear_regression.create(ps, target = 'price', features = features, l2_penalty=best_penalty, validation_set = None) predictions = b...
course-2-regression/notebooks/week-4-ridge-regression-assignment-1-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Working with Text Data <img src="figures/bag_of_words.svg" width=100%>
import pandas as pd import os data = pd.read_csv(os.path.join("data", "train.csv")) len(data) data y_train = np.array(data.Insult) y_train text_train = data.Comment.tolist() text_train[6] data_test = pd.read_csv(os.path.join("data", "test_with_solutions.csv")) text_test, y_test = data_test.Comment.tolist(), np...
10 - Working With Text Data.ipynb
amueller/sklearn_workshop
bsd-2-clause
Exercises Create a pipeine using the count vectorizer and SVM (see 07). Train and score using the pipeline. Vary the n_gram_range in the count vectorizer, visualize the changed coefficients. Grid search the C in the LinearSVC using the pipeline. Grid search the C in the LinearSVC together with the n_gram_range (try (1...
# %load solutions/text_pipeline.py
10 - Working With Text Data.ipynb
amueller/sklearn_workshop
bsd-2-clause
We can also plot the spectral fluxes of energy.
ebud = [ m.get_diagnostic('APEgenspec').sum(axis=0), m.get_diagnostic('APEflux').sum(axis=0), m.get_diagnostic('KEflux').sum(axis=0), -m.rek*m.del2*m.get_diagnostic('KEspec')[1].sum(axis=0)*m.M**2 ] ebud.append(-np.vstack(ebud).sum(axis=0)) ebud_labels = ['APE gen','APE flux','KE flux','Diss....
docs/examples/two-layer.ipynb
rabernat/pyqg
mit
For this notebook we will create a toy "Boron nitride" tight binding:
# First, we create the geometry BN = sisl.geom.graphene(atoms=["B", "N"]) # Create a hamiltonian with different on-site terms H = sisl.Hamiltonian(BN) H[0, 0] = 2 H[1, 1] = -2 H[0, 1] = -2.7 H[1, 0] = -2.7 H[0, 1, (-1, 0)] = -2.7 H[0, 1, (0, -1)] = -2.7 H[1, 0, (1, 0)] = -2.7 H[1, 0, (0, 1)] = -2.7
docs/visualization/viz_module/showcase/FatbandsPlot.ipynb
zerothi/sisl
mpl-2.0
Note that we could have obtained this hamiltonian from any other source. Then we generate a path for the band structure:
band = sisl.BandStructure(H, [[0., 0.], [2./3, 1./3], [1./2, 1./2], [1., 1.]], 301, [r'$\Gamma$', 'K', 'M', r'$\Gamma$'])
docs/visualization/viz_module/showcase/FatbandsPlot.ipynb
zerothi/sisl
mpl-2.0
And finally we just ask for the fatbands plot:
fatbands = band.plot.fatbands() fatbands
docs/visualization/viz_module/showcase/FatbandsPlot.ipynb
zerothi/sisl
mpl-2.0
We only see the bands here, but this is a fatbands plot, and it is ready to accept your requests on what to draw! Requesting specific weights The fatbands that the plot draws are controlled by the groups setting.
print(fatbands.get_param("groups").help)
docs/visualization/viz_module/showcase/FatbandsPlot.ipynb
zerothi/sisl
mpl-2.0
This setting works exactly like the requests setting in PdosPlot, which is documented here. Therefore we won't give an extended description of it, but just quickly show that you can autogenerate the groups:
fatbands.split_groups(on="species")
docs/visualization/viz_module/showcase/FatbandsPlot.ipynb
zerothi/sisl
mpl-2.0
Or write them yourself if you want the maximum flexibility:
fatbands.update_settings(groups=[ {"species": "N", "color": "blue", "name": "Nitrogen"}, {"species": "B", "color": "red", "name": "Boron"} ])
docs/visualization/viz_module/showcase/FatbandsPlot.ipynb
zerothi/sisl
mpl-2.0
Scaling fatbands The visual appeal of fatbands depends a lot on the size of your plot, therefore there's one global scale setting that scales all fatbands at the same time:
fatbands.update_settings(scale=2)
docs/visualization/viz_module/showcase/FatbandsPlot.ipynb
zerothi/sisl
mpl-2.0
You can also use the scale_fatbands method, which additionally lets you choose if you want to rescale from the current size or just set the value of scale:
fatbands.scale_fatbands(0.5, from_current=True)
docs/visualization/viz_module/showcase/FatbandsPlot.ipynb
zerothi/sisl
mpl-2.0
Use BandsPlot settings All settings of BandsPlot work as well for FatbandsPlot. Even spin texture! We hope you enjoyed what you learned! This next cell is just to create the thumbnail for the notebook in the docs
thumbnail_plot = fatbands if thumbnail_plot: thumbnail_plot.show("png")
docs/visualization/viz_module/showcase/FatbandsPlot.ipynb
zerothi/sisl
mpl-2.0
<img src="image/Mean_Variance_Image.png" style="height: 75%;width: 75%; position: relative; right: 5%"> Problem 1 The first problem involves normalizing the features for your training and test data. Implement Min-Max scaling in the normalize_grayscale() function to a range of a=0.1 and b=0.9. After scaling, the values ...
# Problem 1 - Implement Min-Max scaling for grayscale image data def normalize_grayscale(image_data): """ Normalize the image data with Min-Max scaling to a range of [0.1, 0.9] :param image_data: The image data to be normalized :return: Normalized image data """ # TODO: Implement Min-Max scaling...
intro-to-tensorflow/intro_to_tensorflow.ipynb
rahulkgup/deep-learning-foundation
mit
<img src="image/Learn_Rate_Tune_Image.png" style="height: 70%;width: 70%"> Problem 3 Below are 2 parameter configurations for training the neural network. In each configuration, one of the parameters has multiple options. For each configuration, choose the option that gives the best acccuracy. Parameter configurations:...
# Change if you have memory restrictions batch_size = 128 # TODO: Find the best parameters for each configuration epochs = 5 learning_rate = 0.02 ### DON'T MODIFY ANYTHING BELOW ### # Gradient Descent optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) # The accuracy measured against th...
intro-to-tensorflow/intro_to_tensorflow.ipynb
rahulkgup/deep-learning-foundation
mit
We need to create a rotation matrix $\boldsymbol{R}$, which we will do via computation of the eigenvectors (eigenvectors are covered in the next lecture). The details are not so important here; we just need an orthogonal matrix. Computing the eigenvectors of $\boldsymbol{A}$ and checking that the eigenvectors are ortho...
# Compute eigenvectors to generate a set of orthonormal vector evalues, evectors = np.linalg.eig(A) # Verify that eigenvectors R[i] are orthogonal (see Lecture 8 notebook) import itertools pairs = itertools.combinations_with_replacement(range(np.size(evectors, 0)), 2) for p in pairs: e0, e1 = p[0], p[1] print(...
Lecture09.ipynb
garth-wells/IA-maths-Jupyter
mit
We have verified that the eigenvectors form an orthonormal set, and hence can be used to construct a rotation transformation matrix $\boldsymbol{R}$. For reasons that will become apparent later, we choose $\boldsymbol{R}$ to be a matrix whose rows are the eigenvectors of $\boldsymbol{A}$:
R = evectors.T
Lecture09.ipynb
garth-wells/IA-maths-Jupyter
mit
We now apply the transformation defined by $\boldsymbol{R}$ to $\boldsymbol{A}$:
Ap = (R).dot(A.dot(R.T)) print(Ap)
Lecture09.ipynb
garth-wells/IA-maths-Jupyter
mit
Note that the transformed matrix is diagonal. We will investigate this further in following lectures. We can reverse the transformation by exploiting the fact that $\boldsymbol{R}$ is an orthogonal matrix:
print((R.T).dot(Ap.dot(R)))
Lecture09.ipynb
garth-wells/IA-maths-Jupyter
mit
Introduction This is an Earth Engine <> TensorFlow demonstration notebook. Specifically, this notebook shows: Exporting training/testing data from Earth Engine in TFRecord format. Preparing the data for use in a TensorFlow model. Training and validating a simple model (Keras Sequential neural network) in TensorFlow. ...
!pip install earthengine-api
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Authentication To read/write from a Google Cloud Storage bucket to which you have access, it's necessary to authenticate (as yourself). You'll also need to authenticate as yourself with Earth Engine, so that you'll have access to your scripts, assets, etc. Authenticate to Colab and Cloud Identify yourself to Google Cl...
from google.colab import auth auth.authenticate_user()
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Authenticate to Earth Engine Authenticate to Earth Engine the same way you did to the Colab notebook. Specifically, run the code to display a link to a permissions page. This gives you access to your Earth Engine account. Copy the code from the Earth Engine permissions page back into the notebook and press return to...
!earthengine authenticate
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Initialize and test the software setup Test the Earth Engine installation
# Import the Earth Engine API and initialize it. import ee ee.Initialize() # Test the earthengine command by getting help on upload. !earthengine upload image -h
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Test the TensorFlow installation The default public runtime already has the tensorflow libraries we need installed. Before any operations from the TensorFlow API are used, import TensorFlow and enable eager execution. This provides an imperative interface that can help with debugging. See the TensorFlow eager execut...
import tensorflow as tf tf.enable_eager_execution() print(tf.__version__)
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Test the Folium installation The default public runtime already has the Folium library we will use for visualization. Import the library, check the version, and define the URL where Folium will look for Earth Engine generated map tiles.
import folium print(folium.__version__) # Define the URL format used for Earth Engine generated map tiles. EE_TILES = 'https://earthengine.googleapis.com/map/{mapid}/{{z}}/{{x}}/{{y}}?token={token}'
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Get Training and Testing data from Earth Engine To get data for a classification model of three classes (bare, vegetation, water), we need labels and the value of predictor variables for each labeled example. We've already generated some labels in Earth Engine. Specifically, these are visually interpreted points labe...
# Use these bands for prediction. bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'] # Use Landsat 8 surface reflectance data. l8sr = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR') # Cloud masking function. def maskL8sr(image): cloudShadowBitMask = ee.Number(2).pow(3).int() cloudsBitMask = ee.Number(2).pow(5).int() qa =...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Add pixel values of the composite to labeled points. Some training labels have already been collected for you. Load the labeled points from an existing Earth Engine asset. Each point in this table has a property called landcover that stores the label, encoded as an integer. Here we overlay the points on imagery to ...
# Change the following two lines to use your own training data. labels = ee.FeatureCollection('projects/google/demo_landcover_labels') label = 'landcover' # Sample the image at the points and add a random column. sample = image.sampleRegions( collection=labels, properties=[label], scale=30).randomColumn() # Partiti...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Export the training and testing data Now that there's training and testing data in Earth Engine and you've inspected a couple examples to ensure that the information you need is present, it's time to materialize the datasets in a place where the TensorFlow model has access to them. You can do that by exporting the tra...
# REPLACE WITH YOUR BUCKET! outputBucket = 'ee-docs-demos' # Make sure the bucket exists. print('Found Cloud Storage bucket.' if tf.gfile.Exists('gs://' + outputBucket) else 'Output Cloud Storage bucket does not exist.')
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Once you've verified the existence of the intended output bucket, run the exports.
# Names for output files. trainFilePrefix = 'Training_demo_' testFilePrefix = 'Testing_demo_' # This is list of all the properties we want to export. featureNames = list(bands) featureNames.append(label) # Create the tasks. trainingTask = ee.batch.Export.table.toCloudStorage( collection=training, description='Tra...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Monitor task progress You can see all your Earth Engine tasks by listing them. It's also useful to repeatedly poll a task so you know when it's done. Here we can do that because this is a relatively quick export. Be careful when doing this with large exports because it will block the notebook from running other cell...
# Print all tasks. print(ee.batch.Task.list()) # Poll the training task until it's done. import time while trainingTask.active(): print('Polling for task (id: {}).'.format(trainingTask.id)) time.sleep(5) print('Done with training export.')
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Check existence of the exported files If you've seen the status of the export tasks change to COMPLETED, then check for the existince of the files in the output Cloud Storage bucket.
fileNameSuffix = 'ee_export.tfrecord.gz' trainFilePath = 'gs://' + outputBucket + '/' + trainFilePrefix + fileNameSuffix testFilePath = 'gs://' + outputBucket + '/' + testFilePrefix + fileNameSuffix print('Found training file.' if tf.gfile.Exists(trainFilePath) else 'No training file found.') print('Found testing...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Export the imagery You can also export imagery using TFRecord format. Specifically, export whatever imagery you want to be classified by the trained model into the output Cloud Storage bucket.
imageFilePrefix = 'Image_pixel_demo_' # Specify patch and file dimensions. imageExportFormatOptions = { 'patchDimensions': [256, 256], 'maxFileSize': 104857600, 'compressed': True } # Export imagery in this region. exportRegion = ee.Geometry.Rectangle([-122.7, 37.3, -121.8, 38.00]) # Setup the task. imageTask ...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Monitor task progress Before making predictions, we need the image export to finish, so block until it does. This might take a few minutes...
while imageTask.active(): print('Polling for task (id: {}).'.format(imageTask.id)) time.sleep(5) print('Done with image export.')
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Data preparation and pre-processing Read data from the TFRecord file into a tf.data.Dataset. Pre-process the dataset to get it into a suitable format for input to the model. Read into a tf.data.Dataset Here we are going to read a file in Cloud Storage into a tf.data.Dataset. (these TensorFlow docs explain more about ...
# Create a dataset from the TFRecord file in Cloud Storage. trainDataset = tf.data.TFRecordDataset(trainFilePath, compression_type='GZIP') # Print the first record to check. print(iter(trainDataset).next())
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Define the structure of your data For parsing the exported TFRecord files, featuresDict is a mapping between feature names (recall that featureNames contains the band and label names) and float32 tf.io.FixedLenFeature objects. This mapping is necessary for telling TensorFlow how to read data in a TFRecord file into te...
# List of fixed-length features, all of which are float32. columns = [ tf.io.FixedLenFeature(shape=[1], dtype=tf.float32) for k in featureNames ] # Dictionary with names as keys, features as values. featuresDict = dict(zip(featureNames, columns)) pprint(featuresDict)
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Parse the dataset Now we need to make a parsing function for the data in the TFRecord files. The data comes in flattened 2D arrays per record and we want to use the first part of the array for input to the model and the last element of the array as the class label. The parsing function reads data from a serialized Ex...
def parse_tfrecord(example_proto): """The parsing function. Read a serialized example into the structure defined by featuresDict. Args: example_proto: a serialized Example. Returns: A tuple of the predictors dictionary and the label, cast to an `int32`. """ parsed_features = tf.io.parse_single...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Note that each record of the parsed dataset contains a tuple. The first element of the tuple is a dictionary with bands for keys and the numeric value of the bands for values. The second element of the tuple is a class label. Create additional features Another thing we might want to do as part of the input process is...
def normalizedDifference(a, b): """Compute normalized difference of two inputs. Compute (a - b) / (a + b). If the denomenator is zero, add a small delta. Args: a: an input tensor with shape=[1] b: an input tensor with shape=[1] Returns: The normalized difference as a tensor. """ nd = (a - ...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Model setup The basic workflow for classification in TensorFlow is: Create the model. Train the model (i.e. fit()). Use the trained model for inference (i.e. predict()). Here we'll create a Sequential neural network model using Keras. This simple model is inspired by examples in: The TensorFlow Get Started tutorial...
from tensorflow import keras # How many classes there are in the model. nClasses = 3 # Add NDVI. inputDataset = parsedDataset.map(addNDVI) # Keras requires inputs as a tuple. Note that the inputs must be in the # right shape. Also note that to use the categorical_crossentropy loss, # the label needs to be turned i...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Check model accuracy on the test set Now that we have a trained model, we can evaluate it using the test dataset. To do that, read and prepare the test dataset in the same way as the training dataset. Here we specify a batch sie of 1 so that each example in the test set is used exactly once to compute model accuracy....
testDataset = ( tf.data.TFRecordDataset(testFilePath, compression_type='GZIP') .map(parse_tfrecord, num_parallel_calls=5) .map(addNDVI) .map(toTuple) .batch(1) ) model.evaluate(testDataset, steps=100)
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Use the trained model to classify an image from Earth Engine Now it's time to classify the image that was exported from Earth Engine. If the exported image is large, it will be split into multiple TFRecord files in its destination folder. There will also be a JSON sidecar file called "the mixer" that describes the fo...
# Get a list of all the files in the output bucket. filesList = !gsutil ls 'gs://'{outputBucket} # Get only the files generated by the image export. exportFilesList = [s for s in filesList if imageFilePrefix in s] # Get the list of image files and the JSON mixer file. imageFilesList = [] jsonFile = None for f in expor...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Read the JSON mixer file The mixer contains metadata and georeferencing information for the exported patches, each of which is in a different file. Read the mixer to get some information needed for prediction.
import json # Load the contents of the mixer file to a JSON object. jsonText = !gsutil cat {jsonFile} # Get a single string w/ newlines from the IPython.utils.text.SList mixer = json.loads(jsonText.nlstr) pprint(mixer)
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Read the image files into a dataset You can feed the list of files (imageFilesList) directly to the TFRecordDataset constructor to make a combined dataset on which to perform inference. The input needs to be preprocessed differently than the training and testing. Mainly, this is because the pixels are written into re...
# Get relevant info from the JSON mixer file. PATCH_WIDTH = mixer['patchDimensions'][0] PATCH_HEIGHT = mixer['patchDimensions'][1] PATCHES = mixer['totalPatches'] PATCH_DIMENSIONS_FLAT = [PATCH_WIDTH * PATCH_HEIGHT, 1] # Note that the tensors are in the shape of a patch, one patch for each band. imageColumns = [ tf....
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Generate predictions for the image pixels To get predictions in each pixel, run the image dataset through the trained model using model.predict(). Print the first prediction to see that the output is a list of the three class probabilities for each pixel. Running all predictions might take a while.
# Run prediction in batches, with as many steps as there are patches. predictions = model.predict(imageDataset, steps=PATCHES, verbose=1) # Note that the predictions come as a numpy array. Check the first one. print(predictions[0])
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Write the predictions to a TFRecord file Now that there's a list of class probabilities in predictions, it's time to write them back into a file, optionally including a class label which is simply the index of the maximum probability. We'll write directly from TensorFlow to a file in the output Cloud Storage bucket. I...
outputImageFile = 'gs://' + outputBucket + '/Classified_pixel_demo.TFRecord' print('Writing to file ' + outputImageFile) # Instantiate the writer. writer = tf.python_io.TFRecordWriter(outputImageFile) # Every patch-worth of predictions we'll dump an example into the output # file with a single feature that holds our ...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Upload the classifications to an Earth Engine asset Verify the existence of the predictions file At this stage, there should be a predictions TFRecord file sitting in the output Cloud Storage bucket. Use the gsutil command to verify that the predictions image (and associated mixer JSON) exist and have non-zero size.
!gsutil ls -l {outputImageFile}
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Upload the classified image to Earth Engine Upload the image to Earth Engine directly from the Cloud Storage bucket with the earthengine command. Provide both the image TFRecord file and the JSON file as arguments to earthengine upload.
# REPLACE WITH YOUR USERNAME: USER_NAME = 'nclinton' outputAssetID = 'users/' + USER_NAME + '/Classified_pixel_demo' print('Writing to ' + outputAssetID) # Start the upload. !earthengine upload image --asset_id={outputAssetID} {outputImageFile} {jsonFile}
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
View the ingested asset Display the vector of class probabilities as an RGB image with colors corresponding to the probability of bare, vegetation, water in a pixel. Also display the winning class using the same color palette.
predictionsImage = ee.Image(outputAssetID) predictionVis = { 'bands': 'prediction', 'min': 0, 'max': 2, 'palette': ['red', 'green', 'blue'] } probabilityVis = {'bands': ['bareProb', 'vegProb', 'waterProb']} predictionMapid = predictionsImage.getMapId(predictionVis) probabilityMapid = predictionsImage.getMapId...
python/examples/ipynb/TF_demo1_keras.ipynb
tylere/earthengine-api
apache-2.0
Data
url = "https://raw.githubusercontent.com/fehiepsi/rethinking-numpyro/master/data/cherry_blossoms.csv" cherry_blossoms = pd.read_csv(url, sep=";") df = cherry_blossoms display(df.sample(n=5, random_state=1)) display(df.describe()) df2 = df[df.doy.notna()] # complete cases on doy (day of year) x = df2.year.values.asty...
notebooks/misc/splines_numpyro.ipynb
probml/pyprobml
mit
B-splines
def make_splines(x, num_knots, degree=3): knot_list = jnp.quantile(x, q=jnp.linspace(0, 1, num=num_knots)) knots = jnp.pad(knot_list, (3, 3), mode="edge") B = BSpline(knots, jnp.identity(num_knots + 2), k=degree)(x) return B def plot_basis(x, B, w=None): if w is None: w = jnp.ones((B.shape...
notebooks/misc/splines_numpyro.ipynb
probml/pyprobml
mit
Repeat with temperature as target variable
df2 = df[df.temp.notna()] # complete cases x = df2.year.values.astype(float) y = df2.temp.values.astype(float) xlabel = "year" ylabel = "temp" nknots = 15 B = make_splines(x, nknots) plot_basis_with_vertical_line(x, B, 1200) plt.savefig(f"splines_basis_{nknots}_vertical_{ylabel}.pdf", dpi=300) post = fit_model(B, ...
notebooks/misc/splines_numpyro.ipynb
probml/pyprobml
mit
Maximum likelihood estimation
from sklearn.linear_model import LinearRegression, Ridge # reg = LinearRegression().fit(B, y) reg = Ridge().fit(B, y) w = reg.coef_ a = reg.intercept_ print(w) print(a) mu = a + B @ w plot_pred(mu, x, y) plt.savefig(f"splines_MLE_{nknots}_{ylabel}.pdf", dpi=300)
notebooks/misc/splines_numpyro.ipynb
probml/pyprobml
mit
Enter your details for twitter API
# get access to the twitter API APP_KEY = 'fQCYxyQmFDUE6aty0JEhDoZj7' APP_SECRET = 'ZwVIgnWMpuEEVd1Tlg6TWMuyRwd3k90W3oWyLR2Ek1tnjnRvEG' OAUTH_TOKEN = '824520596293820419-f4uGwMV6O7PSWUvbPQYGpsz5fMSVMct' OAUTH_TOKEN_SECRET = '1wq51Im5HQDoSM0Fb5OzAttoP3otToJtRFeltg68B8krh'
Lesson 14/Lesson 14 - Assignment.ipynb
jornvdent/WUR-Geo-Scripting-Course
gpl-3.0