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
Sentiment for individual stocks
stocks = ["GME", "AMC", "AMD","AMZN", "PLTR", "NVDA"] for stock in stocks: gme_posts = df.loc[df["body"].str.contains(stock),:] plot_sentiment(gme_posts,title=f"{stock}-normalized", normalize=True) plot_sentiment(gme_posts,title=f"{stock}-unnormalized", normalize=False)
_____no_output_____
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
Analyzing Stock Data
def get_daily_sentiment(df, stock): # intialize df with all dates in august datelist = pd.date_range(datetime(2021,8,1), periods=31).tolist() sentiment_df = pd.DataFrame({"date":datelist}) sentiment_df = sentiment_df.set_index("date") # get all posts mentioning stock posts = df.loc[df["b...
_____no_output_____
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
visualize stock prices
def scale(x): minx = np.min(x); maxx = np.max(x) return (x-minx) / (maxx-minx) for stock in stocks: # plot scaled price against the number of posts price = stonks_df.dropna(axis=0)[[stock]] num_posts = sentiment_df[stock]["count"].loc[price.index,].values plt.plot(price.index, scale(price), alp...
_____no_output_____
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
sentiment vs stock prices
# from sklearn.linear_model import LinearRegression import statsmodels.api as sm for stock in stocks: # get stock prices y = stonks_df.dropna(axis=0)[[stock]] print("="*50) print(f'name: {stock}, total:{sum(sentiment_df[stock]["count"])}') print("="*50) for col in sentiment_df[stock].columns...
================================================== name: GME, total:7867 ================================================== rsquared: 0.381 intercept: 0.000 positive: 0.111 negative: 0.100 neutral: 0.028 count: 0.056 ================================================== name: AMC, total:5130 ==============================...
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
sentiment vs stock direction
from sklearn.metrics import roc_auc_score stonks_diff = stonks_df.diff() for stock in stocks: # check if stock increased y = (stonks_diff.dropna(axis=0)[[stock]] > 0) * 1 print("="*50) print(f'name: {stock}, total:{sum(sentiment_df[stock]["count"])}') print("="*50) for col in sentiment_df[st...
================================================== name: GME, total:7867 ================================================== count: auc:0.639, acc:0.612 ================================================== name: AMC, total:5130 ================================================== count: auc:0.561, acc:0.592 ================...
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
sentiment vs returns
stonks_diff = stonks_df.diff() for stock in stocks: y = stonks_diff.dropna(axis=0)[[stock]] print("="*50) print(f'name: {stock}') print("="*50) for col in sentiment_df[stock].columns: X = sentiment_df[stock][col].loc[y.index,].values X = sm.add_constant(X) mod = sm.OLS(y,X) ...
================================================== name: GME, total:7867 ================================================== rsquared: 0.314 intercept: 0.271 positive: 0.314 negative: 0.761 neutral: 0.503 count: 0.005 ================================================== name: AMC, total:5130 ==============================...
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
sentiment vs log returns
stonks_log = np.log(stonks_df) for stock in stocks: y = stonks_log.diff().dropna(axis=0)[[stock]] print("="*50) print(f'name: {stock}') print("="*50) for col in sentiment_df[stock].columns: X = sentiment_df[stock][col].loc[y.index,].values X = sm.add_constant(X) mod = sm.OLS(...
================================================== name: GME ================================================== positive: 0.287, pval: 0.003 negative: 0.212, pval: 0.014 neutral: 0.289, pval: 0.003 count: 0.272, pval: 0.004 ================================================== name: AMC ===============================...
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
The
_____no_output_____
MIT
wsb_sentiment.ipynb
kenzeng24/wsb-analysis
NumPy arrays Nikolay Koldunovkoldunovn@gmail.com This is part of [**Python for Geosciences**](https://github.com/koldunovn/python_for_geosciences) notes. ================ - a powerful N-dimensional array object- sophisticated (broadcasting) functions- tools for integrating C/C++ and Fortran code- useful l...
#allow graphics inline %matplotlib inline import matplotlib.pylab as plt #import plotting library import numpy as np #import numpy library np.set_printoptions(precision=3) # this is just to make the output look better
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Load data I am going to use some real data as an example of array manipulations. This will be the AO index downloaded by wget through a system call (you have to be on Linux of course):
!wget www.cpc.ncep.noaa.gov/products/precip/CWlink/daily_ao_index/monthly.ao.index.b50.current.ascii
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
This is how data in the file look like (we again use system call for *head* command):
!head monthly.ao.index.b50.current.ascii
1950 1 -0.60310E-01 1950 2 0.62681E+00 1950 3 -0.81275E-02 1950 4 0.55510E+00 1950 5 0.71577E-01 1950 6 0.53857E+00 1950 7 -0.80248E+00 1950 8 -0.85101E+00 1950 9 0.35797E+00 1950 10 -0.37890E+00
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Load data in to a variable:
ao = np.loadtxt('monthly.ao.index.b50.current.ascii') ao ao.shape
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
So it's a *row-major* order. Matlab and Fortran use *column-major* order for arrays.
type(ao)
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Numpy arrays are statically typed, which allow faster operations
ao.dtype
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
You can't assign value of different type to element of the numpy array:
ao[0,0] = 'Year'
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Slicing works similarly to Matlab:
ao[0:5,:]
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
One can look at the data. This is done by matplotlib.pylab module that we have imported in the beggining as `plt`. We will plot only first 780 poins:
plt.plot(ao[:780,2])
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Index slicing In general it is similar to Matlab First 12 elements of **second** column (months). Remember that indexing starts with 0:
ao[0:12,1]
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
First raw:
ao[0,:]
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
We can create mask, selecting all raws where values in second raw (months) equals 10 (October):
mask = (ao[:,1]==10)
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Here we apply this mask and show only first 5 rowd of the array:
ao[mask][:5,:]
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
You don't have to create separate variable for mask, but apply it directly. Here instead of first five rows I show five last rows:
ao[ao[:,1]==10][-5:,:]
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
You can combine conditions. In this case we select October-December data (only first 10 elements are shown):
ao[(ao[:,1]>=10)&(ao[:,1]<=12)][0:10,:]
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
You can assighn values to subset of values (*thi expression fixes the problem with very small value at 2015-04*)
ao[ao<-10]=0
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Basic operations Create example array from first 12 values of second column and perform some basic operations:
months = ao[0:12,1] months months+10 months*20 months*months
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Basic statistics Create *ao_values* that will contain onlu data values:
ao_values = ao[:,2]
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Simple statistics:
ao_values.min() ao_values.max() ao_values.mean() ao_values.std() ao_values.sum()
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
You can also use *np.sum* function:
np.sum(ao_values)
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
One can make operations on the subsets:
np.mean(ao[ao[:,1]==1,2]) # January monthly mean
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Result will be the same if we use method on our selected data:
ao[ao[:,1]==1,2].mean()
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Saving data You can save your data as a text file
np.savetxt('ao_only_values.csv',ao[:, 2], fmt='%.4f')
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Head of resulting file:
!head ao_only_values.csv
-0.0603 0.6268 -0.0081 0.5551 0.0716 0.5386 -0.8025 -0.8510 0.3580 -0.3789
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
You can also save it as binary:
f=open('ao_only_values.bin', 'w') ao[:,2].tofile(f) f.close()
_____no_output_____
CC-BY-3.0
03 - NumPy arrays.ipynb
davibortolotti/python_for_geosciences
Creating your own dataset from Google Images*by: Francisco Ingham and Jeremy Howard. Inspired by [Adrian Rosebrock](https://www.pyimagesearch.com/2017/12/04/how-to-create-a-deep-learning-dataset-using-google-images/)* In this tutorial we will see how to easily create an image dataset through Google Images. **Note**: ...
%reload_ext autoreload %autoreload 2 %matplotlib inline # You need to mount your google drive to the /content/gdrive folder of your virtual computer # located in the colab server from google.colab import drive drive.mount("/content/gdrive") #drive.mount("/content/gdrive", force_remount=True) from fastai.vision impor...
_____no_output_____
Apache-2.0
MidTermPart2.ipynb
moonryul/course-v3
Get a list of URLs Search and scroll Question 1: (1.1) Please download 3 categories of animal images from google. Download about 100 images for each category. Go to [Google Images](http://images.google.com) and search for the images you are interested in. The more specific you are in your Google Search, the better t...
path = Path('gdrive/My Drive/fastai-v3/data/bears')
_____no_output_____
Apache-2.0
MidTermPart2.ipynb
moonryul/course-v3
Download images Now you will need to download your images from their respective urls.fast.ai has a function that allows you to do just that. You just have to specify the urls filename as well as the destination folder and this function will download and save all images that can be opened. If they have some problem in ...
classes = ['teddys','grizzly','black'] # For example, Do this when download "urls_black.csv' file: folder = 'teddys' dest = path/folder file = 'urls_teddy.csv' download_images(dest/file, dest, max_pics=100) # Question 2: Explain what happens when you execute download_images() statement. for c in classes: print(c) ...
teddys
Apache-2.0
MidTermPart2.ipynb
moonryul/course-v3
View data
np.random.seed(42) data = ImageDataBunch.from_folder(path, train=".", valid_pct=0.2, ds_tfms=get_transforms(), size=224, num_workers=4).normalize(imagenet_stats # Question 3: Explain how the categories of the images are extracted when you exec...
_____no_output_____
Apache-2.0
MidTermPart2.ipynb
moonryul/course-v3
Good! Let's take a look at some of our pictures then. Train model
learn = cnn_learner(data, models.resnet34, metrics=error_rate) # Question 4: 4.1) cnn_learner() has input paramters other than the shown above. # One of them is pretrained, which is True by default when you do not specify it. # What happens when you specify pretrained=True as in # learn = cnn_learner(data, models.res...
_____no_output_____
Apache-2.0
MidTermPart2.ipynb
moonryul/course-v3
Python for Finance (2nd ed.)**Mastering Data-Driven Finance**&copy; Dr. Yves J. Hilpisch | The Python Quants GmbH Data Analysis with pandas pandas Basics First Steps with DataFrame Class
import pandas as pd df = pd.DataFrame([10, 20, 30, 40], columns=['numbers'], index=['a', 'b', 'c', 'd']) df df.index df.columns df.loc['c'] df.loc[['a', 'd']] df.iloc[1:3] df.sum() df.apply(lambda x: x ** 2) df ** 2 df['floats'] = (1.5, 2.5, 3.5, 4.5) df d...
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Second Steps with DataFrame Class
import numpy as np np.random.seed(100) a = np.random.standard_normal((9, 4)) a df = pd.DataFrame(a) df df.columns = ['No1', 'No2', 'No3', 'No4'] df df['No2'].mean() dates = pd.date_range('2019-1-1', periods=9, freq='M') dates df.index = dates df df.values np.array(df)
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Basic Analytics
df.info() df.describe() df.sum() df.mean() df.mean(axis=0) df.mean(axis=1) df.cumsum() np.mean(df) # raises warning np.log(df) np.sqrt(abs(df)) np.sqrt(abs(df)).sum() 100 * df + 100
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Basic Visualization
from pylab import plt, mpl plt.style.use('seaborn') mpl.rcParams['font.family'] = 'serif' %matplotlib inline df.cumsum().plot(lw=2.0, figsize=(10, 6)); # plt.savefig('../../images/ch05/pd_plot_01.png') df.plot.bar(figsize=(10, 6), rot=30); # df.plot(kind='bar', figsize=(10, 6)) # plt.savefig('../../images/c...
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Series Class
type(df) S = pd.Series(np.linspace(0, 15, 7), name='series') S type(S) s = df['No1'] s type(s) s.mean() s.plot(lw=2.0, figsize=(10, 6)); # plt.savefig('../../images/ch05/pd_plot_03.png')
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
GroupBy Operations
df['Quarter'] = ['Q1', 'Q1', 'Q1', 'Q2', 'Q2', 'Q2', 'Q3', 'Q3', 'Q3'] df groups = df.groupby('Quarter') groups.size() groups.mean() groups.max() groups.aggregate([min, max]).round(2) df['Odd_Even'] = ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd'] groups...
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Complex Selection
data = np.random.standard_normal((10, 2)) df = pd.DataFrame(data, columns=['x', 'y']) df.info() df.head() df.tail() df['x'] > 0.5 (df['x'] > 0) & (df['y'] < 0) (df['x'] > 0) | (df['y'] < 0) df[df['x'] > 0] df.query('x > 0') df[(df['x'] > 0) & (df['y'] < 0)] df.query('x > 0 & y < 0') df[(df.x > 0...
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Concatenation, Joining and Merging
df1 = pd.DataFrame(['100', '200', '300', '400'], index=['a', 'b', 'c', 'd'], columns=['A',]) df1 df2 = pd.DataFrame(['200', '150', '50'], index=['f', 'b', 'd'], columns=['B',]) df2
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Concatenation
df1.append(df2, sort=False) df1.append(df2, ignore_index=True, sort=False) pd.concat((df1, df2), sort=False) pd.concat((df1, df2), ignore_index=True, sort=False)
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Joining
df1.join(df2) df2.join(df1) df1.join(df2, how='left') df1.join(df2, how='right') df1.join(df2, how='inner') df1.join(df2, how='outer') df = pd.DataFrame() df['A'] = df1['A'] df df['B'] = df2 df df = pd.DataFrame({'A': df1['A'], 'B': df2['B']}) df
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Merging
c = pd.Series([250, 150, 50], index=['b', 'd', 'c']) df1['C'] = c df2['C'] = c df1 df2 pd.merge(df1, df2) pd.merge(df1, df2, on='C') pd.merge(df1, df2, how='outer') pd.merge(df1, df2, left_on='A', right_on='B') pd.merge(df1, df2, left_on='A', right_on='B', how='outer') pd.merge(df1, df2, left_index=True, right_...
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
Performance Aspects
data = np.random.standard_normal((1000000, 2)) data.nbytes df = pd.DataFrame(data, columns=['x', 'y']) df.info() %time res = df['x'] + df['y'] res[:3] %time res = df.sum(axis=1) res[:3] %time res = df.values.sum(axis=1) res[:3] %time res = np.sum(df, axis=1) res[:3] %time res = np.sum(df.values, axis=1)...
_____no_output_____
CNRI-Python
code/ch05/05_pandas.ipynb
meaninginuse/py4fi2nd
RAC/DVR step 1: diagonalize **H**($\lambda$)
import numpy as np import sys import matplotlib.pyplot as plt %matplotlib qt5 import pandas as pd # # extend path by location of the dvr package # sys.path.append('../../Python_libs') import dvr import jolanta amu_to_au=1822.888486192 au2cm=219474.63068 au2eV=27.211386027 Angs2Bohr=1.8897259886 # # Jolanata-3D paramet...
1 -0.26351095 au = -7.17050 eV 2 0.11989697 au = 3.26256 eV 3 0.28142119 au = 7.65786 eV 4 0.52212147 au = 14.20765 eV
MIT
notebooks/RAC_3D/.ipynb_checkpoints/RAC-DVR-J3D-checkpoint.ipynb
tsommerfeld/L2-methods_for_resonances
RAC by increasing $b$The last energy needs to be about $7E_r \approx 22$eV
# # show the potential # a_ref, b_ref, c_ref = jparam plt.cla() for b_curr in [1.1, 1.3, 1.5, 1.7]: param = [a_ref, b_curr, c_ref] plt.plot(rs, jolanta.Jolanta_3D(rs, param)*au2eV) plt.ylim(-30, 10) plt.show() a_ref, b_ref, c_ref = jparam b_min=b_ref b_max=2.5 nEs_keep=4 # how many energies are kept n_b=...
_____no_output_____
MIT
notebooks/RAC_3D/.ipynb_checkpoints/RAC-DVR-J3D-checkpoint.ipynb
tsommerfeld/L2-methods_for_resonances
RAC with Coulomb potential
# # show the potential # def coulomb(r, lbd=1.0): """ attractive Coulomb potential with strength lbd = lamda """ return -lbd/r plt.cla() for l_curr in [0, 0.5, 1.0, 1.5, 2.0]: plt.plot(rs, (jolanta.Jolanta_3D(rs, jparam)+coulomb(rs, lbd=l_curr))*au2eV) #plt.xlim(0,15) plt.ylim(-30, 10) plt.show() l_m...
_____no_output_____
MIT
notebooks/RAC_3D/.ipynb_checkpoints/RAC-DVR-J3D-checkpoint.ipynb
tsommerfeld/L2-methods_for_resonances
RAC with soft-box
# # show the box potential # def softbox(r, rcut=1.0, lbd=1.0): """ Softbox: -1 at the origin, rises at r0 softly to asymptotic 0 based on Gaussian with inverted scale """ return lbd*(np.exp(-(2*rcut)**2/r**2) - 1) plt.cla() for l_curr in [0.1, 0.2, 0.3, 0.4, 0.5]: Vs = jolanta.Jolanta_3...
_____no_output_____
MIT
notebooks/RAC_3D/.ipynb_checkpoints/RAC-DVR-J3D-checkpoint.ipynb
tsommerfeld/L2-methods_for_resonances
Deep Learning=============Assignment 4------------Previously in `2_fullyconnected.ipynb` and `3_regularization.ipynb`, we trained fully connected networks to classify [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) characters.The goal of this assignment is make the neural network convolutional.
# These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import time import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range pickle_file = 'notMNIST.pickle' with open(pickle...
Training set (200000, 28, 28) (200000,) Validation set (10000, 28, 28) (10000,) Test set (10000, 28, 28) (10000,)
Apache-2.0
previous_training/udacity/4_convolutions.ipynb
archelogos/smart-live-camera
Reformat into a TensorFlow-friendly shape:- convolutions need the image data formatted as a cube (width by height by channels)- labels as float 1-hot encodings.
image_size = 28 num_labels = 10 num_channels = 1 # grayscale import numpy as np def reformat(dataset, labels): dataset = dataset.reshape( (-1, image_size, image_size, num_channels)).astype(np.float32) labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_dataset,...
_____no_output_____
Apache-2.0
previous_training/udacity/4_convolutions.ipynb
archelogos/smart-live-camera
Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes.
batch_size = 16 patch_size = 5 depth = 16 num_hidden = 64 graph = tf.Graph() with graph.as_default(): # Input data. tf_train_dataset = tf.placeholder( tf.float32, shape=(batch_size, image_size, image_size, num_channels)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_vali...
Initialized Minibatch loss at step 0 : 3.51275 Minibatch accuracy: 6.2% Validation accuracy: 12.8% Minibatch loss at step 50 : 1.48703 Minibatch accuracy: 43.8% Validation accuracy: 50.4% Minibatch loss at step 100 : 1.04377 Minibatch accuracy: 68.8% Validation accuracy: 67.4% Minibatch loss at step 150 : 0.601682 Mini...
Apache-2.0
previous_training/udacity/4_convolutions.ipynb
archelogos/smart-live-camera
---Problem 1---------The convolutional model above uses convolutions with stride 2 to reduce the dimensionality. Replace the strides by a max pooling operation (`nn.max_pool()`) of stride 2 and kernel size 2.---
# TODO
_____no_output_____
Apache-2.0
previous_training/udacity/4_convolutions.ipynb
archelogos/smart-live-camera
---Problem 2---------Try to get the best performance you can using a convolutional net. Look for example at the classic [LeNet5](http://yann.lecun.com/exdb/lenet/) architecture, adding Dropout, and/or adding learning rate decay.---
batch_size = 16 patch_size = 3 depth = 16 num_hidden = 705 num_hidden_last = 205 graph = tf.Graph() with graph.as_default(): # Input data. tf_train_dataset = tf.placeholder( tf.float32, shape=(batch_size, image_size, image_size, num_channels)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size,...
Initialized Minibatch loss at step 0 : 2.30135 Minibatch accuracy: 6.2% Validation accuracy: 11.4% Thu Jul 14 19:41:34 2016 Minibatch loss at step 500 : 0.77839 Minibatch accuracy: 87.5% Validation accuracy: 85.0% Thu Jul 14 19:42:07 2016 Minibatch loss at step 1000 : 0.239152 Minibatch accuracy: 93.8% Validation accur...
Apache-2.0
previous_training/udacity/4_convolutions.ipynb
archelogos/smart-live-camera
STEP 4 - Making DRL PySC2 Agent
%load_ext autoreload %autoreload 2 import sys; sys.path.append('..') ### unfortunately, PySC2 uses Abseil, which treats python code as if its run like an app # This does not play well with jupyter notebook # So we will need to monkeypatch sys.argv import sys #sys.argv = ["python", "--map", "AbyssalReef"] sys.argv = [...
_____no_output_____
MIT
s10336/STEP4-making-drl-pysc2-agent.ipynb
parksurk/skcc-drl-sc2-course-2020_1st
0. Runnning 'Agent code' on jupyter notebook
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
_____no_output_____
MIT
s10336/STEP4-making-drl-pysc2-agent.ipynb
parksurk/skcc-drl-sc2-course-2020_1st
1. Creating a PySC2 Agent with Raw Actions & Observations![StarCraft2 PySC2 interfaces](./images/StarCraft2_PySC2_interfaces.png)ref : https://on-demand.gputechconf.com/gtc/2018/presentation/s8739-machine-learning-with-starcraft-II.pdf 1st, Rendered* Decomposed : - Screen, minimap, resources, available actions* S...
import random import time import math import os.path import numpy as np import pandas as pd from collections import deque import pickle from pysc2.agents import base_agent from pysc2.env import sc2_env from pysc2.lib import actions, features, units, upgrades from absl import app import torch from torch.utils.tensorb...
NaiveMultiLayerPerceptron( (hidden_act_func): ReLU() (out_act_func): Identity() (layers): ModuleList( (0): Linear(in_features=10, out_features=20, bias=True) (1): ReLU() (2): Linear(in_features=20, out_features=12, bias=True) (3): ReLU() (4): Linear(in_features=12, out_features=1, bias=True) ...
MIT
s10336/STEP4-making-drl-pysc2-agent.ipynb
parksurk/skcc-drl-sc2-course-2020_1st
Q-update 공식 1. Online Q-learning![Online Q-learning](./images/q-update-experience-replay.png) 2. Online Q-learning with Function Approximation![Online Q-learning with Function Approximation](./images/q-update-function-approximation.png) 3. Batch Q-learning with Function Approximation & Experience Replay![Batch Q-learn...
from random import sample class ExperienceReplayMemory: def __init__(self, max_size): # deque object that we've used for 'episodic_memory' is not suitable for random sampling # here, we instead use a fix-size array to implement 'buffer' self.buffer = [None] * max_size self.max_size...
_____no_output_____
MIT
s10336/STEP4-making-drl-pysc2-agent.ipynb
parksurk/skcc-drl-sc2-course-2020_1st
Moving target problem 1. Function Approximation을 사용하지 않는 Q-learning 의 경우 : 특정한 Q(s,a) update가 다른 Q(s,a)에 영향을 주지 않는다.![Moving target Q-learning](./images/moving-target_q-learing_case.png) 2. Function Approximation을 사용하는 Q-learnig 의 경우 : 특정한 Q(s,a) update가 다른 Q(s,a)에 영향을 준다.![Moving target Q-learning with Function Appro...
import torch import torch.nn as nn import numpy as np import random class DQN(nn.Module): def __init__(self, state_dim: int, action_dim: int, qnet: nn.Module, qnet_target: nn.Module, lr: float, gamma: float, ...
_____no_output_____
MIT
s10336/STEP4-making-drl-pysc2-agent.ipynb
parksurk/skcc-drl-sc2-course-2020_1st
Action 함수 정의
class TerranAgentWithRawActsAndRawObs(base_agent.BaseAgent): # actions 추가 및 함수 정의(hirerachy하게) actions = ("do_nothing", "train_scv", "harvest_minerals", "harvest_gas", "build_commandcenter", "build_refinery", ...
_____no_output_____
MIT
s10336/STEP4-making-drl-pysc2-agent.ipynb
parksurk/skcc-drl-sc2-course-2020_1st
Hyperparameter하이퍼파라미터는 심층강화학습 알고리즘에서 성능에 매우 큰 영향을 미칩니다.이 실험에 쓰인 하이퍼파라미터는 https://github.com/chucnorrisful/dqn 실험에서 제안된 값들을 참고하였습니다.- self.s_dim = 21- self.a_dim = 6- self.lr = 1e-4 * 1- self.batch_size = 32- self.gamma = 0.99- self.memory_size = 200000- self.eps_max = 1.0- self.eps_min = 0.01- self.epsilon = 1.0- self...
class TerranRLAgentWithRawActsAndRawObs(TerranAgentWithRawActsAndRawObs): def __init__(self): super(TerranRLAgentWithRawActsAndRawObs, self).__init__() self.s_dim = 21 self.a_dim = 19 self.lr = 1e-4 * 1 self.batch_size = 32 self.gamma = 0.99 self.mem...
I0922 23:23:02.756312 4616515008 sc_process.py:135] Launching SC2: /Applications/StarCraft II/Versions/Base81102/SC2.app/Contents/MacOS/SC2 -listen 127.0.0.1 -port 19112 -dataDir /Applications/StarCraft II/ -tempDir /var/folders/r1/x6k135_915z463fc7lc4hkp40000gn/T/sc-m9gntgxu/ -displayMode 0 -windowwidth 640 -windowhei...
MIT
s10336/STEP4-making-drl-pysc2-agent.ipynb
parksurk/skcc-drl-sc2-course-2020_1st
[Winning rate graph]
!pip install matplotlib import pickle import numpy as np import matplotlib.pyplot as plt %matplotlib inline SCORE_FILE = 'rlagent_with_vanilla_dqn_score' with open(SCORE_FILE + '.txt', "rb") as fp: scores = pickle.load(fp) np_scores = np.array(scores) np_scores # plot the scores fig = plt.figure() ax = fig.add_sub...
_____no_output_____
MIT
s10336/STEP4-making-drl-pysc2-agent.ipynb
parksurk/skcc-drl-sc2-course-2020_1st
Copyright 2018 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
Custom training: basics Run in Google Colab View source on GitHub In the previous tutorial we covered the TensorFlow APIs for automatic differentiation, a basic building block for machine learning.In this tutorial we will use the TensorFlow primitives introduced in the prior tutorials to do some simple ...
from __future__ import absolute_import, division, print_function, unicode_literals try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass import tensorflow.compat.v1 as tf
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
VariablesTensors in TensorFlow are immutable stateless objects. Machine learning models, however, need to have changing state: as your model trains, the same code to compute predictions should behave differently over time (hopefully with a lower loss!). To represent this state which needs to change over the course of ...
# Using python state x = tf.zeros([10, 10]) x += 2 # This is equivalent to x = x + 2, which does not mutate the original # value of x print(x)
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
TensorFlow, however, has stateful operations built in, and these are often more pleasant to use than low-level Python representations of your state. To represent weights in a model, for example, it's often convenient and efficient to use TensorFlow variables.A Variable is an object which stores a value and, when used i...
v = tf.Variable(1.0) assert v.numpy() == 1.0 # Re-assign the value v.assign(3.0) assert v.numpy() == 3.0 # Use `v` in a TensorFlow operation like tf.square() and reassign v.assign(tf.square(v)) assert v.numpy() == 9.0
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
Computations using Variables are automatically traced when computing gradients. For Variables representing embeddings TensorFlow will do sparse updates by default, which are more computation and memory efficient.Using Variables is also a way to quickly let a reader of your code know that this piece of state is mutable....
class Model(object): def __init__(self): # Initialize variable to (5.0, 0.0) # In practice, these should be initialized to random values. self.W = tf.Variable(5.0) self.b = tf.Variable(0.0) def __call__(self, x): return self.W * x + self.b model = Model() assert model(3.0).numpy() == 15.0
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
Define a loss functionA loss function measures how well the output of a model for a given input matches the desired output. Let's use the standard L2 loss.
def loss(predicted_y, desired_y): return tf.reduce_mean(tf.square(predicted_y - desired_y))
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
Obtain training dataLet's synthesize the training data with some noise.
TRUE_W = 3.0 TRUE_b = 2.0 NUM_EXAMPLES = 1000 inputs = tf.random_normal(shape=[NUM_EXAMPLES]) noise = tf.random_normal(shape=[NUM_EXAMPLES]) outputs = inputs * TRUE_W + TRUE_b + noise
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
Before we train the model let's visualize where the model stands right now. We'll plot the model's predictions in red and the training data in blue.
import matplotlib.pyplot as plt plt.scatter(inputs, outputs, c='b') plt.scatter(inputs, model(inputs), c='r') plt.show() print('Current loss: '), print(loss(model(inputs), outputs).numpy())
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
Define a training loopWe now have our network and our training data. Let's train it, i.e., use the training data to update the model's variables (`W` and `b`) so that the loss goes down using [gradient descent](https://en.wikipedia.org/wiki/Gradient_descent). There are many variants of the gradient descent scheme that...
def train(model, inputs, outputs, learning_rate): with tf.GradientTape() as t: current_loss = loss(model(inputs), outputs) dW, db = t.gradient(current_loss, [model.W, model.b]) model.W.assign_sub(learning_rate * dW) model.b.assign_sub(learning_rate * db)
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
Finally, let's repeatedly run through the training data and see how `W` and `b` evolve.
model = Model() # Collect the history of W-values and b-values to plot later Ws, bs = [], [] epochs = range(10) for epoch in epochs: Ws.append(model.W.numpy()) bs.append(model.b.numpy()) current_loss = loss(model(inputs), outputs) train(model, inputs, outputs, learning_rate=0.1) print('Epoch %2d: W=%1.2f b=...
_____no_output_____
Apache-2.0
site/en/r1/tutorials/eager/custom_training.ipynb
PhilipMay/docs
ENGR 1330 Exam 1 Sec 003/004 Fall 2020Take Home Portion of Exam 1 Full name R: HEX: ENGR 1330 Exam 1 Sec 003/004 Date: Question 1 (1 pts):Run the cell below, and leave the results in your notebook (Windows users may get an error, leave the error in place)
#### RUN! the Cell #### import sys ! hostname ! whoami print(sys.executable) # OK if generates an exception message on Windows machines
atomickitty.aws compthink /opt/conda/envs/python/bin/python
CC0-1.0
5-ExamProblems/.src/EX1-F2020-Solution/.ipynb_checkpoints/Exam1-Deploy-Solutions-checkpoint.ipynb
dustykat/engr-1330-psuedo-course
Question 2 (9 pts):- __When it is 8:00 in Lubbock,__ - __It is 9:00 in New York__ - __It is 14:00 in London__ - __It is 15:00 in Cairo__ - __It is 16:00 in Istanbul__ - __It is 19:00 in Hyderabad__ - __It is 22:00 in Tokyo__ __Write a function that reports the time in New York, London, Cairo, Istanb...
def LBBtime(): try: LBK = int(input('What hour is it in Lubbock?- Please enter a number from 0 to 23')) if LBK>23: print('Please Enter A Number from 00 to 23') if LBK<23 and LBK>=0: if LBK+1>23: print("Time in New York is",(LBK+1)-24,":00") ...
What hour is it in Lubbock?- Please enter a number from 0 to 23 0
CC0-1.0
5-ExamProblems/.src/EX1-F2020-Solution/.ipynb_checkpoints/Exam1-Deploy-Solutions-checkpoint.ipynb
dustykat/engr-1330-psuedo-course
Question 3 (28 pts): Follow the steps below. Add comments to your script and signify when each step and each task is done. *hint: For this problem you will need the numpy and pandas libraries.- __STEP1: There are 8 digits in your R. Define a 2x4 array with these 8 digits, name it "Rarray", and print it__- __STEP2: Fin...
# Code and Run your solution here: print('#Step0: Install Dependencies') import numpy as np import pandas as pd print('#Step1: Create the array') Rarray = np.array([[1,6,7,4],[5,2,3,8]]) #Define Rarray print(Rarray) print('#Step2: find max and its position ') print(np.max(Rarray)) #Find the maximum Value ...
#Step0: Install Dependencies #Step1: Create the array [[1 6 7 4] [5 2 3 8]] #Step2: find max and its position 8 7 #Step3: Sort the array [[1 4 6 7] [2 3 5 8]] #Step4: Create the double array - manual entry [[1 6 7 4] [5 2 3 8] [1 4 6 7] [2 3 5 8]] #Step5: Slice the array [[6 7 4] [2 3 8] [4 6 7] [3 5 8]] #Step...
CC0-1.0
5-ExamProblems/.src/EX1-F2020-Solution/.ipynb_checkpoints/Exam1-Deploy-Solutions-checkpoint.ipynb
dustykat/engr-1330-psuedo-course
Problem 4 (32 pts)Graphing Functions Special Functions Consider the two functions listed below:\begin{equation}f(x) = e^{-\alpha x}\label{eqn:fofx}\end{equation}\begin{equation}g(x) = \gamma sin(\beta x)\label{eqn:gofx}\end{equation}Prepare a plot of the two functions on the same graph. Use the values in Table below ...
# Define the first function f(x,alpha), test the function using your by hand answer # Define the first function f(x,alpha), test the function using your by hand answer def f(x,alpha): import math f = math.exp(-1.0*alpha*x) return f f(1,0.5) # Define the second function g(x,beta,gamma), test the function us...
f(x) - g(x) = -0.3523204174957726 at x = 1 f(x) - g(x) = -1.3150625284443507 at x = 2
CC0-1.0
5-ExamProblems/.src/EX1-F2020-Solution/.ipynb_checkpoints/Exam1-Deploy-Solutions-checkpoint.ipynb
dustykat/engr-1330-psuedo-course
Bonus Problem 1. Extra Credit (You must complete the regular problems)!__create a class to compute the average grade (out of 10) of the students based on their grades in Quiz1, Quiz2, the Mid-term, Quiz3, and the Final exam.__| Student Name | Quiz 1 | Quiz 2 | Mid-term | Quiz 3 | Final Exam || -----...
#Code and run your solution here: #Suggested Solution: class Hogwarts: """This class calculates the average grade of the students""" def __init__(self, Name,Quiz1,Quiz2,MidTerm,Quiz3,Final): self.Name = Name self.Quiz1 = Quiz1 self.Quiz2 = Quiz2 self.MidTerm = MidTerm s...
Harry 8.8 Ron 7.8 Hermione 9.8 Draco 8.2 Luna 7.0 {'Harry': 8.8, 'Ron': 7.8, 'Hermione': 9.8, 'Draco': 8.2, 'Luna': 7.0}
CC0-1.0
5-ExamProblems/.src/EX1-F2020-Solution/.ipynb_checkpoints/Exam1-Deploy-Solutions-checkpoint.ipynb
dustykat/engr-1330-psuedo-course
Bonus 2 Extra credit (You must complete the regular problems)! Write the VOLUME Function to compute the volume of Cylinders, Spheres, Cones, and Rectangular Boxes. This function should:- First, ask the user about __the shape of the object__ of interest using this statement:**"Please choose the shape of the object. Ent...
#Code and Run your solution here #Suggested Solution: import numpy as np # import NumPy: for large, multi-dimensional arrays and matrices, along with high-level mathematical functions to operate on these arrays. pi = np.pi #pi value from the np package def VOLUME(): try: UI = input('Please choose the sh...
Please choose the shape of the object. Enter 1 for "Cylinder", 2 for "Sphere", 3 for "Cone", or 4 for "Rectangular Box" 1 Please enter the radius of the Cylinder 1 Please enter the height of the Cylinder 1
CC0-1.0
5-ExamProblems/.src/EX1-F2020-Solution/.ipynb_checkpoints/Exam1-Deploy-Solutions-checkpoint.ipynb
dustykat/engr-1330-psuedo-course
转置卷积:label:`sec_transposed_conv`到目前为止,我们所见到的卷积神经网络层,例如卷积层( :numref:`sec_conv_layer`)和汇聚层( :numref:`sec_pooling`),通常会减少下采样输入图像的空间维度(高和宽)。然而如果输入和输出图像的空间维度相同,在以像素级分类的语义分割中将会很方便。例如,输出像素所处的通道维可以保有输入像素在同一位置上的分类结果。为了实现这一点,尤其是在空间维度被卷积神经网络层缩小后,我们可以使用另一种类型的卷积神经网络层,它可以增加上采样中间层特征图的空间维度。在本节中,我们将介绍*转置卷积*(transposed convolution) :ci...
from mxnet import init, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np()
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
基本操作让我们暂时忽略通道,从基本的转置卷积开始,设步幅为1且没有填充。假设我们有一个$n_h \times n_w$的输入张量和一个$k_h \times k_w$的卷积核。以步幅为1滑动卷积核窗口,每行$n_w$次,每列$n_h$次,共产生$n_h n_w$个中间结果。每个中间结果都是一个$(n_h + k_h - 1) \times (n_w + k_w - 1)$的张量,初始化为0。为了计算每个中间张量,输入张量中的每个元素都要乘以卷积核,从而使所得的$k_h \times k_w$张量替换中间张量的一部分。请注意,每个中间张量被替换部分的位置与输入张量中元素的位置相对应。最后,所有中间结果相加以获得最终结果。例如, :n...
def trans_conv(X, K): h, w = K.shape Y = np.zeros((X.shape[0] + h - 1, X.shape[1] + w - 1)) for i in range(X.shape[0]): for j in range(X.shape[1]): Y[i: i + h, j: j + w] += X[i, j] * K return Y
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
与通过卷积核“减少”输入元素的常规卷积(在 :numref:`sec_conv_layer`中)相比,转置卷积通过卷积核“广播”输入元素,从而产生大于输入的输出。我们可以通过 :numref:`fig_trans_conv`来构建输入张量`X`和卷积核张量`K`从而[**验证上述实现输出**]。此实现是基本的二维转置卷积运算。
X = np.array([[0.0, 1.0], [2.0, 3.0]]) K = np.array([[0.0, 1.0], [2.0, 3.0]]) trans_conv(X, K)
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
或者,当输入`X`和卷积核`K`都是四维张量时,我们可以[**使用高级API获得相同的结果**]。
X, K = X.reshape(1, 1, 2, 2), K.reshape(1, 1, 2, 2) tconv = nn.Conv2DTranspose(1, kernel_size=2) tconv.initialize(init.Constant(K)) tconv(X)
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
[**填充、步幅和多通道**]与常规卷积不同,在转置卷积中,填充被应用于的输出(常规卷积将填充应用于输入)。例如,当将高和宽两侧的填充数指定为1时,转置卷积的输出中将删除第一和最后的行与列。
tconv = nn.Conv2DTranspose(1, kernel_size=2, padding=1) tconv.initialize(init.Constant(K)) tconv(X)
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
在转置卷积中,步幅被指定为中间结果(输出),而不是输入。使用 :numref:`fig_trans_conv`中相同输入和卷积核张量,将步幅从1更改为2会增加中间张量的高和权重,因此输出张量在 :numref:`fig_trans_conv_stride2`中。![卷积核为$2\times 2$,步幅为2的转置卷积。阴影部分是中间张量的一部分,也是用于计算的输入和卷积核张量元素。](../img/trans_conv_stride2.svg):label:`fig_trans_conv_stride2`以下代码可以验证 :numref:`fig_trans_conv_stride2`中步幅为2的转置卷积的输出。
tconv = nn.Conv2DTranspose(1, kernel_size=2, strides=2) tconv.initialize(init.Constant(K)) tconv(X)
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
对于多个输入和输出通道,转置卷积与常规卷积以相同方式运作。假设输入有$c_i$个通道,且转置卷积为每个输入通道分配了一个$k_h\times k_w$的卷积核张量。当指定多个输出通道时,每个输出通道将有一个$c_i\times k_h\times k_w$的卷积核。同样,如果我们将$\mathsf{X}$代入卷积层$f$来输出$\mathsf{Y}=f(\mathsf{X})$,并创建一个与$f$具有相同的超参数、但输出通道数量是$\mathsf{X}$中通道数的转置卷积层$g$,那么$g(Y)$的形状将与$\mathsf{X}$相同。下面的示例可以解释这一点。
X = np.random.uniform(size=(1, 10, 16, 16)) conv = nn.Conv2D(20, kernel_size=5, padding=2, strides=3) tconv = nn.Conv2DTranspose(10, kernel_size=5, padding=2, strides=3) conv.initialize() tconv.initialize() tconv(conv(X)).shape == X.shape
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
[**与矩阵变换的联系**]:label:`subsec-connection-to-mat-transposition`转置卷积为何以矩阵变换命名呢?让我们首先看看如何使用矩阵乘法来实现卷积。在下面的示例中,我们定义了一个$3\times 3$的输入`X`和$2\times 2$卷积核`K`,然后使用`corr2d`函数计算卷积输出`Y`。
X = np.arange(9.0).reshape(3, 3) K = np.array([[1.0, 2.0], [3.0, 4.0]]) Y = d2l.corr2d(X, K) Y
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
接下来,我们将卷积核`K`重写为包含大量0的稀疏权重矩阵`W`。权重矩阵的形状是($4$,$9$),其中非0元素来自卷积核`K`。
def kernel2matrix(K): k, W = np.zeros(5), np.zeros((4, 9)) k[:2], k[3:5] = K[0, :], K[1, :] W[0, :5], W[1, 1:6], W[2, 3:8], W[3, 4:] = k, k, k, k return W W = kernel2matrix(K) W
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
逐行连结输入`X`,获得了一个长度为9的矢量。然后,`W`的矩阵乘法和向量化的`X`给出了一个长度为4的向量。重塑它之后,可以获得与上面的原始卷积操作所得相同的结果`Y`:我们刚刚使用矩阵乘法实现了卷积。
Y == np.dot(W, X.reshape(-1)).reshape(2, 2)
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
同样,我们可以使用矩阵乘法来实现转置卷积。在下面的示例中,我们将上面的常规卷积$2 \times 2$的输出`Y`作为转置卷积的输入。想要通过矩阵相乘来实现它,我们只需要将权重矩阵`W`的形状转置为$(9, 4)$。
Z = trans_conv(Y, K) Z == np.dot(W.T, Y.reshape(-1)).reshape(3, 3)
_____no_output_____
MIT
submodules/resource/d2l-zh/mxnet/chapter_computer-vision/transposed-conv.ipynb
alphajayGithub/ai.online
[作業重點]清楚了解 L1, L2 的意義與差異為何,並了解 LASSO 與 Ridge 之間的差異與使用情境 作業 請閱讀相關文獻,並回答下列問題[脊回歸 (Ridge Regression)](https://blog.csdn.net/daunxx/article/details/51578787)[Linear, Ridge, Lasso Regression 本質區別](https://www.zhihu.com/question/38121173) Q1: LASSO 回歸可以被用來作為 Feature selection 的工具,請了解 LASSO 模型為什麼可用來作 Feature selection A1: ...
_____no_output_____
MIT
Day_039_HW.ipynb
semishen/ML100Days
PRESENTACIÓN **nombre:** Gabriela Ivonne Montoya Ortiz - **Profesión**: **Estudiante** - **Edad**: 19 años - **Pasa tiempos**: bailar diferentes estilos, leer, ver peliculas. - **Educación**: colegio salesiano anahuac revolucion Foto: Hola Ecuaciones... $f(x) = \sin(x)$
import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.linspace(-2*np.pi, 2*np.pi, 100) plt.figure(figsize = (4,3)) plt.plot(x, np.sin(x));
_____no_output_____
MIT
Untitled.ipynb
Gabs0102/Mi-primer-Proyecto
$$\frac{df}{dx} = -\nabla\psi $$ ** Minichatbot, Gaby **
q1 = "¿Cómo te llamas?" q2 = "¿Qué edad tienes?" q3 = "¿Donde vienes?" q4 = "¿Sexo?" qs = [q1, q2, q3, q4] qs ans1 = "Mucho gusto, me llamo Gaby. " ans2 = "Legal!" ans3 = "Orale, muy bien." ans4 = "NO." anss = [ans1, ans2, ans3, ans4] anss def chatGaby(): print("Hola, bienvenite!, tengo algunas preguntas para ti.")...
_____no_output_____
MIT
Untitled.ipynb
Gabs0102/Mi-primer-Proyecto
**LSTM - Time Series Prediction** **Importing libraries**
import pandas import matplotlib.pyplot as plt import numpy import math from tqdm import tqdm from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.layers import LSTM from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error #...
_____no_output_____
MIT
time-series-prediction.ipynb
srivarshan-s/LSTM-Trials
**Load the data**
! rm /content/airline-passengers.csv ! wget https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv dataset = pandas.read_csv('airline-passengers.csv', usecols=[1], engine='python') plt.plot(dataset) plt.show() # convert an array of values into a dataset matrix def create_dataset(dataset, loo...
_____no_output_____
MIT
time-series-prediction.ipynb
srivarshan-s/LSTM-Trials
**LSTM Network for Regression**
# load the dataset dataframe = pandas.read_csv('airline-passengers.csv', usecols=[1], engine='python') dataset = dataframe.values dataset = dataset.astype('float32') # normalize the dataset scaler = MinMaxScaler(feature_range=(0, 1)) dataset = scaler.fit_transform(dataset) # split into train and test sets train_size = ...
_____no_output_____
MIT
time-series-prediction.ipynb
srivarshan-s/LSTM-Trials