markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
**Load embedding words** | # ***********************
# *** LOAD EMBEDDINGS ***
# ***********************
embedding_weights = []
vocab_size = len(tk.word_index)
embedding_weights.append(np.zeros(vocab_size))
for char, i in tk.word_index.items():
onehot = np.zeros(vocab_size)
onehot[i-1] = 1
embedding_weights.append(onehot)
embedding_... | Vocabulary size: 27
Embedding weights: [[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0... | MIT | models/Character_Level_CNN.ipynb | TheBlueEngineer/Serene-1.0 |
**Build the CNN model** | def KerasModel():
# ***************************************
# *****| BUILD THE NEURAL NETWORK |******
# ***************************************
embedding_layer = Embedding(vocab_size+1,
embedding_size,
input_length = input_size,
... | _____no_output_____ | MIT | models/Character_Level_CNN.ipynb | TheBlueEngineer/Serene-1.0 |
**Train the CNN** | #with tf.device("/gpu:0"):
# history = model.fit(x_train, y_train,
# validation_data = ( x_test, y_test),
# epochs = 10,
# batch_size = batch,
# verbose = True)
with tf.device("/gpu:0"):
grid = KerasClassifier(build_fn = KerasModel, epochs = 15, verbose= True)
... | Model: "model_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input (InputLayer) (None, 1000) 0
_______________________________________... | MIT | models/Character_Level_CNN.ipynb | TheBlueEngineer/Serene-1.0 |
**Test the CNN** | #loss, accuracy = model.evaluate( x_train, y_train, verbose = True)
#print("Training Accuracy: {:.4f}".format( accuracy))
#loss, accuracy = model.evaluate( x_test, y_test, verbose = True)
#print("Testing Accuracy: {:.4f}".format( accuracy))
from sklearn.metrics import classification_report, confusion_matrix
y_predict... | _____no_output_____ | MIT | models/Character_Level_CNN.ipynb | TheBlueEngineer/Serene-1.0 |
constitutive vs variable | def add_genetype(coverage):
"""function to add gene type to the df, and remove random genes"""
select_genes_file = '../../data/genomes/ara_housekeeping_list.out'
select_genes = pd.read_table(select_genes_file, sep='\t', header=None)
cols = ['gene','gene_type']
select_genes.columns = cols
merged ... | variable: (0.8546600937843323, 2.263117515610702e-08)
constitutive: (0.8711197376251221, 9.823354929494599e-08)
| MIT | src/plotting/OpenChromatin_plotsold.ipynb | Switham1/PromoterArchitecture |
Not normal | variance(no_random_roots)
variance(no_random_shoots)
variance(no_random_rootsshoots) | LeveneResult(statistic=0.00041366731166758155, pvalue=0.9837939970964911)
| MIT | src/plotting/OpenChromatin_plotsold.ipynb | Switham1/PromoterArchitecture |
unequal variance for shoots | def kruskal_test(input_data):
"""function to do kruskal-wallis test on data"""
#print('\033[1m' +promoter + '\033[0m')
print(kruskal(data=input_data, dv='percentage_bases_covered', between='gene_type'))
#print('')
no_random_roots
kruskal_test(no_random_roots)
kruskal_test(no_random_shoots)
kruskal_te... | Source ddof1 H p-unc
Kruskal gene_type 1 22.450983 0.000002
| MIT | src/plotting/OpenChromatin_plotsold.ipynb | Switham1/PromoterArchitecture |
try gat enrichment | #add Chr to linestart of chromatin bed files
add_chr_linestart('../../data/ATAC-seq/potter2018/Shoots_NaOH_peaks_all.bed','../../data/ATAC-seq/potter2018/Shoots_NaOH_peaks_all_renamed.bed')
add_chr_linestart('../../data/ATAC-seq/potter2018/Roots_NaOH_peaks_all.bed','../../data/ATAC-seq/potter2018/Roots_NaOH_peaks_all_... | _____no_output_____ | MIT | src/plotting/OpenChromatin_plotsold.ipynb | Switham1/PromoterArchitecture |
now I will do the plots with non-overlapping promoters including the 5'UTR | #merge promoters with genetype selected
promoter_UTR = '../../data/FIMO/non-overlapping_includingbidirectional_all_genes/promoters_5UTR_renamedChr.bed'
promoters_bed = pd.read_table(promoter_UTR, sep='\t', header=None)
cols = ['chr', 'start', 'stop', 'promoter_AGI', 'score', 'strand', 'source', 'feature_name', 'dot2', ... | /home/witham/opt/anaconda3/envs/PromoterArchitecturePipeline/lib/python3.7/site-packages/seaborn/distributions.py:369: UserWarning: Default bandwidth for data is 0; skipping density estimation.
warnings.warn(msg, UserWarning)
| MIT | src/plotting/OpenChromatin_plotsold.ipynb | Switham1/PromoterArchitecture |
Create, train, and predict with models | n,D = X.train.shape
m_v = 25
m_u, Q, = 50, D
Z_v = (m_v,D)
Z_u = (m_u,Q)
sample_size = 200 | _____no_output_____ | Apache-2.0 | main.ipynb | spectraldani/DeepMahalanobisGP |
SGPR | models['sgpr'] = gpflow.models.SGPR(X.train, y.train, gpflow.kernels.RBF(D, ARD=True), initial_inducing_points(X.train, m_u))
train_model('sgpr')
y_pred[('sgpr','mean')], y_pred[('sgpr','var')] = models['sgpr'].predict_y(X.test) | _____no_output_____ | Apache-2.0 | main.ipynb | spectraldani/DeepMahalanobisGP |
Deep Mahalanobis GP | reset_seed()
with gpflow.defer_build():
models['dvmgp'] = deep_vmgp.DeepVMGP(
X.train, y.train, Z_u, Z_v,
[gpflow.kernels.RBF(D,ARD=True) for i in range(Q)],
full_qcov=False, diag_qmu=False
)
models['dvmgp'].compile()
train_model('dvmgp')
y_pred[('dvmgp','mean')], y_pred[('dvmgp','var')]... | _____no_output_____ | Apache-2.0 | main.ipynb | spectraldani/DeepMahalanobisGP |
Show scores | for m in models.index:
scaled_y_test = scalers.y.inverse_transform(y.test)
scaled_y_pred = [
scalers.y.inverse_transform(y_pred[m].values[:,[0]]),
scalers.y.var_ * y_pred[m].values[:,[1]]
]
results.at[m,'MRAE'] = metrics.mean_relative_absolute_error(scaled_y_test, scaled_y_pred[0]).squee... | _____no_output_____ | Apache-2.0 | main.ipynb | spectraldani/DeepMahalanobisGP |
Plot results | class MidpointNormalize(mpl.colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mpl.colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5,... | _____no_output_____ | Apache-2.0 | main.ipynb | spectraldani/DeepMahalanobisGP |
`sasum(N, SX, INCX)`Computes the sum of absolute values of elements of the vector $x$.Operates on single-precision real valued arrays.Input vector $\mathbf{x}$ is represented as a [strided array](../strided_arrays.ipynb) `SX`, spaced by `INCX`.Vector $\mathbf{x}$ is of size `N`. Example usage | import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.abspath(''), "..", "..")))
import numpy as np
from pyblas.level1 import sasum
x = np.array([1, 2, 3], dtype=np.single)
N = len(x)
incx = 1
sasum(N, x, incx) | _____no_output_____ | BSD-3-Clause | docs/level1/sasum.ipynb | timleslie/pyblas |
Docstring | help(sasum) | Help on function sasum in module pyblas.level1.sasum:
sasum(N, SX, INCX)
Computes the sum of absolute values of elements of the vector x
Parameters
----------
N : int
Number of elements in input vector
SX : numpy.ndarray
A single precision real array, dimension (1 + (`N` - 1)*a... | BSD-3-Clause | docs/level1/sasum.ipynb | timleslie/pyblas |
Source code | sasum?? | _____no_output_____ | BSD-3-Clause | docs/level1/sasum.ipynb | timleslie/pyblas |
Notebook para o PAN - Atribuição Autoral - 2018 | %matplotlib inline
#python basic libs
import os;
from os.path import join as pathjoin;
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from sklearn.exceptions import UndefinedMetricWarning
warnings.simplefilter(action='ignore', category=UndefinedMetricWarning)
import re;
import json;
im... | _____no_output_____ | Apache-2.0 | 2019/PAN_AA_2018-POS-tag.ipynb | jeleandro/PANAA2018 |
paths configuration | baseDir = '/Users/joseeleandrocustodio/Dropbox/mestrado/02 - Pesquisa/code';
inputDir= pathjoin(baseDir,'pan18aa');
outputDir= pathjoin(baseDir,'out',"oficial");
if not os.path.exists(outputDir):
os.mkdir(outputDir); | _____no_output_____ | Apache-2.0 | 2019/PAN_AA_2018-POS-tag.ipynb | jeleandro/PANAA2018 |
loading the dataset | problems = pan.readCollectionsOfProblems(inputDir);
print(problems[0]['problem'])
print(problems[0].keys())
pd.DataFrame(problems)
def cachingPOSTAG(problem, taggingVersion='TAG'):
import json;
print ("Tagging: %s, language: %s, " %(problem['problem'],problem['language']), end=' ');
if not os.path.exi... | _____no_output_____ | Apache-2.0 | 2019/PAN_AA_2018-POS-tag.ipynb | jeleandro/PANAA2018 |
analisando os demais parametros | def spaceTokenizer(x):
return x.split(" ");
def runML(problem):
print ("\nProblem: %s, language: %s, " %(problem['problem'],problem['language']), end=' ');
lang = problem['language'];
if lang == 'sp':
lang = 'es';
elif lang =='pl':
print(lang, ' not supported');
return ... | _____no_output_____ | Apache-2.0 | 2019/PAN_AA_2018-POS-tag.ipynb | jeleandro/PANAA2018 |
Saving the model | dfCV.to_csv('PANAA2018_POSTAG.csv', index=False)
dfCV = pd.read_csv('PANAA2018_POSTAG.csv', na_values='')
import pickle;
with open("PANAA2018_POSTAG.pkl","wb") as f:
pickle.dump(estimators,f) | _____no_output_____ | Apache-2.0 | 2019/PAN_AA_2018-POS-tag.ipynb | jeleandro/PANAA2018 |
understanding the model with reports Podemos ver que para um mesmo problema mais de uma configuração é possível | print(' | '.join(best_parameters[0]['vect'].get_feature_names()[0:20]))
(dfCV[dfCV.rank_test_score == 1]).drop_duplicates()[
['problem',
'language',
'mean_test_score',
'std_test_score',
'ngram_range',
'sublinear_tf',
'norm']
].sort_values(by=[
'problem',
'mean_test_score',
'std... | _____no_output_____ | Apache-2.0 | 2019/PAN_AA_2018-POS-tag.ipynb | jeleandro/PANAA2018 |
O score retornado vem do conjunto de teste da validação cruzada e não do conjunto de testes | pd.options.display.precision = 3
print(u"\\begin{table}[h]\n\\centering\n\\caption{Medida F1 para os parâmetros }")
print(re.sub(r'[ ]{2,}',' ',dfCV.pivot_table(
index=['problem','language','sublinear_tf','norm'],
columns=['ngram_range'],
values='mean_test_score'
).to_latex()))
print ("\l... | _____no_output_____ | Apache-2.0 | 2019/PAN_AA_2018-POS-tag.ipynb | jeleandro/PANAA2018 |
tests | problem = problems[0]
print ("\nProblem: %s, language: %s, " %(problem['problem'],problem['language']), end=' ');
def d(estimator, n_features=5):
from IPython.display import Markdown, display, HTML
names = np.array(estimator.named_steps['vect'].get_feature_names());
classes_ = estimator.named_steps['clf']... | _____no_output_____ | Apache-2.0 | 2019/PAN_AA_2018-POS-tag.ipynb | jeleandro/PANAA2018 |
 Spark NLP Quick Start How to use Spark NLP pretrained pipelines [](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/jupyter/quick_start_goog... | !wget http://setup.johnsnowlabs.com/colab.sh -O - | bash
import sparknlp
spark = sparknlp.start()
print("Spark NLP version: {}".format(sparknlp.version()))
print("Apache Spark version: {}".format(spark.version))
from sparknlp.pretrained import PretrainedPipeline | _____no_output_____ | Apache-2.0 | jupyter/spark_nlp_model.ipynb | akashmavle5/--akash |
Let's use Spark NLP pre-trained pipeline for `named entity recognition` | pipeline = PretrainedPipeline('recognize_entities_dl', 'en')
result = pipeline.annotate('President Biden represented Delaware for 36 years in the U.S. Senate before becoming the 47th Vice President of the United States.')
print(result['ner'])
print(result['entities']) | ['O', 'B-PER', 'O', 'B-LOC', 'O', 'O', 'O', 'O', 'O', 'B-LOC', 'O', 'B-ORG', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-LOC', 'I-LOC', 'O']
['Biden', 'Delaware', 'U.S', 'Senate', 'United States']
| Apache-2.0 | jupyter/spark_nlp_model.ipynb | akashmavle5/--akash |
Let's try another Spark NLP pre-trained pipeline for `named entity recognition` | pipeline = PretrainedPipeline('onto_recognize_entities_bert_tiny', 'en')
result = pipeline.annotate("Johnson first entered politics when elected in 2001 as a member of Parliament. He then served eight years as the mayor of London, from 2008 to 2016, before rejoining Parliament.")
print(result['ner'])
print(result['en... | onto_recognize_entities_bert_tiny download started this may take some time.
Approx size to download 30.2 MB
[OK!]
['B-PERSON', 'B-ORDINAL', 'O', 'O', 'O', 'O', 'O', 'B-DATE', 'O', 'O', 'O', 'O', 'B-ORG', 'O', 'O', 'O', 'B-DATE', 'I-DATE', 'O', 'O', 'O', 'O', 'B-GPE', 'O', 'B-DATE', 'O', 'B-DATE', 'O', 'O', 'O', 'B-ORG'... | Apache-2.0 | jupyter/spark_nlp_model.ipynb | akashmavle5/--akash |
Let's use Spark NLP pre-trained pipeline for `sentiment` analysis | pipeline = PretrainedPipeline('analyze_sentimentdl_glove_imdb', 'en')
result = pipeline.annotate("Harry Potter is a great movie.")
print(result['sentiment']) | ['pos']
| Apache-2.0 | jupyter/spark_nlp_model.ipynb | akashmavle5/--akash |
Please check our [Models Hub](https://nlp.johnsnowlabs.com/models) for more pretrained models and pipelines! 😊 | _____no_output_____ | Apache-2.0 | jupyter/spark_nlp_model.ipynb | akashmavle5/--akash | |
电影评论文本分类 此笔记本(notebook)使用评论文本将影评分为*积极(positive)*或*消极(nagetive)*两类。这是一个*二元(binary)*或者二分类问题,一种重要且应用广泛的机器学习问题。我们将使用来源于[网络电影数据库(Internet Movie Database)](https://www.imdb.com/)的 [IMDB 数据集(IMDB dataset)](https://tensorflow.google.cn/api_docs/python/tf/keras/datasets/imdb),其包含 50,000 条影评文本。从该数据集切割出的25,000条评论用作训练,另外 25,000 条... | from __future__ import absolute_import, division, print_function, unicode_literals
try:
# Colab only
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
from tensorflow import keras
import numpy as np
print(tf.__version__) | 2.0.0
| Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
下载 IMDB 数据集IMDB 数据集已经打包在 Tensorflow 中。该数据集已经经过预处理,评论(单词序列)已经被转换为整数序列,其中每个整数表示字典中的特定单词。以下代码将下载 IMDB 数据集到您的机器上(如果您已经下载过将从缓存中复制): | imdb = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000) | _____no_output_____ | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
参数 `num_words=10000` 保留了训练数据中最常出现的 10,000 个单词。为了保持数据规模的可管理性,低频词将被丢弃。 探索数据让我们花一点时间来了解数据格式。该数据集是经过预处理的:每个样本都是一个表示影评中词汇的整数数组。每个标签都是一个值为 0 或 1 的整数值,其中 0 代表消极评论,1 代表积极评论。 | print("Training entries: {}, labels: {}".format(len(train_data), len(train_labels))) | Training entries: 25000, labels: 25000
| Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
评论文本被转换为整数值,其中每个整数代表词典中的一个单词。首条评论是这样的: | print(train_data[0]) | [1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 2, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 2, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38... | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
电影评论可能具有不同的长度。以下代码显示了第一条和第二条评论的中单词数量。由于神经网络的输入必须是统一的长度,我们稍后需要解决这个问题。 | len(train_data[0]), len(train_data[1]) | _____no_output_____ | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
将整数转换回单词了解如何将整数转换回文本对您可能是有帮助的。这里我们将创建一个辅助函数来查询一个包含了整数到字符串映射的字典对象: | # 一个映射单词到整数索引的词典
word_index = imdb.get_word_index()
# 保留第一个索引
word_index = {k:(v+3) for k,v in word_index.items()}
word_index["<PAD>"] = 0
word_index["<START>"] = 1
word_index["<UNK>"] = 2 # unknown
word_index["<UNUSED>"] = 3
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
def decod... | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/imdb_word_index.json
1646592/1641221 [==============================] - 0s 0us/step
| Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
现在我们可以使用 `decode_review` 函数来显示首条评论的文本: | decode_review(train_data[0]) | _____no_output_____ | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
准备数据影评——即整数数组必须在输入神经网络之前转换为张量。这种转换可以通过以下两种方式来完成:* 将数组转换为表示单词出现与否的由 0 和 1 组成的向量,类似于 one-hot 编码。例如,序列[3, 5]将转换为一个 10,000 维的向量,该向量除了索引为 3 和 5 的位置是 1 以外,其他都为 0。然后,将其作为网络的首层——一个可以处理浮点型向量数据的稠密层。不过,这种方法需要大量的内存,需要一个大小为 `num_words * num_reviews` 的矩阵。* 或者,我们可以填充数组来保证输入数据具有相同的长度,然后创建一个大小为 `max_length * num_reviews` 的整型张量。我们可以使用能... | train_data = keras.preprocessing.sequence.pad_sequences(train_data,
value=word_index["<PAD>"],
padding='post',
maxlen=256)
test_data = keras.preprocess... | _____no_output_____ | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
现在让我们看下样本的长度: | len(train_data[0]), len(train_data[1]) | _____no_output_____ | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
并检查一下首条评论(当前已经填充): | print(train_data[0]) | [ 1 14 22 16 43 530 973 1622 1385 65 458 4468 66 3941
4 173 36 256 5 25 100 43 838 112 50 670 2 9
35 480 284 5 150 4 172 112 167 2 336 385 39 4
172 4536 1111 17 546 38 13 447 4 192 50 16 6 147
2025 19 14 22 4 1920 4613 ... | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
构建模型神经网络由堆叠的层来构建,这需要从两个主要方面来进行体系结构决策:* 模型里有多少层?* 每个层里有多少*隐层单元(hidden units)*?在此样本中,输入数据包含一个单词索引的数组。要预测的标签为 0 或 1。让我们来为该问题构建一个模型: | # 输入形状是用于电影评论的词汇数目(10,000 词)
vocab_size = 10000
model = keras.Sequential()
model.add(keras.layers.Embedding(vocab_size, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation='relu'))
model.add(keras.layers.Dense(1, activation='sigmoid'))
model.summary() | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding (Embedding) (None, None, 16) 160000
____________________________________... | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
层按顺序堆叠以构建分类器:1. 第一层是`嵌入(Embedding)`层。该层采用整数编码的词汇表,并查找每个词索引的嵌入向量(embedding vector)。这些向量是通过模型训练学习到的。向量向输出数组增加了一个维度。得到的维度为:`(batch, sequence, embedding)`。2. 接下来,`GlobalAveragePooling1D` 将通过对序列维度求平均值来为每个样本返回一个定长输出向量。这允许模型以尽可能最简单的方式处理变长输入。3. 该定长输出向量通过一个有 16 个隐层单元的全连接(`Dense`)层传输。4. 最后一层与单个输出结点密集连接。使用 `Sigmoid` 激活函数,其函数值为介于 ... | model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']) | _____no_output_____ | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
创建一个验证集在训练时,我们想要检查模型在未见过的数据上的准确率(accuracy)。通过从原始训练数据中分离 10,000 个样本来创建一个*验证集*。(为什么现在不使用测试集?我们的目标是只使用训练数据来开发和调整模型,然后只使用一次测试数据来评估准确率(accuracy))。 | x_val = train_data[:10000]
partial_x_train = train_data[10000:]
y_val = train_labels[:10000]
partial_y_train = train_labels[10000:] | _____no_output_____ | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
训练模型以 512 个样本的 mini-batch 大小迭代 40 个 epoch 来训练模型。这是指对 `x_train` 和 `y_train` 张量中所有样本的的 40 次迭代。在训练过程中,监测来自验证集的 10,000 个样本上的损失值(loss)和准确率(accuracy): | history = model.fit(partial_x_train,
partial_y_train,
epochs=40,
batch_size=512,
validation_data=(x_val, y_val),
verbose=1) | Train on 15000 samples, validate on 10000 samples
Epoch 1/40
15000/15000 [==============================] - 1s 99us/sample - loss: 0.6921 - accuracy: 0.5437 - val_loss: 0.6903 - val_accuracy: 0.6241
Epoch 2/40
15000/15000 [==============================] - 1s 52us/sample - loss: 0.6870 - accuracy: 0.7057 - val_loss: 0.... | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
评估模型我们来看一下模型的性能如何。将返回两个值。损失值(loss)(一个表示误差的数字,值越低越好)与准确率(accuracy)。 | results = model.evaluate(test_data, test_labels, verbose=2)
print(results) | 25000/1 - 1s - loss: 0.3459 - accuracy: 0.8727
[0.325805940823555, 0.87268]
| Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
这种十分朴素的方法得到了约 87% 的准确率(accuracy)。若采用更好的方法,模型的准确率应当接近 95%。 创建一个准确率(accuracy)和损失值(loss)随时间变化的图表`model.fit()` 返回一个 `History` 对象,该对象包含一个字典,其中包含训练阶段所发生的一切事件: | history_dict = history.history
history_dict.keys() | _____no_output_____ | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
有四个条目:在训练和验证期间,每个条目对应一个监控指标。我们可以使用这些条目来绘制训练与验证过程的损失值(loss)和准确率(accuracy),以便进行比较。 | import matplotlib.pyplot as plt
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
epochs = range(1, len(acc) + 1)
# “bo”代表 "蓝点"
plt.plot(epochs, loss, 'bo', label='Training loss')
# b代表“蓝色实线”
plt.plot(epochs, val_loss, 'b', label='Va... | _____no_output_____ | Apache-2.0 | chapter2/2.3.2-text_classification.ipynb | wangxingda/Tensorflow-Handbook |
Just Plot It! Introduction The System In this course we will work with a set of "experimental" data to illustrate going from "raw" measurement (or simulation) data through exploratory visualization to an (almost) paper ready figure.In this scenario, we have fabricated (or simulated) 25 cantilevers. There is some va... | from IPython.display import YouTubeVideo
YouTubeVideo('4aTagDSnclk?start=19') | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
Springs, and our cantilevers, are part of a class of systems known as (Damped) Harmonic Oscillators. We are going to measure the natural frequency and damping rate we deflect each cantilever by the same amount and then observe the position as a function of time as the vibrations damp out. The Tools We are going make ... | # interactive figures, requires ipypml!
%matplotlib widget
#%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import xarray as xa | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
Philsophy While this coures uses Matplotlib for the visualization, the high-level lessons of this course are transferable to any plotting tools (in any language).At its core, programing in the process of taking existing tools (libraries) and building new tools more fit to your purpose. This course will walk through a... | # not sure how else to get the helpers on the path!
import sys
sys.path.append('../scripts')
from data_gen import get_data, fit | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
First look Using the function `get_data` we can pull an `xarray.DataArray` into our namespace and the use the html repr from xarray to get a first look at the data | d = get_data(25)
d | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
From this we can see that we have a, more-or-less, 2D array with 25 rows, each of which is a measurement that is a 4,112 point time series. Because this is an DataArray it also caries **coordinates** giving the value of **control** for each row and the time for each column. If we pull out just one row we can see a sin... | d[6] | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
We can see that the **control** coordinate now gives 1 value, but the **time** coordinate is still a vector. We can access these values via attribute access (which we will use later): | d[6].control
d[6].time | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
The Plotting Plot it?Looking at (truncated) lists of numbers is not intuitive or informative for most people, to get a better sense of what this data looks like lets plot it! We know that `Axes.plot` can plot multiple lines at once so lets try naively throwing `d` at `ax.plot`! | fig, ax = plt.subplots()
ax.plot(d); | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
While this does look sort of cool, it is not *useful*. What has happened is that Matplotlib has looked at our `(25, 4_112)` array and said "Clearly, you have a table that is 4k columns wide and 25 rows long. What you want is each column plotted!". Thus, what we are seeing is "The deflection at a fixed time as a func... | ?? plt.plot | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
While the Implicit API reduces the boilerplate required to get some things done and is convenient when working in a terminal, it comes at the cost of Matplotlib maintaining global state of which Axes is currently active! When scripting this can quickly become a headache to manage. When using Matplotlib with one of the... | fig, ax = plt.subplots()
ax.plot(d.T); | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
Which is better! If we squint a bit (or zoom in if we are using `ipympl` or a GUI backend) can sort of see each of the individual oscillators ringing-down over time. Just one at a time To make it easier to see lets plot just one of the curves: | fig, ax = plt.subplots()
ax.plot(d[6]); | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
Pass freshman physics While we do have just one line on the axes and can see what is going on, this plot would, right, be marked as little-to-no credit if turned in as part of a freshman Physics lab! We do not have a meaningful value on the x-axis, no legend, and no axis labels! | fig, ax = plt.subplots()
m = d[6]
ax.plot(m.time, m, label=f'control = {float(m.control):.1f}')
ax.set_xlabel('time (ms)')
ax.set_ylabel('displacement (mm)')
ax.legend(); | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
At this point we have a minimally acceptable plot! It shows us one curve with axis labels (with units!) and a legend. With sidebar: xarray plotting Because xarray knows more about the structure of your data than a couple of numpy arrays in your local namespace or dictionary, it can make smarter choices about the au... | fig, ax = plt.subplots()
m.plot(ax=ax) | _____no_output_____ | MIT | notebooks/00_just_plot_it.ipynb | NFAcademy/2021_course_dev-tacaswell |
8. Classification[Data Science Playlist on YouTube](https://www.youtube.com/watch?v=VLKEj9EN2ew&list=PLLBUgWXdTBDg1Qgmwt4jKtVn9BWh5-zgy)[](https://www.youtube.com/watch?v=VLKEj9EN2ew&list=PLLBUgWXdTBDg1Qgmwt4jKtVn9BWh5-zgy "Pyth... | from sklearn import datasets, svm
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# train classifier
digits = datasets.load_digits()
n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))
svc = svm.SVC(gamma=0.001)
X_train... | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 Test Number ClassifierThe image classification is trained on 10 randomly selected images from the other half of the data set to evaluate the training. Run the classifier test until you observe a misclassified number. | plt.figure(figsize=(10,4))
for i in range(10):
n = np.random.randint(int(n_samples/2),n_samples)
predict = svc.predict(digits.data[n:n+1])[0]
plt.subplot(2,5,i+1)
plt.imshow(digits.images[n], cmap=plt.cm.gray_r, interpolation='nearest')
plt.text(0,7,'Actual: ' + str(digits.target[n]),color='r')
... | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 Classification with Supervised Learning Select data set option with `moons`, `cirlces`, or `blobs`. Run the following cell to generate the data that will be used to test the classifiers. | option = 'moons' # moons, circles, or blobs
n = 2000 # number of data points
X = np.random.random((n,2))
mixing = 0.0 # add random mixing element to data
xplot = np.linspace(0,1,100)
if option=='moons':
X, y = datasets.make_moons(n_samples=n,noise=0.1)
yplot = xplot*0.0
elif option=='circles':
X, y = datas... | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 S.1 Logistic Regression**Definition:** Logistic regression is a machine learning algorithm for classification. In this algorithm, the probabilities describing the possible outcomes of a single trial are modelled using a logistic function.**Advantages:*... | from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(solver='lbfgs')
lr.fit(XA,yA)
yP = lr.predict(XB)
assess(yP) | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 S.2 Naïve Bayes**Definition:** Naive Bayes algorithm based on Bayes’ theorem with the assumption of independence between every pair of features. Naive Bayes classifiers work well in many real-world situations such as document classification and spam fi... | from sklearn.naive_bayes import GaussianNB
nb = GaussianNB()
nb.fit(XA,yA)
yP = nb.predict(XB)
assess(yP) | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 S.3 Stochastic Gradient Descent**Definition:** Stochastic gradient descent is a simple and very efficient approach to fit linear models. It is particularly useful when the number of samples is very large. It supports different loss functions and penalt... | from sklearn.linear_model import SGDClassifier
sgd = SGDClassifier(loss='modified_huber', shuffle=True,random_state=101)
sgd.fit(XA,yA)
yP = sgd.predict(XB)
assess(yP) | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 S.4 K-Nearest Neighbours**Definition:** Neighbours based classification is a type of lazy learning as it does not attempt to construct a general internal model, but simply stores instances of the training data. Classification is computed from a simple ... | from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(XA,yA)
yP = knn.predict(XB)
assess(yP) | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 S.5 Decision Tree**Definition:** Given a data of attributes together with its classes, a decision tree produces a sequence of rules that can be used to classify the data.**Advantages:** Decision Tree is simple to understand and visualise, requires litt... | from sklearn.tree import DecisionTreeClassifier
dtree = DecisionTreeClassifier(max_depth=10,random_state=101,\
max_features=None,min_samples_leaf=5)
dtree.fit(XA,yA)
yP = dtree.predict(XB)
assess(yP) | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 S.6 Random Forest**Definition:** Random forest classifier is a meta-estimator that fits a number of decision trees on various sub-samples of datasets and uses average to improve the predictive accuracy of the model and controls over-fitting. The sub-sa... | from sklearn.ensemble import RandomForestClassifier
rfm = RandomForestClassifier(n_estimators=70,oob_score=True,\
n_jobs=1,random_state=101,max_features=None,\
min_samples_leaf=3) #change min_samples_leaf from 30 to 3
rfm.fit(XA,yA)
yP = rfm.predict(XB)
assess(y... | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 S.7 Support Vector Classifier**Definition:** Support vector machine is a representation of the training data as points in space separated into categories by a clear gap that is as wide as possible. New examples are then mapped into that same space and ... | from sklearn.svm import SVC
svm = SVC(gamma='scale', C=1.0, random_state=101)
svm.fit(XA,yA)
yP = svm.predict(XB)
assess(yP) | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 S.8 Neural NetworkThe `MLPClassifier` implements a multi-layer perceptron (MLP) algorithm that trains using Backpropagation.**Definition:** A neural network is a set of neurons (activation functions) in layers that are processed sequentially to relate ... | from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(solver='lbfgs',alpha=1e-5,max_iter=200,activation='relu',\
hidden_layer_sizes=(10,30,10), random_state=1, shuffle=True)
clf.fit(XA,yA)
yP = clf.predict(XB)
assess(yP) | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 Unsupervised ClassificationAdditional examples show the potential for unsupervised learning to classify the groups. Unsupervised learning does not use the labels (`True`/`False`) so the results may need to be switched to align with the te... | from sklearn.cluster import KMeans
km = KMeans(n_clusters=2)
km.fit(XA)
yP = km.predict(XB)
if len(XB[yP!=yB]) > n/4: yP = 1 - yP
assess(yP) | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 U.2 Gaussian Mixture Model**Definition:** Data points that exist at the boundary of clusters may simply have similar probabilities of being on either clusters. A mixture model predicts a probability instead of a hard classification such as K-Means clus... | from sklearn.mixture import GaussianMixture
gmm = GaussianMixture(n_components=2)
gmm.fit(XA)
yP = gmm.predict_proba(XB) # produces probabilities
if len(XB[np.round(yP[:,0])!=yB]) > n/4: yP = 1 - yP
assess(np.round(yP[:,0])) | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 U.3 Spectral Clustering**Definition:** Spectral clustering is known as segmentation-based object categorization. It is a technique with roots in graph theory, where identify communities of nodes in a graph are based on the edges connecting them. The me... | from sklearn.cluster import SpectralClustering
sc = SpectralClustering(n_clusters=2,eigen_solver='arpack',\
affinity='nearest_neighbors')
yP = sc.fit_predict(XB) # No separation between fit and predict calls
# need to fit and predict on same dataset
if len(XB[yP!=yB]) > n... | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
 TCLab ActivityTrain a classifier to predict if the heater is on (100%) or off (0%). Generate data with 10 minutes of 1 second data. If you do not have a TCLab, use one of the sample data sets.- [Sample Data Set 1 (10 min)](http://apmonitor.com/do/u... | # 10 minute data collection
import tclab, time
import numpy as np
import pandas as pd
with tclab.TCLab() as lab:
n = 600; on=100; t = np.linspace(0,n-1,n)
Q1 = np.zeros(n); T1 = np.zeros(n)
Q2 = np.zeros(n); T2 = np.zeros(n)
Q1[20:41]=on; Q1[60:91]=on; Q1[150:181]=on
Q1[190:206]=on; Q1[2... | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
Use the data file `08-tclab.csv` to train and test the classifier. Select and scale (0-1) the features of the data including `T1`, `T2`, and the 1st and 2nd derivatives of `T1`. Use the measured temperatures, derivatives, and heater value label to create a classifier that predicts when the heater is on or off. Validate... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
try:
data = pd.read_csv('08-tclab.csv')
except:
print('Warning: Unable to load 08-tclab.csv, using online da... | _____no_output_____ | MIT | 08. Classification.ipynb | monocilindro/data_science |
Data Science - Regressão Linear Bônus Importando nosso modelo | import pickle
modelo = open('../Exercicio/modelo_preço','rb')
lm_new = pickle.load(modelo)
modelo.close()
area = 38
garagem = 2
banheiros = 4
lareira = 4
marmore = 0
andares = 1
entrada = [[area, garagem, banheiros, lareira, marmore, andares]]
print('$ {0:.2f}'.format(lm_new.predict(entrada)[0])) | _____no_output_____ | MIT | reg-linear/Bonus/Simulador Interativo.ipynb | DiegoVialle/Regressao-Linear-Testando-Relacoes-e-Prevendo-Resultados |
Exemplo de um simulador interativo para Jupyterhttps://ipywidgets.readthedocs.io/en/stable/index.htmlhttps://github.com/jupyter-widgets/ipywidgets | # Importando bibliotecas
from ipywidgets import widgets, HBox, VBox
from IPython.display import display
# Criando os controles do formulário
area = widgets.Text(description="Área")
garagem = widgets.Text(description="Garagem")
banheiros = widgets.Text(description="Banheiros")
lareira = widgets.Text(description="Lareir... | _____no_output_____ | MIT | reg-linear/Bonus/Simulador Interativo.ipynb | DiegoVialle/Regressao-Linear-Testando-Relacoes-e-Prevendo-Resultados |
Installing & importing necsessary libs | !pip install -q transformers
import numpy as np
import pandas as pd
from sklearn import metrics
import transformers
import torch
from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler
from transformers import AlbertTokenizer, AlbertModel, AlbertConfig
from tqdm.notebook import tqdm
from tran... | _____no_output_____ | MIT | albert-base/albert-baseline.ipynb | shanayghag/AV-Janatahack-Independence-Day-2020-ML-Hackathon |
Data Preprocessing | df = pd.read_csv("../input/avjantahack/data/train.csv")
df['list'] = df[df.columns[3:]].values.tolist()
new_df = df[['ABSTRACT', 'list']].copy()
new_df.head() | _____no_output_____ | MIT | albert-base/albert-baseline.ipynb | shanayghag/AV-Janatahack-Independence-Day-2020-ML-Hackathon |
Model configurations | # Defining some key variables that will be used later on in the training
MAX_LEN = 512
TRAIN_BATCH_SIZE = 16
VALID_BATCH_SIZE = 8
EPOCHS = 5
LEARNING_RATE = 3e-05
tokenizer = AlbertTokenizer.from_pretrained('albert-base-v2') | _____no_output_____ | MIT | albert-base/albert-baseline.ipynb | shanayghag/AV-Janatahack-Independence-Day-2020-ML-Hackathon |
Custom Dataset Class | class CustomDataset(Dataset):
def __init__(self, dataframe, tokenizer, max_len):
self.tokenizer = tokenizer
self.data = dataframe
self.abstract = dataframe.ABSTRACT
self.targets = self.data.list
self.max_len = max_len
def __len__(self):
return len(self.abstract)... | _____no_output_____ | MIT | albert-base/albert-baseline.ipynb | shanayghag/AV-Janatahack-Independence-Day-2020-ML-Hackathon |
Albert model | class AlbertClass(torch.nn.Module):
def __init__(self):
super(AlbertClass, self).__init__()
self.albert = transformers.AlbertModel.from_pretrained('albert-base-v2')
self.drop = torch.nn.Dropout(0.1)
self.linear = torch.nn.Linear(768, 6)
def forward(self, ids, mask, token_typ... | _____no_output_____ | MIT | albert-base/albert-baseline.ipynb | shanayghag/AV-Janatahack-Independence-Day-2020-ML-Hackathon |
Hyperparameters & Loss function | def loss_fn(outputs, targets):
return torch.nn.BCEWithLogitsLoss()(outputs, targets)
param_optimizer = list(model.named_parameters())
no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"]
optimizer_parameters = [
{
"params": [
p for n, p in param_optimizer if not any(nd in n for nd in no... | _____no_output_____ | MIT | albert-base/albert-baseline.ipynb | shanayghag/AV-Janatahack-Independence-Day-2020-ML-Hackathon |
Train & Eval Functions | def train(epoch):
model.train()
for _,data in tqdm(enumerate(training_loader, 0), total=len(training_loader)):
ids = data['ids'].to(device, dtype = torch.long)
mask = data['mask'].to(device, dtype = torch.long)
token_type_ids = data['token_type_ids'].to(device, dtype = torch.long)
... | _____no_output_____ | MIT | albert-base/albert-baseline.ipynb | shanayghag/AV-Janatahack-Independence-Day-2020-ML-Hackathon |
Training Model | MODEL_PATH = "/kaggle/working/albert-multilabel-model.bin"
best_micro = 0
for epoch in range(EPOCHS):
train(epoch)
outputs, targets = validation(epoch)
outputs = np.array(outputs) >= 0.5
accuracy = metrics.accuracy_score(targets, outputs)
f1_score_micro = metrics.f1_score(targets, outputs, average='... | _____no_output_____ | MIT | albert-base/albert-baseline.ipynb | shanayghag/AV-Janatahack-Independence-Day-2020-ML-Hackathon |
Droplet Evaporation | import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
# Ethyl Acetate
#time_in_sec = np.array([0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110])
#diameter = np.array([2.79,2.697,2.573,2.542,2.573,2.48,2.449,2.449,2.387,2.356,2.263,2.232,2.201,2.139,1.82,1.426,1.178,1.085,0.... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
Ethyl Acetate | time_in_sec = np.array([0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110])
diameter = np.array([2.79,2.697,2.573,2.542,2.573,2.48,2.449,2.449,2.387,2.356,2.263,2.232,2.201,2.139,1.82,1.426,1.178,1.085,0.992,0.496,0.403,0.372,0.11])
x = time_in_sec.tolist()
y = diameter.tolist()
polynomial_coeff_1=... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
Linear Fit | # Calculating time taken for vaporization for different diameters. (LINEAR FIT)
diameter = np.array([2.79,2.697,2.573,2.542,2.573,2.48,2.449,2.449,2.387,2.356,2.263,2.232,2.201,2.139,1.82,1.426,1.178,1.085,0.992,0.496,0.403,0.372,0.11])
time_in_sec = np.array([0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,1... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
Quadratic Fit | # Calculating time taken for vaporization for different diameters. (QUADRATIC FIT)
diameter = np.array([2.79,2.697,2.573,2.542,2.573,2.48,2.449,2.449,2.387,2.356,2.263,2.232,2.201,2.139,1.82,1.426,1.178,1.085,0.992,0.496,0.403,0.372,0.11])
time_in_sec = np.array([0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,9... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
Ethyl Acetate - After finding d-square Law | # Linear
C = 41.72856231
n = -0.97941652
# Quadratic
# C = 11.6827828
# n = -2.13925924
x = vap_time.tolist()
y = initial_diameter.tolist()
ynew=np.linspace(0,3 ,100)
xnew=[]
for item in ynew:
v1 = C/(item**n)
xnew.append(v1)
plt.plot(x,y,'o')
plt.plot(xnew,ynew)
plt.title("Initial Diameter vs Vaporiz... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
Gasoline | time_in_min = np.array([0,15,30,45,60,75,90,105,120,135,150,165,180,210,235,250,265])
diameter = np.array([2,1.85,1.82,1.8,1.77,1.74,1.72,1.68,1.57,1.3,1.166,1.091,0.94,0.81,0.74,0.66,0.59])
x = time_in_min.tolist()
y = diameter.tolist()
polynomial_coeff_1=np.polyfit(x,y,1)
polynomial_coeff_2=np.polyfit(x,y,2)
polynom... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
Linear Fit | # Calculating time taken for vaporization for different diameters. (LINEAR FIT)
time_in_min = np.array([0,15,30,45,60,75,90,105,120,135,150,165,180,210,235,250,265])
diameter = np.array([2,1.85,1.82,1.8,1.77,1.74,1.72,1.68,1.57,1.3,1.166,1.091,0.94,0.81,0.74,0.66,0.59])
t_vap = time_in_min
t_vap = t_vap*0
t_vap = t_vap... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
Quadratic Fit | # Calculating time taken for vaporization for different diameters.
time_in_min = np.array([0,15,30,45,60,75,90,105,120,135,150,165,180,210,235,250,265])
diameter = np.array([2,1.85,1.82,1.8,1.77,1.74,1.72,1.68,1.57,1.3,1.166,1.091,0.94,0.81,0.74,0.66,0.59])
t_vap = time_in_min
t_vap = t_vap*0
t_vap = t_vap + 329.781
t_... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
Gasoline - After finding Vaporization Time Data | #Linear
C_g = 140.10666889
n_g = -1.1686059
# Quadratic
C_g = 140.10666889
n_g = -1.1686059
x_g = vap_time_g.tolist()
y_g = initial_diameter_g.tolist()
ynew_g=np.linspace(0,2.2 ,100)
xnew_g=[]
for item in ynew_g:
v1 = C_g/(item**n_g)
xnew_g.append(v1)
print(ynew_g)
print(xnew_g)
plt.plot(x_g,y_g,'o')... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
Optimization Methods (IGNORE) | import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
plt.style.use('seaborn-poster')
time_in_sec = np.array([5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110])
diameter = np.array([2.697,2.573,2.542,2.573,2.48,2.449,2.449,2.387,2.356,2.263,2.232,2.201,2.139,1.82,1.426,1.178,... | _____no_output_____ | MIT | AS2520 Propulsion Lab/Experiment 6 - Droplet Evaporation/re-work-notebook.ipynb | kirtan2605/Coursework-Codes |
NLP with Bert for Sentiment Analysis Importing Libraries | !pip3 install ktrain
import os.path
import numpy as np
import pandas as pd
import tensorflow as tf
import ktrain
from ktrain import text | _____no_output_____ | Unlicense | Special. NLP_with_BERT.ipynb | Samrath49/AI_ML_DL |
Part 1: Data Preprocessing Loading the IMDB dataset | dataset = tf.keras.utils.get_file(fname = "aclImdb_v1.tar",
origin = "https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar",
extract = True)
IMDB_DATADIR = os.path.join(os.path.dirname(dataset), 'aclImdb')
print(os.path.dirname(dataset))
pr... | /root/.keras/datasets
/root/.keras/datasets/aclImdb
| Unlicense | Special. NLP_with_BERT.ipynb | Samrath49/AI_ML_DL |
Creating the training & test sets | (X_train, y_train), (X_test, y_test), preproc = text.texts_from_folder(datadir = IMDB_DATADIR,
classes = ['pos','neg'],
maxlen = 500,
... | detected encoding: utf-8
downloading pretrained BERT model (uncased_L-12_H-768_A-12.zip)...
[██████████████████████████████████████████████████]
extracting pretrained BERT model...
done.
cleanup downloaded zip...
done.
preprocessing train...
language: en
| Unlicense | Special. NLP_with_BERT.ipynb | Samrath49/AI_ML_DL |
Part 2: Building the BERT model | model = text.text_classifier(name = 'bert',
train_data = (X_train, y_train),
preproc = preproc) | Is Multi-Label? False
maxlen is 500
done.
| Unlicense | Special. NLP_with_BERT.ipynb | Samrath49/AI_ML_DL |
Part 3: Training the BERT model | learner = ktrain.get_learner(model = model,
train_data = (X_train, y_train),
val_data = (X_test, y_test),
batch_size = 6)
learner.fit_onecycle(lr=2e-5,
epochs = 1) |
begin training using onecycle policy with max lr of 2e-05...
4167/4167 [==============================] - 3436s 820ms/step - loss: 0.3313 - accuracy: 0.8479 - val_loss: 0.1619 - val_accuracy: 0.9383
| Unlicense | Special. NLP_with_BERT.ipynb | Samrath49/AI_ML_DL |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.