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
Check how to create it:* pd.DataFrame().from_records()* pd.DataFrame().from_dict()
pd.DataFrame.from_records(some_data) pd.DataFrame.from_dict()
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
This data set is too big for github, download it from [here](https://www.kaggle.com/START-UMD/gtd). You will need to register on Kaggle first.
df = pd.read_csv('globalterrorismdb_0718dist.csv', encoding='ISO-8859-1')
/opt/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3145: DtypeWarning: Columns (4,6,31,33,61,62,63,76,79,90,92,94,96,114,115,121) have mixed types.Specify dtype option on import or set low_memory=False. has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Let's explore the second set of data. How many rows and columns are there?
df.shape
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
General information on this data set:
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 181691 entries, 0 to 181690 Columns: 135 entries, eventid to related dtypes: float64(55), int64(22), object(58) memory usage: 187.1+ MB
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Let's take a look at the dataset information. In .info (), you can pass additional parameters, including:* **verbose**: whether to print information about the DataFrame in full (if the table is very large, then some information may be lost);* **memory_usage**: whether to print memory consumption (the default is True, b...
df.describe() df.describe(include=['object', 'int'])
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
The describe method shows the basic statistical characteristics of the data for each numeric feature (int64 and float64 types): the number of non-missing values, mean, standard deviation, range, median, 0.25 and 0.75 quartiles. How to look only at the column names, index:
df.columns df.index
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
How to look at the first 10 lines?
df.head(10)
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
How to look at the last 15 lines?
df.tail(15)
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
How to request only one particular line (by counting lines)?
df.head(4) #the first 3 lines df.iloc[:3] # the number of rows by counting them
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
How to request only one particular line by its index?
# the first lines till the row with the index 3 df.loc[:3] # 3 is treated as an index
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Look only at the unique values of some columns.
list(df['city'].unique())
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
How many unique values there are in ```city``` column? = On how many cities this data set hold information on terrorist attacks?
df['city'].nunique()
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
In what years did the largest number of terrorist attacks occur (according to only to this data set)?
df['iyear'].value_counts().head(5) df['iyear'].value_counts()[:5]
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
How we can sort all data by year in descending order?
df['iyear'].sort_values() df.sort_values(by='iyear', ascending=False)
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Which data types we have in each column?
dict(df.dtypes)
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
How to check the missing values?
df df.isna() dict(df.isna().sum()) df.dropna(axis=1) df.head(5) df['attacktype2'].min() df['attacktype2'].max() df['attacktype2'].mode() df['attacktype2'].median() df['attacktype2'].mean() df['attacktype2'].fillna(df['attacktype2'].mode())
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Let's delete a column ```approxdate``` from this data set, because it contains a lot of missing values:
df.drop(['approxdate'], axis=1, inplace=True)
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Create a new variable ```casualties``` by summing up the value in ```Killed``` and ```Wounded```.
set(df.columns) df['casualties'] = df['nwound'] + df['nkill'] df.head()
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Rename a column ```iyear``` to ```Year```:
df.rename({'iyear' : 'Year'}, axis='columns', inplace=True) df
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
How to drop all missing values? Replace these missing values with others?
df.dropna(inplace=True)
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
**Task!** Use a function to replace NaNs (=missing values) to a string 'None' in ```related``` column
# TODO
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
For the selected columns show its mean, median (and/or mode).
df['Year'].mean()
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Min, max and sum:
df['Year'].sum() sum(df['Year']) max('word')
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Filter the dataset to look only at the attacks after 2015 year
df[df.Year > 2015]
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
What if we have several conditions? Try it out
df[(df.Year > 2015) & (df.extended == 1)]
_____no_output_____
MIT
week8/in_class_notebooks/week8-192.ipynb
anamarina/Data_Analysis_in_Python
Tips Introduction:This exercise was created based on the tutorial and documentation from [Seaborn](https://stanford.edu/~mwaskom/software/seaborn/index.html) The dataset being used is tips from Seaborn. Step 1. Import the necessary libraries:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/07_Visualization/Tips/tips.csv). Step 3. Assign it to a variable called tips
url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/07_Visualization/Tips/tips.csv' tips = pd.read_csv(url, index_col=0) tips.reset_index() tips
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 4. Delete the Unnamed 0 column
# already done
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 5. Plot the total_bill column histogram
sns.set(style='white') sns.set_context(rc = {'patch.linewidth': 2.0}) ax = sns.histplot(tips['total_bill'], kde=True, stat='density') ax.set(xlabel='Value', ylabel='Frequency') ax.set_title('Total Bill', size=15) sns.despine(); # Original solution: # create histogram ttbill = sns.distplot(tips.total_bill); # set la...
/anaconda3/lib/python3.7/site-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms). war...
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 6. Create a scatter plot presenting the relationship between total_bill and tip
sns.jointplot(x=tips['total_bill'], y=tips['tip'], xlim=(0, 60), ylim=(0, 12));
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 7. Create one image with the relationship of total_bill, tip and size. Hint: It is just one function.
sns.pairplot(data=tips[['total_bill', 'tip', 'size']]); # Original solution: # # sns.pairplot(tips)
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 8. Present the relationship between days and total_bill value
sns.set_style('whitegrid') plt.figure(figsize=(8, 6)) ax = sns.stripplot(x=tips['day'], y=tips['total_bill']) ax.set_ylim(0, 60); # Original solution: # # sns.stripplot(x = "day", y = "total_bill", data = tips, jitter = True); # What a "jitter" is (for demonstration purposes): sns.stripplot(x = "day", y = "total_bill"...
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 9. Create a scatter plot with the day as the y-axis and tip as the x-axis, differ the dots by sex
sns.set_style("whitegrid") plt.figure(figsize=(8, 6)) ax = sns.scatterplot(data=tips, x='tip', y='day', hue='sex'); ax.yaxis.grid(False) ax.legend(title='Sex', framealpha = 1, edgecolor='w'); # Original solution: # # sns.stripplot(x = "tip", y = "day", hue = "sex", data = tips, jitter = True);
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 10. Create a box plot presenting the total_bill per day differetiation the time (Dinner or Lunch)
plt.figure(figsize=(12, 6)) sns.boxplot(data=tips, x='day', y='total_bill', hue='time');
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 11. Create two histograms of the tip value based for Dinner and Lunch. They must be side by side.
sns.set_style('ticks') g = sns.FacetGrid(data=tips, col='time') g.map(sns.histplot, 'tip', bins=10) g.set(xlim=(0, 12), ylim=(0, 60), xticks=range(0, 13, 2), yticks=range(0, 61, 10)); sns.despine(); # Original solution: # # # better seaborn style # sns.set(style = "ticks") # # creates FacetGrid # g = sns.FacetGrid(tip...
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Step 12. Create two scatterplots graphs, one for Male and another for Female, presenting the total_bill value and tip relationship, differing by smoker or no smoker They must be side by side.
g = sns.FacetGrid(data=tips, col='sex') g.map_dataframe(sns.scatterplot, x='total_bill', y='tip', hue='smoker') g.add_legend(title='Smoker') g.set_axis_labels('Total bill', 'Tip') g.set(xlim=(0, 60), ylim=(0, 12), xticks=range(0, 61, 10), yticks=range(0, 13, 2)); # Original solution: # # g = sns.FacetGrid(tips, col =...
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
BONUS: Create your own question and answer it using a graph.
g = sns.FacetGrid(data=tips, col='sex') g.map(sns.kdeplot, 'total_bill'); sns.kdeplot(tips['total_bill'], hue=tips['sex']); sns.histplot(data=tips, x='total_bill', hue='sex'); tips.groupby('sex')[['total_bill']].sum() tips.groupby('sex')[['total_bill']].count() males = tips[tips['sex'] == 'Male'].sample(87) males.head(...
_____no_output_____
BSD-3-Clause
07_Visualization/Tips/Exercises.ipynb
alexkataev/pandas_exercises
Model_2_Linear_Regression
# Update sklearn to prevent version mismatches !pip install sklearn --upgrade import pandas as pd
_____no_output_____
ADSL
starter_code/.ipynb_checkpoints/Model_2_Logistic_Regression-checkpoint.ipynb
bandipara/machine-learning-challenge
Read the CSV and Perform Basic Data Cleaning
df = pd.read_csv("exoplanet_data.csv") # Drop the null columns where all values are null df = df.dropna(axis='columns', how='all') # Drop the null rows df = df.dropna() df.head()
_____no_output_____
ADSL
starter_code/.ipynb_checkpoints/Model_2_Logistic_Regression-checkpoint.ipynb
bandipara/machine-learning-challenge
Create a Train Test Split
from sklearn.model_selection import train_test_split y=df['koi_disposition'] X=df.drop(columns=['koi_disposition']) X_train, X_test, y_train, y_test = train_test_split(X,y, random_state=1, stratify=y) X_train.head()
_____no_output_____
ADSL
starter_code/.ipynb_checkpoints/Model_2_Logistic_Regression-checkpoint.ipynb
bandipara/machine-learning-challenge
Preprocessing
from sklearn.preprocessing import MinMaxScaler X_scaler = MinMaxScaler().fit(X_train) X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test)
_____no_output_____
ADSL
starter_code/.ipynb_checkpoints/Model_2_Logistic_Regression-checkpoint.ipynb
bandipara/machine-learning-challenge
Linear Regression
from sklearn.linear_model import LogisticRegression model1 = LogisticRegression() model1.fit(X_train_scaled, y_train) print(f'Train = {model1.score(X_train_scaled, y_train)}') print(f'Test = {model1.score(X_test_scaled, y_test)}')
Train = 0.8411214953271028 Test = 0.8409610983981693
ADSL
starter_code/.ipynb_checkpoints/Model_2_Logistic_Regression-checkpoint.ipynb
bandipara/machine-learning-challenge
GridSearch
# Create the GridSearchCV model from sklearn.model_selection import GridSearchCV param_grid= {'C':[1,5,10], 'penalty': ['l1','l2']} grid1 = GridSearchCV(model1, param_grid) grid1.fit(X_train_scaled, y_train) print(grid1.best_params_) print(grid1.best_score_)
{'C': 5, 'penalty': 'l1'} 0.8798397863818425
ADSL
starter_code/.ipynb_checkpoints/Model_2_Logistic_Regression-checkpoint.ipynb
bandipara/machine-learning-challenge
Save the model
# save your model by updating "your_name" with your name # and "your_model" with your model variable # be sure to turn this in to BCS # if joblib fails to import, try running the command to install in terminal/git-bash import joblib filename = 'Model_2_Linear_Regression' joblib.dump(grid1, filename)
_____no_output_____
ADSL
starter_code/.ipynb_checkpoints/Model_2_Logistic_Regression-checkpoint.ipynb
bandipara/machine-learning-challenge
MatplotlibMatplotlib is a powerful tool for generating scientific charts of various sorts.This presentation only touches on some features of matplotlib. Please seehttps://jakevdp.github.io/PythonDataScienceHandbook/index.html or many otherresources for a moredetailed discussion,The following notebook shows how to use...
# Import numpy and matplotlib modules %matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') import numpy as np # Get x values between -2 and 2 xs = np.linspace(-2, 2, 21) xs # Compute array of f values for x values fs = 0.2 * xs * xs + np.sin(xs + 1) - 0.5 fs # Make a figure and plot x v...
_____no_output_____
BSD-2-Clause
notebooks/matplotlib teaser.ipynb
flatironinstitute/mfa_jupyter_for_programming
Solving an equationAt what value of $x$ in $[-2, 2]$ does $f(x) = 0$?Let's look at different plots for $f$ using functions to automate things.
def f(x): return 0.2 * x ** 2 + np.sin(x + 1) - 0.5 def plot_f(low_x=-2, high_x=2, number_of_samples=30): # Get an array of x values between low_x and high_x of length number_of_samples xs = FILL_IN_THE_BLANK fs = f(xs) fig = plt.figure() ax = plt.axes() ax.plot(xs, fs); plot_f() plot_...
_____no_output_____
BSD-2-Clause
notebooks/matplotlib teaser.ipynb
flatironinstitute/mfa_jupyter_for_programming
Interactive plotsWe can make an interactive figure where we can try to locate the crossing point visually
from ipywidgets import interact interact(plot_f, low_x=(-2.,2), high_x=(-2.,2)) # But we really should do it using an algorithm like binary search: def find_x_at_zero(some_function, x_below_zero, x_above_zero, iteration_limit=10): """ Given f(x_below_zero)<=0 and f(x_above_zero) >= 0 iteratively use the m...
_____no_output_____
BSD-2-Clause
notebooks/matplotlib teaser.ipynb
flatironinstitute/mfa_jupyter_for_programming
Baseline ModelWe build the baseline model according to our first hypothesis:Lower school attendance leeds to higher target. Import and Setup
import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score import matplotlib.pyplot as plt %matplotlib inline RSEED = 42 # imp...
_____no_output_____
MIT
baseline_model.ipynb
JanaConradi/Zindi_Data_female_households_RSA
`psa_00`: "Percentage listing present school attendance as: Yes" `target`: "Percentage of women head households with income under R19.6k out of total number of households"
sns.lmplot(y='target', x='psa_00', data=df, line_kws={'color': 'red'}) plt.title('Trend between school attendance and percentage of low income') # define feature and target X = df[["psa_00"]] y = df.target
_____no_output_____
MIT
baseline_model.ipynb
JanaConradi/Zindi_Data_female_households_RSA
We have a Test and a Train dataset here in this notebook, but since the Test dataset doesn't have the target we will only use the Train dataset, und make our own test and train data from that. (The target was to predict and submit to the Zindi competition)
# train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=RSEED) # Fit a basic linear regression model on the train data lm = LinearRegression() lm.fit(X_train, y_train) # make predictions on test data y_pred = lm.predict(X_test) # evaluation metrics test print(f"R2: {r...
R2: 0.6123813749418046 RMSE: 6.227259786482336
MIT
baseline_model.ipynb
JanaConradi/Zindi_Data_female_households_RSA
Leaf Rice Disease Detection using ResNet50V2 Architecture ![a.jpg](data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAF7BwgDASIA...
from google.colab import drive drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Importing Libraries
import keras from keras import Sequential from keras.applications import MobileNetV2 from keras.layers import Dense from keras.preprocessing import image import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import seaborn as sns import tensorflow as tf from tensorflow.keras.utils import to_c...
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Target Class
Class=[] for file in os.listdir(directory): Class+=[file] print(Class) print(len(Class))
['blast', 'blight', 'tungro'] 3
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Mapping the Images
Map=[] for i in range(len(Class)): Map = Map+[i] normal_mapping=dict(zip(Class,Map)) reverse_mapping=dict(zip(Map,Class)) def mapper(value): return reverse_mapping[value] set1=[] set2=[] count=0 for i in Class: path=os.path.join(directory,i) t=0 for image in os.listdir(path): if imag...
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Dividing Data and Test
data, dataa=zip(*set1) test, test_test=zip(*set2) label=to_categorical(dataa) X=np.array(data) y=np.array(label) labell=to_categorical(test_test) test=np.array(test) labell=np.array(labell) print(len(y)) print(len(labell))
180 60
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Train Test Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) print(X_train.shape,X_test.shape) print(y_train.shape,y_test.shape)
(144, 100, 100, 3) (36, 100, 100, 3) (144, 3) (36, 3)
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Image Generator
generator = ImageDataGenerator(horizontal_flip=True,vertical_flip=True,rotation_range=20,zoom_range=0.2, width_shift_range=0.2,height_shift_range=0.2,shear_range=0.1,fill_mode="nearest")
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Calling Resnet50V2 Model
from tensorflow.keras.applications import ResNet50V2 resnet50v2 = tf.keras.applications.DenseNet201(input_shape=(100,100,3),include_top=False,weights='imagenet',pooling='avg') resnet50v2.trainable = False
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Making Deep CNN Model
model_input = resnet50v2.input classifier = tf.keras.layers.Dense(128, activation='relu')(resnet50v2.output) classifier = tf.keras.layers.Dense(64, activation='relu')(resnet50v2.output) classifier = tf.keras.layers.Dense(512, activation='relu')(resnet50v2.output) classifier = tf.keras.layers.Dense(128, activation='relu...
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Compiling with ADAM Optimizer and Binary Crossentropy Loss Function
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Fitting the Dataset into Model
history=model.fit(generator.flow(X_train,y_train,batch_size=32),validation_data=(X_test,y_test),epochs=50)
Epoch 1/50 5/5 [==============================] - 19s 1s/step - loss: 0.8226 - accuracy: 0.4309 - val_loss: 0.5457 - val_accuracy: 0.5556 Epoch 2/50 5/5 [==============================] - 1s 99ms/step - loss: 0.4008 - accuracy: 0.8104 - val_loss: 0.3669 - val_accuracy: 0.6667 Epoch 3/50 5/5 [===========================...
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Prediction on Test Set
y_pred=model.predict(X_test) y_pred=np.argmax(y_pred,axis=1) y_test = np.argmax(y_test,axis=1)
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Confusion Matrix
from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test,y_pred) print(cm) plt.subplots(figsize=(15,7)) sns.heatmap(cm, annot= True, linewidth=1, cmap="autumn_r")
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Accuracy
print("Accuracy : ",accuracy_score(y_test,y_pred))
Accuracy : 0.9444444444444444
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Classification Report
print(classification_report(y_test,y_pred))
precision recall f1-score support 0 1.00 1.00 1.00 10 1 0.94 0.94 0.94 16 2 0.90 0.90 0.90 10 accuracy 0.94 36 macro avg 0.95 0.95 0.95 ...
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Loss vs Validation Loss Plot
import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter(y=history.history['loss'], name='Loss', line=dict(color='royalblue', width=3))) fig.add_trace(go.Scatter(y=history.history['val_loss'], name='Validation Loss', line=dict(color='firebrick', wid...
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Accuracy vs Validation Accuracy Plot
fig = go.Figure() fig.add_trace(go.Scatter(y=history.history['accuracy'], name='Accuracy', line=dict(color='royalblue', width=3))) fig.add_trace(go.Scatter(y=history.history['val_accuracy'], name='Validation Accuracy', line=dict(color='firebrick', width=3)))
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Testing on some Random Images
image=load_img("/content/drive/MyDrive/rice/tungro/IMG_0852.jpg",target_size=(100,100)) imagee=load_img("/content/drive/MyDrive/rice/blight/IMG_0936.jpg",target_size=(100,100)) imageee=load_img("/content/drive/MyDrive/rice/blast/IMG_0560.jpg",target_size=(100,100)) imageeee=load_img("/content/drive/MyDrive/rice/blight/...
This Rice Belongs to tungro class This Rice Belongs to blight class This Rice Belongs to blast class This Rice Belongs to blight class This Rice Belongs to tungro class
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Prediction on Different Test Set
print(test.shape) predictionn=model.predict(test) print(predictionn.shape) test_pred=[] for item in predictionn: value=np.argmax(item) test_pred = test_pred + [value]
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Confusion Matrix
from sklearn.metrics import confusion_matrix cm = confusion_matrix(test_test,test_pred) print(cm) plt.subplots(figsize=(15,7)) sns.heatmap(cm, annot= True, linewidth=1, cmap="CMRmap")
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Accuracy
accuracy=accuracy_score(test_test,test_pred) print("Model Accuracy : ",accuracy)
Model Accuracy : 0.9706666666666667
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Classification Report
print(classification_report(test_test,test_pred))
precision recall f1-score support 0 0.95 0.95 0.95 20 1 0.95 1.00 0.98 20 2 1.00 0.95 0.97 20 accuracy 0.97 60 macro avg 0.97 0.97 0.97 ...
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
This Model can Successfully Detects The Disease of a Rice Leaf with an Accuracy of 97%
_____no_output_____
MIT
rice_leaf_disease_detection_with_resnet50v2.ipynb
Chandramouli-Das/Rice-Leaf-Disease-Detection-using-ResNet50V2-Architecture
Stock Prediction using fb ProphetProphet is a procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. It works best with time series that have strong seasonal effects and several seasons of historical data. ...
import pandas as pd import numpy as np import os import matplotlib.pyplot as plt from alpha_vantage.timeseries import TimeSeries from fbprophet import Prophet os.chdir(r'N:\STOCK ADVISOR BOT') ALPHA_VANTAGE_API_KEY = 'XAGC5LBB1SI9RDLW' ts = TimeSeries(key= ALPHA_VANTAGE_API_KEY, output_format='pandas') df_Stock, Stoc...
_____no_output_____
MIT
Stock Prediction/.ipynb_checkpoints/ADS_Stock_Prediction_Prophet_MSFT-checkpoint.ipynb
Chowry000/Stock-Prediction-Using-LSTM
If you want to visualize the individual forecast components, we can use Prophet’s built-in plot_components method like below
prophet_model.plot_components(forcast); forcast.shape forcast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
_____no_output_____
MIT
Stock Prediction/.ipynb_checkpoints/ADS_Stock_Prediction_Prophet_MSFT-checkpoint.ipynb
Chowry000/Stock-Prediction-Using-LSTM
Prediction PerformanceThe performance_metrics utility can be used to compute some useful statistics of the prediction performance (yhat, yhat_lower, and yhat_upper compared to y), as a function of the distance from the cutoff (how far into the future the prediction was). The statistics computed are mean squared error ...
from fbprophet.diagnostics import cross_validation, performance_metrics df_cv = cross_validation(prophet_model, horizon='180 days') df_cv.head() df_cv df_p = performance_metrics(df_cv) df_p.head() df_p from fbprophet.plot import plot_cross_validation_metric fig = plot_cross_validation_metric(df_cv, metric='mape')
_____no_output_____
MIT
Stock Prediction/.ipynb_checkpoints/ADS_Stock_Prediction_Prophet_MSFT-checkpoint.ipynb
Chowry000/Stock-Prediction-Using-LSTM
PROJECT 1 Pseudocode For Project 1 AVOIDS INPUT input word and letters IF letters or words inputed are not forbidden RETURN "TRUE" END
def avoids(): forbidden = list(str(input("Input forbidden letters:"))) sentence = str(input("Input a sentence to be inspected:")).split("") li =[] no = 0 for i in sentence: boo = True for j in forbidden: if j in i: boo = False if boo == False: ...
Input forbidden letters:rtre Input a sentence to be inspected: oj is a GOAT
MIT
WEEK5/WEEK5_PROJECTS.ipynb
ayomideoj/ayomideojikutuCSC102
PROJECT 2 Pseudocode for Project 2 USES ALL INPUT word and strings of letters IF word uses all required letters at least once RETURN "TRUE" ELSE "FALSE" END
def uses_all (word, req): newReq = list(req) li = [] for i in newReq: if i in word: continue else: li.append(i) if len(li) > 0: print(False) else: print(True) print("the required letters",li,"not found",word) uses_all("elegaont","eguon...
False the required letters ['u'] not found elegaont
MIT
WEEK5/WEEK5_PROJECTS.ipynb
ayomideoj/ayomideojikutuCSC102
PROJECT 3 Pseudocode for Project 3 INPUT Jane = "odd" INPUT Jack = "even" IF Jack + Jane = odd number PRINT "Jane wins" ELIF Jack + Jane = even number PRINT "Jack wins" END
import math a = str(input("Player1, enter guess")) b = str(input("Player2, enter guess")) num1 = int(input("Player1, what number did you choose")) num2 = int(input("Player2, what number did you choose")) total = num1 + num2 if total % 2 == 0: nature = "even" else: nature = "odds" if a == nature and b == natu...
Player1, enter guess3 Player2, enter guess4 Player1, what number did you choose3 Player2, what number did you choose4 Nobody wins
MIT
WEEK5/WEEK5_PROJECTS.ipynb
ayomideoj/ayomideojikutuCSC102
PROJECT 4 Pseudocode for Project 4 Velocity, V = D/T Distance, D = 50 Time, T = 2 CALCULATE V END
d = int(input("Enter value of distance")) t = int(input("Enter value of time")) v= d/t print("the care is moving at",v,"miles per hour")
Enter value of distance400 Enter value of time2 the care is moving at 200.0 miles per hour
MIT
WEEK5/WEEK5_PROJECTS.ipynb
ayomideoj/ayomideojikutuCSC102
Linear Models: Multiple variables with interactions Contents1&nbsp;&nbsp;Introduction1.1&nbsp;&nbsp;Chapter aims1.2&nbsp;&nbsp;Formulae with interactions in R2&nbsp;&nbsp;Model 1: Mammalian genome size3&nbsp;&nbsp;Model 2 (ANCOVA): Body Weight in Odonata Introduction Here you will build on your skills in fitting l...
load('../data/mammals.Rdata')
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
If `mammals.Rdata` is missing, just import the data again using `read.csv`. You will then have to add the log C Value column to the imported data frame again.Let's refit the model from [the first multiple explanatory variables chapter](16-MulExpl.ipynb), but including the interaction between trophic level and ground dw...
model <- lm(logCvalue ~ TrophicLevel * GroundDwelling, data= mammals) par(mfrow=c(2,2), mar=c(3,3,1,1), mgp=c(2, 0.8,0)) plot(model)
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
Now, examine the `anova` and `summary` outputs for the model:
anova(model)
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
Compared to the model from [the first multiple explanatory variables chapter](16-MulExpl.ipynb), there is an extra line at the bottom. The top two are the same and show that trophic level and ground dwelling both have independent main effects. The extra lineshows that there is also an interaction between the two. It do...
summary(model)
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
The lines in this output are:1. The reference level (intercept) for non ground dwelling carnivores. (The reference level is decided just by the alphabetic order of the levels)2. Two differences for being in different trophic levels.3. One difference for being ground dwelling4. Two new differences that give specific dif...
# a data frame of combinations of variables gd <- rep(levels(mammals$GroundDwelling), times = 3) print(gd) tl <- rep(levels(mammals$TrophicLevel), each = 2) print(tl) # New data frame predVals <- data.frame(GroundDwelling = gd, TrophicLevel = tl) # predict using the new data frame predVals$predict <- predict(model, ne...
GroundDwelling TrophicLevel predict 1 No Carnivore 0.9589465 2 Yes Carnivore 1.2138170 3 No Herbivore 1.0124594 4 Yes Herbivore 1.2976624 5 No Omnivore 1.1917603 6 Yes Omnivore 1.2990165
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
$\star$ Include and run the code for gererating these predictions in your script.If we plot these data points onto the barplot from [the first multiple explanatory variables chapter](16-MulExpl.ipynb), they now lie exactly on the mean values, because we've allowed for interactions. The triangle on this plot shows the p...
odonata <- read.csv('../data/GenomeSize.csv')
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
$\star$ Now create two new variables in the `odonata` data set called `logGS` and `logBW` containing log genome size and log body weight:
odonata$logGS <- log(odonata$GenomeSize) odonata$logBW <- log(odonata$BodyWeight)
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
The models we fitted [before](12-ExpDesign.ipynb) looked like this: We can now fit the model of body weight as a function of both genome size and suborder:
odonModel <- lm(logBW ~ logGS * Suborder, data = odonata)
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
Again, we'll look at the anova table first:
anova(odonModel)
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
Interpreting this:* There is no significant main effect of log genome size. The *main* effect is the important thing here — genome size is hugely important but does very different things for the two different suborders. If we ignored `Suborder`, there isn't an overall relationship: the average of those two lines is pre...
summary(odonModel)
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
* The first thing to note is that the $r^2$ value is really high. The model explains three quarters (0.752) of the variation in the data.* Next, there are four coefficients: * The intercept is for the first level of `Suborder`, which is Anisoptera (dragonflies). * The next line, for `log genome size`, is the slop...
#get the range of the data: rng <- range(odonata$logGS) #get a sequence from the min to the max with 100 equally spaced values: LogGSForFitting <- seq(rng[1], rng[2], length = 100)
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
Have a look at these numbers:
print(LogGSForFitting)
[1] -0.891598119 -0.873918728 -0.856239337 -0.838559945 -0.820880554 [6] -0.803201163 -0.785521772 -0.767842380 -0.750162989 -0.732483598 [11] -0.714804206 -0.697124815 -0.679445424 -0.661766032 -0.644086641 [16] -0.626407250 -0.608727859 -0.591048467 -0.573369076 -0.555689685 [21] -0.538010293 -0.520330902 -0.5...
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
We can now use the model to predict the values of body weight at each of those points for each of the two suborders:
#get a data frame of new data for the order ZygoVals <- data.frame(logGS = LogGSForFitting, Suborder = "Zygoptera") #get the predictions and standard error ZygoPred <- predict(odonModel, newdata = ZygoVals, se.fit = TRUE) #repeat for anisoptera AnisoVals <- data.frame(logGS = LogGSForFitting, Suborder = "Anisoptera")...
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
We've added `se.fit=TRUE` to the function to get the standard error around the regression lines. Both `AnisoPred` and `ZygoPred` contain predicted values (called `fit`) and standard error values (called `se.fit`) for each of the values in our generated values in `LogGSForFitting` for each of the two suborders.We can ad...
# plot the scatterplot of the data plot(logBW ~ logGS, data = odonata, col = Suborder) # add the predicted lines lines(AnisoPred$fit ~ LogGSForFitting, col = "black") lines(AnisoPred$fit + AnisoPred$se.fit ~ LogGSForFitting, col = "black", lty = 2) lines(AnisoPred$fit - AnisoPred$se.fit ~ LogGSForFitting, col = "black"...
_____no_output_____
MIT
notebooks/17-MulExplInter.ipynb
mathemage/TheMulQuaBio
Optimization MethodsUntil now, you've always used Gradient Descent to update the parameters and minimize the cost. In this notebook, you will learn more advanced optimization methods that can speed up learning and perhaps even get you to a better final value for the cost function. Having a good optimization algorithm ...
import numpy as np import matplotlib.pyplot as plt import scipy.io import math import sklearn import sklearn.datasets from opt_utils import load_params_and_grads, initialize_parameters, forward_propagation, backward_propagation from opt_utils import compute_cost, predict, predict_dec, plot_decision_boundary, load_data...
_____no_output_____
Apache-2.0
Week2/Optimization+methods.ipynb
softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization
1 - Gradient DescentA simple optimization method in machine learning is gradient descent (GD). When you take gradient steps with respect to all $m$ examples on each step, it is also called Batch Gradient Descent. **Warm-up exercise**: Implement the gradient descent update rule. The gradient descent rule is, for $l = ...
# GRADED FUNCTION: update_parameters_with_gd def update_parameters_with_gd(parameters, grads, learning_rate): """ Update parameters using one step of gradient descent Arguments: parameters -- python dictionary containing your parameters to be updated: parameters['W' + str(l)] =...
W1 = [[ 1.63535156 -0.62320365 -0.53718766] [-1.07799357 0.85639907 -2.29470142]] b1 = [[ 1.74604067] [-0.75184921]] W2 = [[ 0.32171798 -0.25467393 1.46902454] [-2.05617317 -0.31554548 -0.3756023 ] [ 1.1404819 -1.09976462 -0.1612551 ]] b2 = [[-0.88020257] [ 0.02561572] [ 0.57539477]]
Apache-2.0
Week2/Optimization+methods.ipynb
softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization
**Expected Output**: **W1** [[ 1.63535156 -0.62320365 -0.53718766] [-1.07799357 0.85639907 -2.29470142]] **b1** [[ 1.74604067] [-0.75184921]] **W2** [[ 0.32171798 -0.25467393 1.46902454] [-2.05617317 -0.31554548 -0.3756023 ] [ 1.140...
# GRADED FUNCTION: random_mini_batches def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0): """ Creates a list of random minibatches from (X, Y) Arguments: X -- input data, of shape (input size, number of examples) Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (...
shape of the 1st mini_batch_X: (12288, 64) shape of the 2nd mini_batch_X: (12288, 64) shape of the 3rd mini_batch_X: (12288, 20) shape of the 1st mini_batch_Y: (1, 64) shape of the 2nd mini_batch_Y: (1, 64) shape of the 3rd mini_batch_Y: (1, 20) mini batch sanity check: [ 0.90085595 -0.7612069 0.2344157 ]
Apache-2.0
Week2/Optimization+methods.ipynb
softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization
**Expected Output**: **shape of the 1st mini_batch_X** (12288, 64) **shape of the 2nd mini_batch_X** (12288, 64) **shape of the 3rd mini_batch_X** (12288, 20) **shape of the 1st mini_batch_Y** (1, 64) ...
# GRADED FUNCTION: initialize_velocity def initialize_velocity(parameters): """ Initializes the velocity as a python dictionary with: - keys: "dW1", "db1", ..., "dWL", "dbL" - values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters. Argumen...
v["dW1"] = [[ 0. 0. 0.] [ 0. 0. 0.]] v["db1"] = [[ 0.] [ 0.]] v["dW2"] = [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] v["db2"] = [[ 0.] [ 0.] [ 0.]]
Apache-2.0
Week2/Optimization+methods.ipynb
softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization
**Expected Output**: **v["dW1"]** [[ 0. 0. 0.] [ 0. 0. 0.]] **v["db1"]** [[ 0.] [ 0.]] **v["dW2"]** [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] **v["db2"]** [[ 0.] [ 0.] [ 0.]] **Exercise**: ...
# GRADED FUNCTION: update_parameters_with_momentum def update_parameters_with_momentum(parameters, grads, v, beta, learning_rate): """ Update parameters using Momentum Arguments: parameters -- python dictionary containing your parameters: parameters['W' + s...
W1 = [[ 1.62544598 -0.61290114 -0.52907334] [-1.07347112 0.86450677 -2.30085497]] b1 = [[ 1.74493465] [-0.76027113]] W2 = [[ 0.31930698 -0.24990073 1.4627996 ] [-2.05974396 -0.32173003 -0.38320915] [ 1.13444069 -1.0998786 -0.1713109 ]] b2 = [[-0.87809283] [ 0.04055394] [ 0.58207317]] v["dW1"] = [[-0.11006192 ...
Apache-2.0
Week2/Optimization+methods.ipynb
softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization
**Expected Output**: **W1** [[ 1.62544598 -0.61290114 -0.52907334] [-1.07347112 0.86450677 -2.30085497]] **b1** [[ 1.74493465] [-0.76027113]] **W2** [[ 0.31930698 -0.24990073 1.4627996 ] [-2.05974396 -0.32173003 -0.38320915] [ 1.134...
# GRADED FUNCTION: initialize_adam def initialize_adam(parameters) : """ Initializes v and s as two python dictionaries with: - keys: "dW1", "db1", ..., "dWL", "dbL" - values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters. Arguments:...
v["dW1"] = [[ 0. 0. 0.] [ 0. 0. 0.]] v["db1"] = [[ 0.] [ 0.]] v["dW2"] = [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] v["db2"] = [[ 0.] [ 0.] [ 0.]] s["dW1"] = [[ 0. 0. 0.] [ 0. 0. 0.]] s["db1"] = [[ 0.] [ 0.]] s["dW2"] = [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] s["db2"] = [[ 0.] [ 0.] [ 0.]]
Apache-2.0
Week2/Optimization+methods.ipynb
softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization