我正在关注这个页面。我加载了一个数据集并将其转换为 Pandas 数据框,然后转换回数据集。我无法匹配特征,因为数据集不匹配。如何设置新数据集的特征以使它们与旧数据集匹配?
import pandas as pd
import datasets
from transformers import LongformerTokenizerFast, LongformerForSequenceClassification, Trainer, TrainingArguments, LongformerConfig
import torch.nn as nn
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from tqdm import tqdm
#import wandb
import os
train_data_s1, test_data_s1 = datasets.load_dataset('imdb', split =['train[0:500]', 'test[0:500]'],
cache_dir='/media/data_files/github/website_tutorials/data')
print (type (train_data_s1))
#<class 'datasets.arrow_dataset.Dataset'>
#converting to pandas - https://towardsdatascience.com/use-the-datasets-library-of-hugging-face-in-your-next-nlp-project-94e300cca850
print (type(train_data_s1))
df_pandas = pd.DataFrame(train_data_s1)
print (type(df_pandas))
#<class 'datasets.arrow_dataset.Dataset'>
#<class 'pandas.core.frame.DataFrame'>
from datasets import Dataset …Run Code Online (Sandbox Code Playgroud) 我早些时候发布了这个问题。我想嵌入类似于这个youtube视频,时间 33 分钟以后。
1)我不认为我从CLS令牌中获得的嵌入与 YouTube 视频中显示的相似。我试图执行语义相似性并得到了可怕的结果。有人可以确认我得到的嵌入是否与视频的 35.27 标记中提到的嵌入相似?
2)如果上述问题的答案是“不相似”,那么我如何使用我编写的代码获得我正在寻找的嵌入?
3)如果第一个问题的答案是“它们很相似”,那么为什么我会得到可怕的结果?我需要使用更多数据进行微调吗?
我用来微调的代码如下。它来自这个页面。对该代码进行了很少的更改以返回CLS嵌入。这些变化是基于对我的问题的回答
train_InputExamples = train2.apply(lambda x: run_classifier.InputExample(guid=None, # Globally unique ID for bookkeeping, unused in this example
text_a = x[DATA_COLUMN],
text_b = None,
label = x[LABEL_COLUMN]), axis = 1)
"""
test_InputExamples = test2.apply(lambda x: run_classifier.InputExample(guid=None,
text_a = x[DATA_COLUMN],
text_b = None,
label = x[LABEL_COLUMN]), axis = 1)
"""
# In[17]:
# This is a path to an uncased …Run Code Online (Sandbox Code Playgroud) 我正在尝试此页面中的代码。我跑到这个部分LR (tf-idf)并得到了类似的结果
之后我决定尝试一下GridSearchCV。我的问题如下:
1)
#lets try gridsearchcv
#https://www.kaggle.com/enespolat/grid-search-with-logistic-regression
from sklearn.model_selection import GridSearchCV
grid={"C":np.logspace(-3,3,7), "penalty":["l2"]}# l1 lasso l2 ridge
logreg=LogisticRegression(solver = 'liblinear')
logreg_cv=GridSearchCV(logreg,grid,cv=3,scoring='f1')
logreg_cv.fit(X_train_vectors_tfidf, y_train)
print("tuned hpyerparameters :(best parameters) ",logreg_cv.best_params_)
print("best score :",logreg_cv.best_score_)
#tuned hpyerparameters :(best parameters) {'C': 10.0, 'penalty': 'l2'}
#best score : 0.7390325593588823
Run Code Online (Sandbox Code Playgroud)
然后我手动计算了f1分数。为什么不匹配?
logreg_cv.predict_proba(X_train_vectors_tfidf)[:,1]
final_prediction=np.where(logreg_cv.predict_proba(X_train_vectors_tfidf)[:,1]>=0.5,1,0)
#https://www.statology.org/f1-score-in-python/
from sklearn.metrics import f1_score
#calculate F1 score
f1_score(y_train, final_prediction)
0.9839388145315489
Run Code Online (Sandbox Code Playgroud)
scoring='precision'为什么会出现以下错误?我不清楚主要是因为我有相对平衡的数据集(55-45%)并且f1需要precision计算没有任何问题#lets try gridsearchcv #https://www.kaggle.com/enespolat/grid-search-with-logistic-regression
from sklearn.model_selection import GridSearchCV
grid={"C":np.logspace(-3,3,7), …Run Code Online (Sandbox Code Playgroud) 我有以下工作代码.当我在不同的数据集上复制相同的东西时,我得到错误:(
#max by values
df <- data.frame(age=c(5,NA,9), marks=c(1,2,7), story=c(2,9,NA))
df
df$colMax <- apply(df[,1:3], 1, function(x) max(x[x != 9],na.rm=TRUE))
df
Run Code Online (Sandbox Code Playgroud)
我试图在更大的数据上做同样的事情,我收到警告,为什么?
maindata$max_pc_age <- apply(maindata[,c(paste("Q2",1:18,sep="_"))], 1, function(x) max(x[x != 9],na.rm=TRUE))
50: In max(x[x != 9], na.rm = TRUE) :
no non-missing arguments to max; returning -Inf
Run Code Online (Sandbox Code Playgroud)
为了更好地理解问题,我做了如下更改,但仍然收到警告
maindata$max_pc_age <- apply(maindata[,c(paste("Q2",1:18,sep="_"))], 1, function(x) max(x,na.rm=TRUE))
1: In max(x, na.rm = TRUE) : no non-missing arguments to max; returning -Inf
Run Code Online (Sandbox Code Playgroud) 我有下面的代码将图像保存到我的电脑.我希望将图像围绕其中心(或左下角)旋转45,90和135度,然后保存为3个不同的图像.我怎么能这样做?
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
plotRGB(x)
png(width=50, height=50)
par(mai=c(0,0,0,0))
image(x)
dev.off()
Run Code Online (Sandbox Code Playgroud)
--------- UPDATE1 -------------------------
根据接受的答案,工作代码如下
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
r1
x <- crop(r1, extent(0,ncol(r1),0,nrow(r1)))
plotRGB(x)
x1 <- 0:ncol(x)
y1 <- 0:nrow(x)
z <- matrix(1, nrow=length(x1), ncol=length(y1))
col.mat <- t(apply(matrix(rgb(getValues(x)/255), nrow=nrow(x), byrow=TRUE), 2, rev))
# Rotate 45 degrees
persp(x1, y1, z, zlim=c(0,2), theta = 20, phi = 90,
col = col.mat, scale=FALSE, border=NA, box=FALSE)
png("SaveThisPlot.png")
persp(x1, y1, z, zlim=c(0,2), theta = 20, phi = 90, …Run Code Online (Sandbox Code Playgroud) 我想解决这个挑战.我喜欢的语言是R.我不确定如何接收输入.在hackerrank编码窗口,它说
"# Enter your code here. Read input from STDIN. Print output to STDOUT"
Run Code Online (Sandbox Code Playgroud)
到目前为止,我习惯通过使用来接收输入
v1 <- readline("Enter two integers: ")
Run Code Online (Sandbox Code Playgroud)
我该如何收到hackerrank的输入?我试图看到解决的例子,但找不到任何已解决的例子.
更新1
下面的代码在R中工作.唯一的问题是步数和键盘输入不提供球值.我们必须在第1行和第2行手动更新它们.我如何在解决方案下获得更新,以便它适用于hackerrank?
steps=4
ball_numbers=c(1,2,2,2)
d=as.data.frame(c(0,1))
for (i in (1:(length(ball_numbers)-1)))
{
assign(x = paste("A", i, sep = ""),value = c(0,1))
e <- as.data.frame(get(paste("A", i, sep = "")))
colnames(e) <- paste("A", i, sep="")
d <- merge(d,e)
}
d=as.matrix(t(d))
answer=sum(ball_numbers %*% d)/ncol(d)
Run Code Online (Sandbox Code Playgroud)
UPDATE2
下面的代码产生正确答案
# Enter your code here. Read input from STDIN. Print output to STDOUT
nums <- …Run Code Online (Sandbox Code Playgroud) 我的问题是基于这个问题.使用它我写下面的代码,其中第一组坐标是纽约LGA机场,而第二组坐标是纽约EWR机场.我得到了答案33713.那是英里还是公里?一个快速的谷歌检查说,距离应该是33英里(但它不是直线/弧距离:(这是一个公路的距离).包文件说答案是以米为单位.请澄清.这是一个给出2个坐标找到地球上距离的好方法?我怎样才能在里程中找到答案?
library(geosphere)
distm (c(40.777250, -73.872610), c(40.6895, -74.1745), fun = distHaversine)
[,1]
[1,] 33713.61
Run Code Online (Sandbox Code Playgroud) 如何将data.frame abc添加/附加到我之前打开的文本文件中.我正在向该文件写一些重要信息,然后我想在该信息下面附加该data.frame.当我尝试使用cat编写data.frame abc时出错.
fileConn<-file("metadata.txt","w+")
smoke <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
smoke <- as.data.frame(smoke)
table <- sapply (smoke, class)
abc <- data.frame(nm = names(smoke), cl = sapply(unname(smoke), class))
cat("some imp info","\n", file=fileConn)
cat(abc,"\n", file=fileConn)
close(fileConn)
class(abc)
Run Code Online (Sandbox Code Playgroud) 所附模型显示了如何在不平衡分类问题的情况下添加偏差initial_bias = np.log([pos/neg])。如果你有不平衡数据的多类分类,有没有办法增加偏差,比如说 5 个类,其中类具有分布(0.4,0.3,0.2.0.08 and 0.02)
2)在这种情况下如何计算和使用班级权重?
I found a way to apply weights, still not sure how to use bias
#####adding weights 20 Feb
weight_for_0 = ( 1/ 370)*(370+ 977+ 795)/3
weight_for_1 = ( 1/ 977)*(370+ 977+ 795)/3
weight_for_2 = (1 / 795)*(370+ 977+ 795)/3
#array([0, 1, 2]), array([370, 977, 795])
class_weights_dict = {0: weight_for_0, 1: weight_for_1, 2:weight_for_2}
class_weights_dict
Dcnn.fit(train_dataset,
epochs=NB_EPOCHS,
callbacks=[MyCustomCallback()],verbose=2,validation_data=test_dataset, class_weight=class_weights_dict)
Run Code Online (Sandbox Code Playgroud) 我正在复制此页面的代码。我已将 BERT 模型下载到本地系统并获取句子嵌入。
我有大约 500,000 个句子需要句子嵌入,这需要花费很多时间。
。
#!pip install transformers
import torch
import transformers
from transformers import BertTokenizer, BertModel
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased',
output_hidden_states = True, # Whether the model returns all hidden-states.
)
# Put the model in "evaluation" mode, meaning feed-forward operation.
model.eval()
corpa=["i am a boy","i live in a city"]
storage=[]#list to store all embeddings
for text in corpa:
# Add the special tokens.
marked_text = "[CLS] " + text + …Run Code Online (Sandbox Code Playgroud) python nlp bert-language-model huggingface-transformers huggingface-tokenizers