我使用TensorFlow 插件中的 HammingLoss 指标创建并训练了一个 TensorFlow 模型。因此,它不是我自己创建的自定义指标。我将回调函数与方法结合使用ModelCheckpoint(),EarlyStopping分别保存最佳模型的最佳权重并在给定阈值停止模型训练。当我保存模型检查点时,我会序列化整个模型结构(类似于model.save()),而不是model.save_weights(),这只会保存模型权重(有关 ModelCheckpoint 的更多信息,请参见此处)。
TL;DR: 这是一个 Colab 笔记本,其中包含我在下面发布的代码,以防您想跳过此步骤。
我训练过的模型保存在此处链接的 GoogleDrive 中。要加载特定模型,我使用以下代码:
neural_network_parameters = {}
#======================================================================
# PARAMETERS THAT DEFINE THE NEURAL NETWORK STRUCTURE =
#======================================================================
neural_network_parameters['model_loss'] = tf.keras.losses.BinaryCrossentropy(from_logits=False, name='binary_crossentropy')
neural_network_parameters['model_metric'] = [tfa.metrics.HammingLoss(mode="multilabel", name="hamming_loss"),
tfa.metrics.F1Score(17, average="micro", name="f1_score_micro"),
tfa.metrics.F1Score(17, average=None, name="f1_score_none"),
tfa.metrics.F1Score(17, average="macro", name="f1_score_macro"),
tfa.metrics.F1Score(17, average="weighted", name="f1_score_weighted")]
"""Initialize the hyper parameters tuning the model using Tensorflow's hyperparameters module"""
HP_HIDDEN_UNITS = hp.HParam('batch_size', hp.Discrete([32]))
HP_EMBEDDING_DIM = …Run Code Online (Sandbox Code Playgroud) 我已经通过运行以下命令安装了 databricks cli 工具
pip install databricks-cli使用适合您的 Python 安装的 pip 版本。如果您使用的是 Python 3,请运行 pip3。
然后,通过创建 PAT(Databricks 中的个人访问令牌),我运行以下 .sh bash 脚本:
# You can run this on Windows as well, just change to a batch files
# Note: You need the Databricks CLI installed and you need a token configued
#!/bin/bash
echo "Creating DBFS direcrtory"
dbfs mkdirs dbfs:/databricks/packages
echo "Uploading cluster init script"
dbfs cp --overwrite python_dependencies.sh dbfs:/databricks/packages/python_dependencies.sh
echo "Listing DBFS direcrtory"
dbfs ls dbfs:/databricks/packages
Run Code Online (Sandbox Code Playgroud)
python_dependency.sh 脚本
#!/bin/bash
# Restart …Run Code Online (Sandbox Code Playgroud) 我很难理解如何让 Tensorboard 在 Google Colab 上运行的笔记本上正常工作。我将在下面发布一系列用于处理张量板的代码片段。
\nTensorFlow 版本:2.2.0
\nEager 模式:True
\nHub 版本:0.8.0
\nGPU 可用
%load_ext tensorboard\nimport tensorflow as tf\nfrom tensorboard.plugins.hparams import api as hp\nRun Code Online (Sandbox Code Playgroud)\ncallbacks = [\n \n EarlyStopping(monitor=monitor_metric,\n min_delta=minimum_delta,\n patience=patience_limit,\n verbose=verbose_value,\n mode=mode_value,\n restore_best_weights=True),\n\n ModelCheckpoint(filepath=weights_fname,\n monitor=monitor_metric,\n verbose=verbose_value,\n save_best_only=True,\n save_weights_only=True),\n \n tf.keras.callbacks.TensorBoard(logdir), #used here\n\n TensorBoardColabCallback(tbc),\n \n hp.KerasCallback(logdir, hparams) #used here\n ]\n \n return callbacks\nRun Code Online (Sandbox Code Playgroud)\n初始化将由 Tensorboard 记录的超参数
\nHP_HIDDEN_UNITS = hp.HParam(\'batch_size\', hp.Discrete([128]))\nHP_EMBEDDING_DIM = hp.HParam(\'embedding_dim\', hp.Discrete([50, 100]))\nHP_LEARNING_RATE = hp.HParam(\'learning_rate\', hp.Discrete([0.01])) # Adam default: 0.001, SGD default: 0.01, RMSprop …Run Code Online (Sandbox Code Playgroud) 我有一个没有目标值的值样本。实际上,X 特征(预测变量)全部用于拟合隔离森林估计器。目标是确定哪些 X 特征以及未来出现的特征实际上是异常值。举例来说,假设我拟合一个数组 (340,3) => (n_samples, n_features)并且我预测这些特征来识别 340 个观察值中哪些是异常值。
到目前为止我的方法是:
首先我创建一个管道对象
from sklearn.pipeline import Pipeline
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import GridSearchCV
steps=[('IsolationForest', IsolationForest(n_jobs=-1, random_state=123))]
pipeline=Pipeline(steps)
Run Code Online (Sandbox Code Playgroud)
然后我创建一个用于超参数调整的参数网格
parameteres_grid={'IsolationForest__n_estimators':[25,50,75],
'IsolationForest__max_samples':[0.25,0.5,0.75,1.0],
'IsolationForest__contamination':[0.01,0.05],
'IsolationForest__bootstrap':[True, False]
}
Run Code Online (Sandbox Code Playgroud)
最后,我应用GridSearchCV算法
isolation_forest_grid=GridSearchCV(pipeline, parameteres_grid, scoring=scorer_f, cv=3, verbose=2)
isolation_forest_grid.fit(scaled_x_features.values)
Run Code Online (Sandbox Code Playgroud)
我的目标是确定最适合的评分函数(记为Scorer_f ),它将有效地选择最合适的隔离森林估计器来进行异常值检测。
到目前为止,基于这个出色的答案,我的评分如下:
isolation_forest_grid=GridSearchCV(pipeline, parameteres_grid, scoring=scorer_f, cv=3, verbose=2)
isolation_forest_grid.fit(scaled_x_features.values)
Run Code Online (Sandbox Code Playgroud)
简单解释一下,我不断地将批次中 5%(0.05 分位数)的观察值识别为异常值。因此,每个低于阈值的分数都被表示为异常值。因此,我指示 GridSearch 函数选择异常值最多的模型作为最坏情况。
让您尝尝结果:
isolation_forest_grid.cv_results_['mean_test_score']
array([4. , 4. , 4. , …Run Code Online (Sandbox Code Playgroud) python machine-learning outliers scikit-learn isolation-forest
免责声明 (1):这个问题支持这个 SO。在两位用户请求详细说明我的案例后。
免责声明 (2) - 29/11 添加:到目前为止,我已经看到了两种利用该功能的解决方案(在此 SO 中提出的以及支持性的解决方案)explode()。根据我对整个数据集(约 300 万行数据)所做的一些基准测试,RAM 确实会爆炸explode(),因此我将在数据集的样本上测试该函数,如果它有效,我将接受那些可能在较小的数据集上进行实验的人的方法解决方案表。
输入数据集(约 300 万行)来自80_000 个 IMDb 电影的 ml-latest 数据集以及 330_000 个用户的相应评分(您可以从此处ratings.csv下载 CSV 文件- 891mb)。
polars我使用like加载数据集movie_ratings = pl.read_csv(os.path.join(application_path + data_directory, "ratings.csv")),application_path并且data_directory是本地服务器上的父路径。
阅读数据集后,我的目标是生成用户在所有其他用户之间的余弦相似度。为此,首先我必须将评级表(约 300 万行)转换为每个用户 1 行的表。因此,我运行以下查询
## 1st computation bottleneck using UDF functions (2.5minutes for 250_000 rows)
users_metadata = movie_ratings.filter(
(pl.col("userId") != input_id) #input_id is a random userId. I prefer …Run Code Online (Sandbox Code Playgroud) 我正在运行以下代码:
list_of_paths 是一个包含以 avro 文件结尾的路径的列表。例如,
['folder_1/folder_2/0/2020/05/15/10/41/08.avro', 'folder_1/folder_2/0/2020/05/15/11/41/08.avro', 'folder_1/folder_2/0/2020/05/15/12/41/08.avro']
Run Code Online (Sandbox Code Playgroud)
注意:以上路径存储在Azure Data Lake存储中,以下过程在Databricks中执行
spark.conf.set("fs.azure.account.key.{0}.dfs.core.windows.net".format(storage_account_name), storage_account_key)
spark.conf.set("spark.sql.execution.arrow.enabled", "false")
begin_time = time.time()
for i in range(len(list_of_paths)):
try:
read_avro_data,avro_decoded=None,None
#Read paths from Azure Data Lake "abfss"
read_avro_data=spark.read.format("avro").load("abfss://{0}@{1}.dfs.core.windows.net/{2}".format(storage_container_name, storage_account_name, list_of_paths[i]))
except Exception as e:
custom_log(e)
Run Code Online (Sandbox Code Playgroud)
模式
read_avro_data.printSchema()
root
|-- SequenceNumber: long (nullable = true)
|-- Offset: string (nullable = true)
|-- EnqueuedTimeUtc: string (nullable = true)
|-- SystemProperties: map (nullable = true)
| |-- key: string
| |-- value: struct (valueContainsNull = true)
| | |-- …Run Code Online (Sandbox Code Playgroud) 我在 Python 中有以下极坐标 DF
df = pl.DataFrame({
"user_movies": [[7064, 7153, 78009], [6, 7, 1042], [99, 110, 3927], [2, 11, 152081], [260, 318, 195627]],
"user_ratings": [[5.0, 5.0, 5.0], [4.0, 2.0, 4.0], [4.0, 4.0, 3.0], [3.5, 3.0, 4.0], [1.0, 4.5, 0.5]],
"common_movies": [[7064, 7153], [7], [110, 3927], [2], [260, 195627]]
})
print(df.head())
Run Code Online (Sandbox Code Playgroud)
我想创建一个名为“common_movie_ ratings”的新列,该列将从每个评级列表中仅获取常见电影中评级的电影的索引。例如,对于第一行,我应该仅返回电影的评分 [7064, 7153,],对于第二行,我应该返回电影的评分 [7],依此类推。
为此,我创建了以下函数:
def get_common_movie_ratings(row): #Each row is a tuple of arrays.
common_movies = row[2] #the index of the tuple denotes the 3rd array, which represents the …Run Code Online (Sandbox Code Playgroud) 问候亲爱的社区成员。我正在创建一个神经网络来预测多标签 y。具体来说,神经网络接受 5 个输入(演员列表、情节摘要、电影特色、电影评论、片名)并尝试预测电影类型的顺序。在神经网络中,我使用了嵌入层和全局最大池化层。
然而,我最近发现了带有注意力的循环层,这是当今机器学习翻译中一个非常有趣的话题。所以,我想知道是否可以使用这些层之一,但只能使用 Plot Summary 输入。请注意,我不做 ml 翻译,而是做文本分类。
我的神经网络处于当前状态
def create_fit_keras_model(hparams,
version_data_control,
optimizer_name,
validation_method,
callbacks,
optimizer_version = None):
sentenceLength_actors = X_train_seq_actors.shape[1]
vocab_size_frequent_words_actors = len(actors_tokenizer.word_index)
sentenceLength_plot = X_train_seq_plot.shape[1]
vocab_size_frequent_words_plot = len(plot_tokenizer.word_index)
sentenceLength_features = X_train_seq_features.shape[1]
vocab_size_frequent_words_features = len(features_tokenizer.word_index)
sentenceLength_reviews = X_train_seq_reviews.shape[1]
vocab_size_frequent_words_reviews = len(reviews_tokenizer.word_index)
sentenceLength_title = X_train_seq_title.shape[1]
vocab_size_frequent_words_title = len(title_tokenizer.word_index)
model = keras.Sequential(name='{0}_{1}dim_{2}batchsize_{3}lr_{4}decaymultiplier_{5}'.format(sequential_model_name,
str(hparams[HP_EMBEDDING_DIM]),
str(hparams[HP_HIDDEN_UNITS]),
str(hparams[HP_LEARNING_RATE]),
str(hparams[HP_DECAY_STEPS_MULTIPLIER]),
version_data_control))
actors = keras.Input(shape=(sentenceLength_actors,), name='actors_input')
plot = keras.Input(shape=(sentenceLength_plot,), batch_size=hparams[HP_HIDDEN_UNITS], name='plot_input')
features = keras.Input(shape=(sentenceLength_features,), name='features_input')
reviews = keras.Input(shape=(sentenceLength_reviews,), name='reviews_input')
title = keras.Input(shape=(sentenceLength_title,), name='title_input')
emb1 …Run Code Online (Sandbox Code Playgroud) 我有以下火花数据框:
datalake_spark_dataframe_downsampled = pd.DataFrame(
{'id' : ['001', '001', '001', '001', '001', '002', '002', '002'],
'OuterSensorConnected':[0, 0, 0, 1, 0, 0, 0, 1],
'OuterHumidity':[31.784826, 32.784826, 33.784826, 43.784826, 23.784826, 54.784826, 31.784826, 31.784826],
'EnergyConsumption': [70, 70, 70, 70, 70, 70, 70, 70],
'DaysDeploymentDate': [10, 20, 21, 31, 41, 11, 19, 57],
'label': [0, 0, 1, 1, 1, 0, 0, 1]}
)
datalake_spark_dataframe_downsampled = spark.createDataFrame(datalake_spark_dataframe_downsampled )
# printSchema of the datalake_spark_dataframe_downsampled (spark df):
"root
|-- IMEI: string (nullable = true)
|-- OuterSensorConnected: integer (nullable …Run Code Online (Sandbox Code Playgroud) python ×9
apache-spark ×2
keras ×2
pyspark ×2
tensorflow ×2
bash ×1
databricks ×1
dataframe ×1
linux ×1
outliers ×1
scikit-learn ×1
tensorboard ×1