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 |
|---|---|---|---|---|---|
geom_density2d() | import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
df = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv')
ggplot(df, aes('cty', 'hwy')) + geom_density2d(aes(color='..group..')) | _____no_output_____ | MIT | source/examples/basics/gog/geom_density2d.ipynb | ASmirnov-HORIS/lets-plot-docs |
General Imports | import pandas as pd
import numpy as np | _____no_output_____ | MIT | examples/permutation_importance_example.ipynb | barak1412/automl_infrastructure |
Data Loading | df = pd.read_csv('adult_salary.data', header=None, usecols=[3,4,5,6,8,9,14],
names=['EDUCATION', 'EDUCATION_PERIOD', 'STATUS', 'OCCUPY', 'RACE', 'GENDER','RICH'],
dtype=str)
label_col = 'RICH'
features_cols = [c for c in df.columns if c != label_col]
df['EDUCATION_PERIOD'] = df['EDUCATI... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 32561 entries, 0 to 32560
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 EDUCATION 32561 non-null object
1 EDUCATION_PERIOD 32561 non-null int32
2 STATUS 32561... | MIT | examples/permutation_importance_example.ipynb | barak1412/automl_infrastructure |
Data Preparation | from sklearn.preprocessing import LabelBinarizer
feature_encoder_dict = {}
final_df = df.copy()
for feature in categorial_features:
feature_encoder_dict[feature] = LabelBinarizer()
final_df[feature] = pd.Series(list(feature_encoder_dict[feature].fit_transform(df[feature])))
final_df
from sklearn.model_selectio... | _____no_output_____ | MIT | examples/permutation_importance_example.ipynb | barak1412/automl_infrastructure |
Modeling | from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, make_scorer
from automl_infrastructure.classifiers.adapters import SklearnClassifierAdapter
lr_model = SklearnClassifierAdapter(name='lr1', sklearn_model=LogisticRegressi... | C:\Users\Barak\.conda\envs\DSEnv\lib\site-packages\sklearn\linear_model\_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preproc... | MIT | examples/permutation_importance_example.ipynb | barak1412/automl_infrastructure |
Permutation Importance Calculation | from automl_infrastructure.interpretation import PermutationImportance
pi = PermutationImportance(lr_model, scoring='accuracy')
pi.fit(test_df[features_cols], test_df[label_col])
pi.show_weights()
print()
pi = PermutationImportance(rf_model, scoring='accuracy')
pi.fit(test_df[features_cols], test_df[label_col])
pi.sh... | Feature Weight Std
0 STATUS 0.076348 0.002884
1 OCCUPY 0.029066 0.001612
2 EDUCATION_PERIOD 0.026302 0.001469
3 EDUCATION 0.005322 0.001511
4 RACE 0.001228 0.001566
5 GENDER 0.000819 0.000145
Feature Weight Std... | MIT | examples/permutation_importance_example.ipynb | barak1412/automl_infrastructure |
Tutorial 0a: Setting Up Python For Scientific Computing In this tutorial, we will set up a scientific Python computing environment using the [Anaconda python distribution by Continuum Analytics](https://www.continuum.io/downloads). Why Python? As is true in human language, there are [hundreds of computer programming... | # This a comment and won't be read by Python. All comments start with `#`
print('Hello, World. Long time, no see. This sentence should be printed below by pressing `Shift + Enter` ') | Hello, World. Long time, no see. This sentence should be printed below by pressing `Shift + Enter`
| MIT | Chapter00/t0a/t0a_setting_up_python.ipynb | mazhengcn/scientific-computing-with-python |
Note that you cannot edit the text *below* the code cell. This is the output of the `print()` function in Python. Our First PlotThis class will often require you to generate plots of your computations coupled with some comments about your interpretation. Let's try to generate a simple plot here to make sure everything ... | # Import Python packages necessary for this script
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
# Generate a beautiful sinusoidal curve
x = np.linspace(0, 2*np.pi, 500)
y = np.sin(2 * np.sin(2 * np.sin(2 * x)))
plt.plot(x, y)
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show() | _____no_output_____ | MIT | Chapter00/t0a/t0a_setting_up_python.ipynb | mazhengcn/scientific-computing-with-python |
Dummy applications CPU stress test | #analysis("example-data/cpu")
analysis("example-data-sana/cpu", skiprows=15)
#analysis("data-3bb4e2af-bf0a-4b78-b8b2-f9dbd1df35b3 (copy)/cpu")
|
====================
CPU Analysis
====================
Total CPU core:
64
Total CPU time (seconds):
6979.350
Parallel CPU time (seconds):
128.090
Makes span (seconds):
128.090
| MIT | notebooks/Performance_Ridgeregression_Sana.ipynb | courtois-neuromod/movie_decoding_sa |
Disk test | analysis("example-data-sana/disk", skiprows=15) |
====================
CPU Analysis
====================
Total CPU core:
64
Total CPU time (seconds):
6979.350
Parallel CPU time (seconds):
128.090
Makes span (seconds):
128.090
| MIT | notebooks/Performance_Ridgeregression_Sana.ipynb | courtois-neuromod/movie_decoding_sa |
Network test | analysis("example-data-sana/network", skiprows=15) |
====================
CPU Analysis
====================
Total CPU core:
64
Total CPU time (seconds):
6979.350
Parallel CPU time (seconds):
128.090
Makes span (seconds):
128.090
| MIT | notebooks/Performance_Ridgeregression_Sana.ipynb | courtois-neuromod/movie_decoding_sa |
Neuroimaging Applications BET participant analysis | analysis("example-data-sana/bet_participant", skiprows=15) |
====================
CPU Analysis
====================
Total CPU core:
64
Total CPU time (seconds):
6979.350
Parallel CPU time (seconds):
128.090
Makes span (seconds):
128.090
| MIT | notebooks/Performance_Ridgeregression_Sana.ipynb | courtois-neuromod/movie_decoding_sa |
BET group analysis | analysis("example-data-sana/bet_group", skiprows=15) |
====================
CPU Analysis
====================
Total CPU core:
64
Total CPU time (seconds):
6979.350
Parallel CPU time (seconds):
128.090
Makes span (seconds):
128.090
| MIT | notebooks/Performance_Ridgeregression_Sana.ipynb | courtois-neuromod/movie_decoding_sa |
MRIQC participant analysis | analysis("example-data-sana/mriqc_participant", skiprows=15) |
====================
CPU Analysis
====================
Total CPU core:
64
Total CPU time (seconds):
6979.350
Parallel CPU time (seconds):
128.090
Makes span (seconds):
128.090
| MIT | notebooks/Performance_Ridgeregression_Sana.ipynb | courtois-neuromod/movie_decoding_sa |
MRIQC group analysis | analysis("example-data-sana/mriqc_group", skiprows=15) |
====================
CPU Analysis
====================
Total CPU core:
64
Total CPU time (seconds):
6979.350
Parallel CPU time (seconds):
128.090
Makes span (seconds):
128.090
| MIT | notebooks/Performance_Ridgeregression_Sana.ipynb | courtois-neuromod/movie_decoding_sa |
Bokeh Circle X Glyph | from bokeh.plotting import figure, output_file, show
from bokeh.models import Range1d
from bokeh.io import export_png
fill_color = '#e08214'
line_color = '#fdb863'
output_file("../../figures/circle_x.html")
p = figure(plot_width=400, plot_height=400)
p.circle_x(x=0,y=0,size=100, fill_alpha=1,fill_color=fill_color,
... | _____no_output_____ | MIT | visualizations/bokeh/notebooks/glyphs/circle_x.ipynb | martinpeck/apryor6.github.io |
CNN Image Data Preview & Statistics Welcome! This notebook allows you to preview some of your single-cell image patches to make sure your annotated data are of good quality. You will also get a chance to calculate the statistics for your annotated data which can be useful for data preprocessing, e.g. *class imbalance ... | import os
import json
import random
import zipfile
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from datetime import datetime
from skimage.io import imread | _____no_output_____ | BSD-3-Clause | notebooks/B_CNN_Data_Preview_Images.ipynb | nthndy/cnn-annotator |
Specify how many patches you'd like to visualise from your batch:By default, the code below will allow you to see any 10 random patches per each class. If there is not enough training data for any label, a noisy image will be visualised. The default setting doesn't save the collage out, but you can change it by specif... | LABELS = ["Interphase", "Prometaphase", "Metaphase", "Anaphase", "Apoptosis"]
patches_to_show = 10
save_collage = False
| _____no_output_____ | BSD-3-Clause | notebooks/B_CNN_Data_Preview_Images.ipynb | nthndy/cnn-annotator |
Load a random 'annotation' zip file to check image patches: | zipfiles = [f for f in os.listdir("./") if f.startswith("annotation") and f.endswith(".zip")]
zip_file_name = zipfiles[0]
| _____no_output_____ | BSD-3-Clause | notebooks/B_CNN_Data_Preview_Images.ipynb | nthndy/cnn-annotator |
Optional: specify which zip file you'd like to visualise: | #zip_file_name = "annotation_02-08-2021--10-33-59.zip"
| _____no_output_____ | BSD-3-Clause | notebooks/B_CNN_Data_Preview_Images.ipynb | nthndy/cnn-annotator |
Process the zip file & extract subfolders with individual images: | # Make sure zip file name is stripped of '.zip' suffix:
if zip_file_name.endswith(".zip"):
zip_file_name = zip_file_name.split(".zip")[0]
# Check if the zipfile was extracted:
if not zip_file_name in os.listdir("./"):
print (f"Zip file {zip_file_name}.zip : Exporting...", end="\t")
with zipfile.Zip... | Zip file annotation_02-08-2021--10-33-59.zip : Exporting... Done!
| BSD-3-Clause | notebooks/B_CNN_Data_Preview_Images.ipynb | nthndy/cnn-annotator |
Plot the collage with all 5 labels: | fig, axs = plt.subplots(figsize=(int(len(LABELS)*5), int(patches_to_show*5)),
nrows=patches_to_show, ncols=len(LABELS),
sharex=True, sharey=True)
for idx in range(len(LABELS)):
label = LABELS[idx]
label_dr = f"./{zip_file_name}/{label}/"
# Check i... | Label: Interphase contains 6 single-cell image patches
Label: Prometaphase contains 6 single-cell image patches
Label: Metaphase contains 5 single-cell image patches
Label: Anaphase contains 8 single-cell image patches
Label: Apoptosis contains 6 single-cell image patches
| BSD-3-Clause | notebooks/B_CNN_Data_Preview_Images.ipynb | nthndy/cnn-annotator |
Calculate some data statistics WITHOUT unzipping the files: | label_count = dict({'Prometaphase' : 0, 'Metaphase' : 0, 'Interphase' : 0, 'Anaphase' : 0, 'Apoptosis' : 0})
for f in tqdm(zipfiles):
archive = zipfile.ZipFile(f, 'r')
json_data = archive.read(f.split(".zip")[0] + ".json")
data = json.loads(json_data)
# Count instances per label:
counts =... | 100%|██████████| 1/1 [00:00<00:00, 255.97it/s] | BSD-3-Clause | notebooks/B_CNN_Data_Preview_Images.ipynb | nthndy/cnn-annotator |
Plot the statistics: | COLOR_CYCLE = [
'#1f77b4', # blue
'#ff7f0e', # orange
'#2ca02c', # green
'#d62728', # red
'#9467bd', # purple
]
# Plot the bar graph:
plt.bar(range(len(label_count)), list(label_count.values()), align='center', color=COLOR_CYCLE)
plt.xticks(range(len(label_count)), list(label_count.keys()), rotatio... | _____no_output_____ | BSD-3-Clause | notebooks/B_CNN_Data_Preview_Images.ipynb | nthndy/cnn-annotator |
Getting and Knowing your Dataimport dataset from https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user Import the necessary libraries | import numpy as np
import pandas as pd | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
Assign it to a variable called users and use the 'user_id' as index and See the first 25 entries | df = pd.read_csv("https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user",sep='|', index_col="user_id")
df.head(25) | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
See the last 10 entries | df.tail(10) | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
The number of observations in the dataset | df.shape[0] | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
The number of columns in the dataset | df.shape[1] | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
Name of all the columns | df.columns | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
Dataset index | df.index | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
Data type of each column | df.dtypes | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
Observation only the occupation column | df["occupation"] | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
The number of occupations in this dataset | df.occupation.nunique() | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
The most frequent occupation in dataset | df.occupation.value_counts()
df.occupation.value_counts().head()
df.occupation.value_counts().head().index[0] | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
Summarize the DataFrame | df.describe() | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
Summarize all the columns | df.describe(include = "all") | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
Summarize only the gender column | df.gender.describe() | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
The mean age of dataframe | round(df.age.mean()) | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
The occupation with least occurrence | df.occupation.value_counts().tail() | _____no_output_____ | MIT | DataTalks_GettingKnowingData I.ipynb | gympohnpimol/Pandas-Data-Talks |
Encoding of categorical variablesIn this notebook, we will present typical ways of dealing with**categorical variables** by encoding them, namely **ordinal encoding** and**one-hot encoding**. Let's first load the entire adult dataset containing both numerical andcategorical data. | import pandas as pd
adult_census = pd.read_csv("../datasets/adult-census.csv")
# drop the duplicated column `"education-num"` as stated in the first notebook
adult_census = adult_census.drop(columns="education-num")
target_name = "class"
target = adult_census[target_name]
data = adult_census.drop(columns=[target_nam... | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
Identify categorical variablesAs we saw in the previous section, a numerical variable is aquantity represented by a real or integer number. These variables can benaturally handled by machine learning algorithms that are typically composedof a sequence of arithmetic instructions such as additions andmultiplications.In ... | data["native-country"].value_counts().sort_index() | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
How can we easily recognize categorical columns among the dataset? Part ofthe answer lies in the columns' data type: | data.dtypes | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
If we look at the `"native-country"` column, we observe its data type is`object`, meaning it contains string values. Select features based on their data typeIn the previous notebook, we manually defined the numerical columns. We coulddo a similar approach. Instead, we will use the scikit-learn helper function`make_colu... | from sklearn.compose import make_column_selector as selector
categorical_columns_selector = selector(dtype_include=object)
categorical_columns = categorical_columns_selector(data)
categorical_columns | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
Here, we created the selector by passing the data type to include; we thenpassed the input dataset to the selector object, which returned a list ofcolumn names that have the requested data type. We can now filter out theunwanted columns: | data_categorical = data[categorical_columns]
data_categorical.head()
print(f"The dataset is composed of {data_categorical.shape[1]} features") | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
In the remainder of this section, we will present different strategies toencode categorical data into numerical data which can be used by amachine-learning algorithm. Strategies to encode categories Encoding ordinal categoriesThe most intuitive strategy is to encode each category with a differentnumber. The `OrdinalEn... | from sklearn.preprocessing import OrdinalEncoder
education_column = data_categorical[["education"]]
encoder = OrdinalEncoder()
education_encoded = encoder.fit_transform(education_column)
education_encoded | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
We see that each category in `"education"` has been replaced by a numericvalue. We could check the mapping between the categories and the numericalvalues by checking the fitted attribute `categories_`. | encoder.categories_ | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
Now, we can check the encoding applied on all categorical features. | data_encoded = encoder.fit_transform(data_categorical)
data_encoded[:5]
print(
f"The dataset encoded contains {data_encoded.shape[1]} features") | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
We see that the categories have been encoded for each feature (column)independently. We also note that the number of features before and after theencoding is the same.However, be careful when applying this encoding strategy:using this integer representation leads downstream predictive modelsto assume that the values ar... | from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse=False)
education_encoded = encoder.fit_transform(education_column)
education_encoded | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
Notesparse=False is used in the OneHotEncoder for didactic purposes, namelyeasier visualization of the data.Sparse matrices are efficient data structures when most of your matrixelements are zero. They won't be covered in detail in this course. If youwant more details about them, you can look atthis. We see that encodi... | feature_names = encoder.get_feature_names_out(input_features=["education"])
education_encoded = pd.DataFrame(education_encoded, columns=feature_names)
education_encoded | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
As we can see, each category (unique value) became a column; the encodingreturned, for each sample, a 1 to specify which category it belongs to.Let's apply this encoding on the full dataset. | print(
f"The dataset is composed of {data_categorical.shape[1]} features")
data_categorical.head()
data_encoded = encoder.fit_transform(data_categorical)
data_encoded[:5]
print(
f"The encoded dataset contains {data_encoded.shape[1]} features") | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
Let's wrap this NumPy array in a dataframe with informative column names asprovided by the encoder object: | columns_encoded = encoder.get_feature_names_out(data_categorical.columns)
pd.DataFrame(data_encoded, columns=columns_encoded).head() | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
Look at how the `"workclass"` variable of the 3 first records has beenencoded and compare this to the original string representation.The number of features after the encoding is more than 10 times larger thanin the original data because some variables such as `occupation` and`native-country` have many possible categori... | data["native-country"].value_counts() | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
We see that the `Holand-Netherlands` category is occurring rarely. This willbe a problem during cross-validation: if the sample ends up in the test setduring splitting then the classifier would not have seen the category duringtraining and will not be able to encode it.In scikit-learn, there are two solutions to bypass... | from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
model = make_pipeline(
OneHotEncoder(handle_unknown="ignore"), LogisticRegression(max_iter=500)
) | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
NoteHere, we need to increase the maximum number of iterations to obtain a fullyconverged LogisticRegression and silence a ConvergenceWarning. Contraryto the numerical features, the one-hot encoded categorical features are allon the same scale (values are 0 or 1), so they would not benefit fromscaling. In this case, in... | from sklearn.model_selection import cross_validate
cv_results = cross_validate(model, data_categorical, target)
cv_results
scores = cv_results["test_score"]
print(f"The accuracy is: {scores.mean():.3f} +/- {scores.std():.3f}") | _____no_output_____ | CC-BY-4.0 | notebooks/03_categorical_pipeline.ipynb | parmentelat/scikit-learn-mooc |
Box Plots The following illustrates some options for the boxplot in statsmodels. These include `violin_plot` and `bean_plot`. | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm | _____no_output_____ | BSD-3-Clause | examples/notebooks/plots_boxplots.ipynb | chengevo/statsmodels |
Bean Plots The following example is taken from the docstring of `beanplot`.We use the American National Election Survey 1996 dataset, which has PartyIdentification of respondents as independent variable and (among otherdata) age as dependent variable. | data = sm.datasets.anes96.load_pandas()
party_ID = np.arange(7)
labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat",
"Independent-Independent", "Independent-Republican",
"Weak Republican", "Strong Republican"] | _____no_output_____ | BSD-3-Clause | examples/notebooks/plots_boxplots.ipynb | chengevo/statsmodels |
Group age by party ID, and create a violin plot with it: | plt.rcParams['figure.subplot.bottom'] = 0.23 # keep labels visible
plt.rcParams['figure.figsize'] = (10.0, 8.0) # make plot larger in notebook
age = [data.exog['age'][data.endog == id] for id in party_ID]
fig = plt.figure()
ax = fig.add_subplot(111)
plot_opts={'cutoff_val':5, 'cutoff_type':'abs',
... | _____no_output_____ | BSD-3-Clause | examples/notebooks/plots_boxplots.ipynb | chengevo/statsmodels |
Advanced Box Plots Based of example script `example_enhanced_boxplots.py` (by Ralf Gommers) | import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
# Necessary to make horizontal axis labels fit
plt.rcParams['figure.subplot.bottom'] = 0.23
data = sm.datasets.anes96.load_pandas()
party_ID = np.arange(7)
labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat",
... | _____no_output_____ | BSD-3-Clause | examples/notebooks/plots_boxplots.ipynb | chengevo/statsmodels |
TEST for matrix_facto_10_embeddings_100_epochs Deep recommender on top of Amason’s Clean Clothing Shoes and Jewelry explicit rating datasetFrame the recommendation system as a rating prediction machine learning problem and create a hybrid architecture that mixes the collaborative and content based filtering approaches... | ### name of model
modname = 'matrix_facto_10_embeddings_100_epochs'
### number of epochs
num_epochs = 100
### size of embedding
embedding_size = 10
# import sys
# !{sys.executable} -m pip install --upgrade pip
# !{sys.executable} -m pip install sagemaker-experiments
# !{sys.executable} -m pip install pandas
# !{sys.... | Populating the interactive namespace from numpy and matplotlib
WARNING:tensorflow:From /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_core/__init__.py:1467: The name tf.estimator.inputs is deprecated. Please use tf.compat.v1.estimator.inputs instead.
time: 3.5 s
| Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
Set and Check GPUs | #Session
from keras import backend as K
def set_check_gpu():
cfg = K.tf.ConfigProto()
cfg.gpu_options.per_process_gpu_memory_fraction =1 # allow all of the GPU memory to be allocated
# for 8 GPUs
# cfg.gpu_options.visible_device_list = "0,1,2,3,4,5,6,7" # "0,1"
# for 1 GPU
cfg.gpu_options.visib... | time: 2.51 ms
| Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
Load dataset and analysis using Spark Download and prepare Data: 1. Read the data: Read the data from the reviews dataset of amazon. Use the dastaset in which all users and items have at least 5 reviews. Location of dataset: https://nijianmo.github.io/amazon/index.html | import pandas as pd
import boto3
import sagemaker
from sagemaker import get_execution_role
from sagemaker.session import Session
from sagemaker.analytics import ExperimentAnalytics
import gzip
import json
from pyspark.ml import Pipeline
from pyspark.sql.types import StructField, StructType, StringType, DoubleType
fr... | total 3.3G
drwxrwxr-x 5 ec2-user ec2-user 4.0K May 26 16:08 .
drwxrwxr-x 8 ec2-user ec2-user 4.0K May 26 19:47 ..
-rw-rw-r-- 1 ec2-user ec2-user 308M May 26 15:35 Clean_Clothing_Shoes_and_Jewelry_5_clean.parquet
drwxrwxr-x 2 ec2-user ec2-user 4.0K May 26 15:46 Cleaned_meta_Clothing_Shoes_and_Jewelry.parquet
-rw-rw-r-- ... | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
Read clened dataset from parquet files | review_data = pd.read_parquet("./data/Clean_Clothing_Shoes_and_Jewelry_5_clean.parquet")
review_data[:3]
review_data.shape | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
2. Arrange and clean the data Rearrange the columns by relevance and rename column names | review_data.columns
review_data = review_data[['asin', 'image', 'summary', 'reviewText', 'overall', 'reviewerID', 'reviewerName', 'reviewTime']]
review_data.rename(columns={ 'overall': 'score','reviewerID': 'user_id', 'reviewerName': 'user_name'}, inplace=True)
#the variables names after rename in the modified data f... | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
Add Metadata Metadata includes descriptions, price, sales-rank, brand info, and co-purchasing links- asin - ID of the product, e.g. 0000031852- title - name of the product- price - price in US dollars (at time of crawl)- imUrl - url of the product image- related - related products (also bought, also viewed, bought to... | # !aws s3 cp s3://dse-cohort5-group1/2-Keras-DeepRecommender/dataset/Cleaned_meta_Clothing_Shoes_and_Jewelry.parquet ./data/
all_info = pd.read_parquet("./data/Cleaned_meta_Clothing_Shoes_and_Jewelry.parquet")
all_info.head(n=5) | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
Arrange and clean the data - Cleaning, handling missing data, normalization, etc:- For the algorithm in keras to work, remap all item_ids and user_ids to an interger between 0 and the total number of users or the total number of items | all_info.columns
items = all_info.asin.unique()
item_map = {i:val for i,val in enumerate(items)}
inverse_item_map = {val:i for i,val in enumerate(items)}
all_info["old_item_id"] = all_info["asin"] # copying for join with metadata
all_info["item_id"] = all_info["asin"].map(inverse_item_map)
items = all_info.item_id.uniq... | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
Adding the review count and avarage to the metadata | #items_nb = review_data['old_item_id'].value_counts().reset_index()
items_avg = review_data.drop(['summary','reviewText','user_id','asin','user_name','reviewTime','old_user_id','item_id'],axis=1).groupby('old_item_id').agg(['count','mean']).reset_index()
items_avg.columns= ['old_item_id','num_ratings','avg_rating']
#it... | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
Explicit feedback (Reviewed Dataset) Recommender System Explicit feedback is when users gives voluntarily the rating information on what they like and dislike.- In this case, I have explicit item ratings ranging from one to five.- Framed the recommendation system as a rating prediction machine learning problem: -... | ratings_train, ratings_test = train_test_split( review_data, test_size=0.1, random_state=0)
ratings_train.shape
ratings_test.shape | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
Adding Metadata to the train setCreate an architecture that mixes the collaborative and content based filtering approaches:```- Collaborative Part: Predict items ratings to recommend to the user items which he is likely to rate high according to learnt item & user embeddings (learn similarity from interactions).- Cont... | # # creating metadata mappings
# titles = all_info['title'].unique()
# titles_map = {i:val for i,val in enumerate(titles)}
# inverse_titles_map = {val:i for i,val in enumerate(titles)}
# price = all_info['price'].unique()
# price_map = {i:val for i,val in enumerate(price)}
# inverse_price_map = {val:i for i,val in en... | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
create rating train/test dataset and upload into S3 | # !aws s3 cp s3://dse-cohort5-group1/2-Keras-DeepRecommender/dataset/ratings_test.parquet ./data/
# !aws s3 cp s3://dse-cohort5-group1/2-Keras-DeepRecommender/dataset/ratings_train.parquet ./data/
ratings_test = pd.read_parquet('./data/ratings_test.parquet')
ratings_train = pd.read_parquet('./data/ratings_train.parquet... | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
**Define embeddings The $\underline{embeddings}$ are low-dimensional hidden representations of users and items, i.e. for each item I can find its properties and for each user I can encode how much they like those properties so I can determine attitudes or preferences of users by a small number of hidden factors Thro... | price = all_info['price'].unique()
titles = all_info['title'].unique() | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
1. Matrix factorization approach | # declare input embeddings to the model
# User input
user_id_input = Input(shape=[1], name='user')
# Item Input
item_id_input = Input(shape=[1], name='item')
price_id_input = Input(shape=[1], name='price')
title_id_input = Input(shape=[1], name='title')
# define the size of embeddings as a parameter
# Check 5, 10 , 15... | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
Matrix Factorisation works on the principle that we can learn the user and the item embeddings, and then predict the rating for each user-item by performing a dot (or scalar) product between the respective user and item embedding. | # Applying matrix factorization: declare the output as being the dot product between the two embeddings: items and users
y = Dot(1, normalize=False)([user_vecs, item_vecs])
!mkdir -p ./models
# create model
model = Model(inputs=
[
user_id_input,
item_id_inpu... | _____no_output_____ | Apache-2.0 | Keras-DeepRecommender-Clothing-Shoes-Jewelry/2_Modeling/matrix_facto_10_embeddings_100_epochs.ipynb | zirubak/dse260-CapStone-Amazon |
#let us import the pandas library
import pandas as pd | _____no_output_____ | MIT | Moringa_Data_Science_Prep_W4_Independent_Project_2021_07_Cindy_Gachuhi_Python_IP.ipynb | CindyMG/Week4IP | |
From the following data sources, we will acquire our datasets for analysis:http://bit.ly/autolib_datasethttps://drive.google.com/a/moringaschool.com/file/d/13DXF2CFWQLeYxxHFekng8HJnH_jtbfpN/view?usp=sharing | # let us create a dataframe from the following url:
# http://bit.ly/autolib_dataset
df_url = "http://bit.ly/autolib_dataset"
Autolib_dataset = pd.read_csv(df_url)
Autolib_dataset
# let us identify the columns with null values and drop them
#
Autolib_dataset.isnull()
Autolib_dataset.dropna(axis=1,how='all',inplace=True... | _____no_output_____ | MIT | Moringa_Data_Science_Prep_W4_Independent_Project_2021_07_Cindy_Gachuhi_Python_IP.ipynb | CindyMG/Week4IP |
Assignment 2 Batch 7 Ans.1. **List properties:** ordered, iterable, mutable, can contain multiple data types List default functions are:- append()- add values or items at the end of the list- index()-returns the index of the list item- count()-Return number of occurrences of value. | list1 = ['Abhilasha','Anamika','Dhanya',1,2,3,4]
list1.append('Matu')
list1
list1.remove('Matu')
list1
list1.append(1)
list1
list1.count(1)
list1.pop(-1)
list1.clear() #Remove all items from list.
list1 | _____no_output_____ | Apache-2.0 | Python Essentials B7 Assignment Day2.ipynb | dhanyasingh/LetsUpgrade-Python-B7 |
Ans.2. **Dictionary properties:**unordered, iterable, mutable, can contain multiple data types- Made of key-value pairs- Keys must be unique, and can be strings, numbers, or tuples- Values can be any type Dictionaries default functions:- get()- retrieving a value from dictionary- items()- keys()- pop() | # create an empty dictionary (two ways)
empty_dict = {}
empty_dict = dict()
# create a dictionary (two ways)
family = {'dad':'Sachin', 'mom':'Geeta', 'size':6}
family = dict(dad='Sachin', mom='Geeta', size=6)
family
# pass a key to return its value
family['dad']
# return the number of key-value pairs
len(family)
'Geeta... | _____no_output_____ | Apache-2.0 | Python Essentials B7 Assignment Day2.ipynb | dhanyasingh/LetsUpgrade-Python-B7 |
Ans.3. **Set properties:** unordered, iterable, mutable, can contain multiple data types- Made of unique elements (strings, numbers, or tuples)- Like dictionaries, but with keys only (no values)- complex data structures- used for finding union, disjoints, commons etc. | st = {1,2,4,5,'Dhanya', 7777}
st1 = {'Matu',7777, 6,7,8,9}
st.intersection(st1)
st.issubset(st1)
st1.issubset(st)
st.union(st1)
st.difference(st1)
st.isdisjoint(st1) | _____no_output_____ | Apache-2.0 | Python Essentials B7 Assignment Day2.ipynb | dhanyasingh/LetsUpgrade-Python-B7 |
Ans.4. **Tuple properties:** ordered, iterable, immutable, can contain multiple data typesLike lists, but they don't change size | # create a tuple directly
digits = (0, 1, 'two')
# create a tuple from a list
digits = tuple([0, 1, 'two'])
digits[2]
len(digits)
digits.count(0) #count no.of instances
digits.index(1) | _____no_output_____ | Apache-2.0 | Python Essentials B7 Assignment Day2.ipynb | dhanyasingh/LetsUpgrade-Python-B7 |
Ans.5. **String and its default methods:** stores characters, | name1 = 'Kumari Himanshi'
name2 = 'Piyushi Srivastava'
name1 + " " + name2
type(name1)
name1*2 #repetition of string
name2*5 | _____no_output_____ | Apache-2.0 | Python Essentials B7 Assignment Day2.ipynb | dhanyasingh/LetsUpgrade-Python-B7 |
DescriptionThis notebook is used to request computation of average time-series of a WaPOR data layer for an area using WaPOR API.You will need WaPOR API Token to use this notebook Step 1: Read APITokenGet your APItoken from https://wapor.apps.fao.org/profile. Enter your API Token when running the cell below. | import requests
import pandas as pd
path_query=r'https://io.apps.fao.org/gismgr/api/v1/query/'
path_sign_in=r'https://io.apps.fao.org/gismgr/api/v1/iam/sign-in/'
APIToken=input('Your API token: ') | Your API token: Enter your API token
| CC0-1.0 | notebooks/Module1_unit5/4_AreaStatsTimeSeries.ipynb | LaurenZ-IHE/WAPOROCW |
Step 2: Get Authorization AccessTokenUsing the input API token to get AccessToken for authorization | resp_signin=requests.post(path_sign_in,headers={'X-GISMGR-API-KEY':APIToken})
resp_signin = resp_signin.json()
AccessToken=resp_signin['response']['accessToken']
AccessToken | _____no_output_____ | CC0-1.0 | notebooks/Module1_unit5/4_AreaStatsTimeSeries.ipynb | LaurenZ-IHE/WAPOROCW |
Step 3: Write Query PayloadFor more examples of areatimeseries query load visit https://io.apps.fao.org/gismgr/api/v1/swagger-ui/examples/AreaStatsTimeSeries.txt | crs="EPSG:4326" #coordinate reference system
cube_code="L1_PCP_E"
workspace='WAPOR_2'
start_date="2009-01-01"
end_date="2019-01-01"
#get datacube measure
cube_url=f'https://io.apps.fao.org/gismgr/api/v1/catalog/workspaces/{workspace}/cubes/{cube_code}/measures'
resp=requests.get(cube_url).json()
measure=resp['response... | MEASURE: WATER_MM
DIMENSION: DAY
| CC0-1.0 | notebooks/Module1_unit5/4_AreaStatsTimeSeries.ipynb | LaurenZ-IHE/WAPOROCW |
Define area by coordinate extent | bbox= [37.95883206252312, 7.89534, 43.32093, 12.3873979377346] #latlon
xmin,ymin,xmax,ymax=bbox[0],bbox[1],bbox[2],bbox[3]
Polygon=[
[xmin,ymin],
[xmin,ymax],
[xmax,ymax],
[xmax,ymin],
[xmin,ymin]
]
query_areatimeseries={
"type": "AreaStatsTimeSeries",
"para... | _____no_output_____ | CC0-1.0 | notebooks/Module1_unit5/4_AreaStatsTimeSeries.ipynb | LaurenZ-IHE/WAPOROCW |
OR define area by reading GeoJSON | import ogr
shp_fh=r".\data\Awash_shapefile.shp"
shpfile=ogr.Open(shp_fh)
layer=shpfile.GetLayer()
epsg_code=layer.GetSpatialRef().GetAuthorityCode(None)
shape=layer.GetFeature(0).ExportToJson(as_object=True)['geometry'] #get geometry of shapefile in JSON string
shape["properties"]={"name": "EPSG:{0}".format(epsg_code)... | _____no_output_____ | CC0-1.0 | notebooks/Module1_unit5/4_AreaStatsTimeSeries.ipynb | LaurenZ-IHE/WAPOROCW |
Step 4: Post the QueryPayload with AccessToken in Header In responses, get an url to query job. | resp_query=requests.post(path_query,headers={'Authorization':'Bearer {0}'.format(AccessToken)},
json=query_areatimeseries)
resp_query = resp_query.json()
job_url=resp_query['response']['links'][0]['href']
job_url | _____no_output_____ | CC0-1.0 | notebooks/Module1_unit5/4_AreaStatsTimeSeries.ipynb | LaurenZ-IHE/WAPOROCW |
Step 5: Get Job Results.It will take some time for the job to be finished. When the job is finished, its status will be changed from 'RUNNING' to 'COMPLETED' or 'COMPLETED WITH ERRORS'. If it is COMPLETED, the area time series results can be achieved from Response 'output'. | i=0
print('RUNNING',end=" ")
while i==0:
resp = requests.get(job_url)
resp=resp.json()
if resp['response']['status']=='RUNNING':
print('.',end =" ")
if resp['response']['status']=='COMPLETED':
results=resp['response']['output']
df=pd.DataFrame(results['items'],column... | _____no_output_____ | CC0-1.0 | notebooks/Module1_unit5/4_AreaStatsTimeSeries.ipynb | LaurenZ-IHE/WAPOROCW |
Key word / sentence topic loading | keyword_embed = model_distilBert.embed(["volunteering"])
res = cosine_similarity(keyword_embed, model_distilBert.topic_vectors)
scores = pd.DataFrame(res, index=["Cosine similiarity"]).T
scores["Topic"] = list(range(0,len(scores)))
scores["Top words"] = scores["Topic"].apply(lambda x: list(topics_top2Vec.iloc[x,0:3]))
... | _____no_output_____ | Apache-2.0 | notebook/REIT-Industrial.ipynb | piinghel/TopicModelling |
Most similar documents for a topic | documents, document_scores, document_ids = model_distilBert.search_documents_by_topic(topic_num=5, num_docs=2)
for doc, score, doc_id in zip(documents, document_scores, document_ids):
print(f"Document: {doc_id}, Filename (Company and year): {df.iloc[doc_id,:].filename}, Score: {score}")
print("-----------")
... | _____no_output_____ | Apache-2.0 | notebook/REIT-Industrial.ipynb | piinghel/TopicModelling |
Update model | model_distilBert.n_components = 5
model_distilBert.ngram_range = (1,4)
model_distilBert._update_steps(documents=paragraphs, step=1)
topic_words, word_scores, topic_nums = model_distilBert.get_topics()
topic_sizes, topic_nums = model_distilBert.get_topic_sizes()
topics_top2Vec = pd.DataFrame(topic_words).iloc[:,0:10]
t... | _____no_output_____ | Apache-2.0 | notebook/REIT-Industrial.ipynb | piinghel/TopicModelling |
Reflect Tables into SQLAlchemy ORM | # Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, inspect
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# reflect an existing database into a new model
Base = au... | _____no_output_____ | ADSL | climate_starter.ipynb | ishanku/sqlalchemy-challenge |
Exploratory Climate Analysis | columns = inspector.get_columns('Measurement')
for column in columns:
print(column["name"], column["type"])
columns = inspector.get_columns('Station')
for column in columns:
print(column["name"], column["type"])
# Design a query to retrieve the last 12 months of precipitation data and plot the results
# Calcula... | _____no_output_____ | ADSL | climate_starter.ipynb | ishanku/sqlalchemy-challenge |
 | # Use Pandas Plotting with Matplotlib to plot the data
LPData.plot(rot=90);
plt.ylim(0,7)
plt.xlabel("Date")
plt.ylabel("Rain (Inches)")
plt.title("Precipitation Analysis")
plt.legend(["Precipitation"])
plt.savefig("./Output/Figure1.png")
plt.show()
# Use Pandas to calcualte the summary statistics for the precipitation... | _____no_output_____ | ADSL | climate_starter.ipynb | ishanku/sqlalchemy-challenge |
 | # Design a query to show how many stations are available in this dataset?
# ---- From Measurement Data
session.query(Measurement.station).group_by(Measurement.station).count()
#----From Station Date
session.query(Station).count()
#-- Method 1 -- Using DataFrame
# What are the most active stations? (i.e. what stations h... | _____no_output_____ | ADSL | climate_starter.ipynb | ishanku/sqlalchemy-challenge |
 | # This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d'
# and return the minimum, average, and maximum temperatures for that range of dates
def calc_temps(start_date, end_date):
"""TMIN, TAVG, and TMAX for a list of dates.
Args:
start_date (string): A date ... | [('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4, 0.31), ('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9, 0.25), ('USC00518838', 'UPPER WAHIAWA 874.3, HI US', 21.4992, -158.0111, 306.6, 0.1), ('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6, 0.0600000... | ADSL | climate_starter.ipynb | ishanku/sqlalchemy-challenge |
Optional Challenge Assignment | # Create a query that will calculate the daily normals
# (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day)
def daily_normals(date):
"""Daily Normals.
Args:
date (str): A date string in the format '%m-%d'
Returns:
A list of tu... | _____no_output_____ | ADSL | climate_starter.ipynb | ishanku/sqlalchemy-challenge |
使用随即森林填补缺失值 | dataset = load_boston()
dataset.data.shape
#总共506*13=6578个数据
X_full, y_full = dataset.data, dataset.target
n_samples = X_full.shape[0]
n_features = X_full.shape[1] | _____no_output_____ | MIT | code/randomForest/bostonRegression.ipynb | Knowledge-Precipitation-Tribe/Machine-Learning |
添加缺失值 | #首先确定我们希望放入的缺失数据的比例,在这里我们假设是50%,那总共就要有3289个数据缺失
rng = np.random.RandomState(0)
missing_rate = 0.5
n_missing_samples = int(np.floor(n_samples * n_features * missing_rate))
#np.floor向下取整,返回.0格式的浮点数
#所有数据要随机遍布在数据集的各行各列当中,而一个缺失的数据会需要一个行索引和一个列索引
#如果能够创造一个数组,包含3289个分布在0~506中间的行索引,和3289个分布在0~13之间的列索引,那我们就可
#以利用索引来为数据中的任意3289... | _____no_output_____ | MIT | code/randomForest/bostonRegression.ipynb | Knowledge-Precipitation-Tribe/Machine-Learning |
使用0和均值填充 | #使用均值进行填补
from sklearn.impute import SimpleImputer
imp_mean = SimpleImputer(missing_values=np.nan, strategy='mean')
X_missing_mean = imp_mean.fit_transform(X_missing)
#使用0进行填补
imp_0 = SimpleImputer(missing_values=np.nan, strategy="constant",fill_value=0)
X_missing_0 = imp_0.fit_transform(X_missing) | _____no_output_____ | MIT | code/randomForest/bostonRegression.ipynb | Knowledge-Precipitation-Tribe/Machine-Learning |
使用随即森林填充缺失值 | """
使用随机森林回归填补缺失值
任何回归都是从特征矩阵中学习,然后求解连续型标签y的过程,之所以能够实现这个过程,是因为回归算法认为,特征
矩阵和标签之前存在着某种联系。实际上,标签和特征是可以相互转换的,比如说,在一个“用地区,环境,附近学校数
量”预测“房价”的问题中,我们既可以用“地区”,“环境”,“附近学校数量”的数据来预测“房价”,也可以反过来,
用“环境”,“附近学校数量”和“房价”来预测“地区”。而回归填补缺失值,正是利用了这种思想。
对于一个有n个特征的数据来说,其中特征T有缺失值,我们就把特征T当作标签,其他的n-1个特征和原本的标签组成新
的特征矩阵。那对于T来说,它没有缺失的部分,就是我们的Y_test,... | _____no_output_____ | MIT | code/randomForest/bostonRegression.ipynb | Knowledge-Precipitation-Tribe/Machine-Learning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.