我使用 Python 和 Keras 和 Tensorflow 作为后端,并且我希望为我的模型使用尽可能小的输入图像。
VGG19 应用程序表示,它允许输入宽度和高度低至 32 的形状。几周前,Keras 网站上的最小值为 48。我用48没问题。现在,我想尝试 32,但我做不到,因为我得到:
ValueError: Input size must be at least 48x48; got `input_shape=(32, 32, 3)`
Run Code Online (Sandbox Code Playgroud)
我提到我将 Keras 更新到了 2.2.2 版本,并且还删除了 VGG19 的权重模型文件(来自~/.keras/models/)。如果我将 input_shape 设置为 (48, 48, 3),它会再次下载模型,否则会出现上述错误。
简而言之,我的代码只想加载预训练的模型:
vgg_conv = VGG19(weights='imagenet', include_top=False, input_shape=(32, 32, 3))
Run Code Online (Sandbox Code Playgroud)
任何可以遵循的想法都值得赞赏。
当您查看 pytorch 代码内部如何构建网络架构时,我们需要扩展torch.nn.Module和 内部__init__,我们定义了网络模块,pytorch 将跟踪这些模块的参数梯度。然后在forward函数内部,我们定义应该如何为我们的网络完成前向传递。
我在这里不明白的是批量学习将如何发生。在包括forward函数在内的上述定义中,我们都不关心网络输入的批次维度。为了执行批量学习,我们唯一需要设置的是向输入添加一个与批量大小相对应的额外维度,但如果我们使用批量学习,网络定义中的任何内容都不会改变。至少,这是我在这里的代码中看到的。
因此,如果到目前为止我解释的所有内容都是正确的(如果您让我知道我是否误解了某些内容,我将不胜感激),如果在我们的网络类的定义中没有声明关于批量大小的任何内容,则如何执行批量学习(继承的类torch.nn.Module)?具体来说,我很想知道当我们只设置nn.MSELoss批量维度时,如何在pytorch中实现批量梯度下降算法。
基本上就是标题;keras.preprocessing.text.TokenizerPytorch 中有类似的东西吗?我还没有找到任何一个可以提供所有实用程序而无需手工制作的东西。
我在情感分析管道中使用默认模型没有任何问题。
# Allocate a pipeline for sentiment-analysis
nlp = pipeline('sentiment-analysis')
nlp('I am a black man.')
>>>[{'label': 'NEGATIVE', 'score': 0.5723695158958435}]
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试通过添加特定模型来稍微自定义管道时。它抛出一个KeyError。
nlp = pipeline('sentiment-analysis',
tokenizer = AutoTokenizer.from_pretrained("DeepPavlov/bert-base-cased-conversational"),
model = AutoModelWithLMHead.from_pretrained("DeepPavlov/bert-base-cased-conversational"))
nlp('I am a black man.')
>>>---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-55-af7e46d6c6c9> in <module>
3 tokenizer = AutoTokenizer.from_pretrained("DeepPavlov/bert-base-cased-conversational"),
4 model = AutoModelWithLMHead.from_pretrained("DeepPavlov/bert-base-cased-conversational"))
----> 5 nlp('I am a black man.')
6
7
~/opt/anaconda3/lib/python3.7/site-packages/transformers/pipelines.py in __call__(self, *args, **kwargs)
721 outputs = super().__call__(*args, **kwargs)
722 scores = np.exp(outputs) / np.exp(outputs).sum(-1, keepdims=True)
--> 723 …Run Code Online (Sandbox Code Playgroud) 想做类似的事情
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
outputs = model(input_ids)
last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
Run Code Online (Sandbox Code Playgroud)
(来自此线程)使用 longformer
文档示例似乎做了类似的事情,但令人困惑(特别是如何设置注意力掩码,我假设我想将其设置为[CLS]令牌,该示例将全局注意力设置为我认为的随机值)
>>> import torch
>>> from transformers import LongformerModel, LongformerTokenizer
>>> model = LongformerModel.from_pretrained('allenai/longformer-base-4096', return_dict=True)
>>> tokenizer = LongformerTokenizer.from_pretrained('allenai/longformer-base-4096')
>>> SAMPLE_TEXT = ' '.join(['Hello world! '] * 1000) # long input document
>>> input_ids = torch.tensor(tokenizer.encode(SAMPLE_TEXT)).unsqueeze(0) # batch …Run Code Online (Sandbox Code Playgroud) 我想匹配一个看起来像这样的表达式:
(<some value with spaces and m$1124any crazy signs> (<more values>) <even more>)
Run Code Online (Sandbox Code Playgroud)
我只是想沿着圆括号 () 拆分这些值。目前,我可以减少 s-expression 示例中的 pyparsing 开销,这非常广泛且无法理解(恕我直言)。
我尽可能使用该nestedExpr语句,将其减少为一行:
import pyparsing as pp
parser = pp.nestedExpr(opener='(', closer=')')
print parser.parseString(example, parseAll=True).asList()
Run Code Online (Sandbox Code Playgroud)
结果似乎也被分割在空白处,这是我不想要的:
skewed_output = [['<some',
'value',
'with',
'spaces',
'and',
'm$1124any',
'crazy',
'signs>',
['<more', 'values>'],
'<even',
'more>']]
expected_output = [['<some value with spaces and m$1124any crazy signs>'
['<more values>'], '<even more>']]
best_output = [['some value with spaces and m$1124any crazy signs'
['more vlaues'], 'even more']]
Run Code Online (Sandbox Code Playgroud)
或者,我很乐意指出我可以阅读一些 …
考虑到室内和室外的气候,我试图预测墙壁的湿热响应。根据文献研究,我相信使用RNN应该可以做到这一点,但我一直无法获得很好的准确性。
该数据集具有12个输入要素(外部和内部气候数据的时间序列)和10个输出要素(湿热响应的时间序列),均包含10年的小时值。该数据是使用湿热模拟软件创建的,没有丢失的数据。
与大多数时间序列预测问题不同,我想在每个时间步长预测输入要素时间序列的全长响应,而不是时间序列的后续值(例如财务时间序列预测)。我还没有找到类似的预测问题(在相似或其他领域),因此,如果您知道其中一个,那么欢迎参考。
我认为使用RNN应该可以实现,因此我目前正在使用Keras的LSTM。在训练之前,我会通过以下方式预处理数据:
StandardScalerSklearn 归一化训练集(零均值,单位方差)。类似地使用均值与训练集的方差归一化测试集。这导致:X_train.shape = (1, 61320, 12),y_train.shape = (1, 61320, 10),X_test.shape = (1, 17520, 12),y_test.shape = (1, 17520, 10)
由于这些都是较长的时间序列,因此我将使用有状态LSTM并按照此处的说明使用stateful_cut()函数削减时间序列。我只有1个样本,所以只有1个batch_size。因为T_after_cut我尝试了24和120(24 * 5);24似乎可以提供更好的结果。这导致X_train.shape = (2555, 24, 12),y_train.shape = (2555, 24, 10),X_test.shape = (730, 24, 12),y_test.shape = (730, 24, 10)。
接下来,我按以下步骤构建和训练LSTM模型:
model = Sequential()
model.add(LSTM(128,
batch_input_shape=(batch_size,T_after_cut,features),
return_sequences=True,
stateful=True,
)) …Run Code Online (Sandbox Code Playgroud) machine-learning time-series prediction lstm recurrent-neural-network
我怀疑使用与GPU支持的Torch和使用以下功能的Numpy进行元素逐次乘法,结果发现Numpy的循环速度比Torch快,但事实并非如此。
我想知道如何使用GPU使用Torch执行常规算术运算。
注意:我在Google Colab笔记本中运行了这些代码段
定义默认张量类型以启用全局GPU标志
torch.set_default_tensor_type(torch.cuda.FloatTensor if
torch.cuda.is_available() else
torch.FloatTensor)
Run Code Online (Sandbox Code Playgroud)
初始化Torch变量
x = torch.Tensor(200, 100) # Is FloatTensor
y = torch.Tensor(200,100)
Run Code Online (Sandbox Code Playgroud)
有问题的功能
def mul(d,f):
g = torch.mul(d,f).cuda() # I explicitly called cuda() which is not necessary
return g
Run Code Online (Sandbox Code Playgroud)
当调用上面的函数为
%timeit mul(x,y)
返回值:
最慢的运行比最快的运行时间长10.22倍。这可能意味着正在缓存中间结果。10000次循环,最好为3次:每个循环50.1 µs
现在试用numpy,
使用了与割炬变量相同的值
x_ = x.data.cpu().numpy()
y_ = y.data.cpu().numpy()
Run Code Online (Sandbox Code Playgroud)
def mul_(d,f):
g = d*f
return g
Run Code Online (Sandbox Code Playgroud)
%timeit mul_(x_,y_)
退货
最慢的运行时间比最快的运行时间长了12.10倍。这可能意味着正在缓存中间结果。100000次循环,每循环3:7.73 µs最佳
需要一些帮助来了解启用GPU的Torch操作。
我试图从 Transformer 导入 BertModel,但失败了。这是我正在使用的代码
from transformers import BertModel, BertForMaskedLM
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误
ImportError: cannot import name 'BertModel' from 'transformers'
Run Code Online (Sandbox Code Playgroud)
谁能帮我解决这个问题吗?
python nlp pytorch bert-language-model huggingface-transformers
我想应用 Roberta 模型来实现文本相似度。给定一对句子,输入的格式应为<s> A </s></s> B </s>。我想出了两种可能的方法来生成输入ID,即
A)
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained('roberta-base')
list1 = tokenizer.encode('Very severe pain in hands')
list2 = tokenizer.encode('Numbness of upper limb')
sequence = list1+[2]+list2[1:]
Run Code Online (Sandbox Code Playgroud)
在这种情况下,顺序是[0, 12178, 3814, 2400, 11, 1420, 2, 2, 234, 4179, 1825, 9, 2853, 29654, 2]
b)
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained('roberta-base')
list1 = tokenizer.encode('Very severe pain in hands', add_special_tokens=False)
list2 = tokenizer.encode('Numbness of upper limb', add_special_tokens=False)
sequence = [0]+list1+[2,2]+list2+[2]
Run Code Online (Sandbox Code Playgroud)
在这种情况下,顺序是[0, 25101, …
我有一批形状为[5,1,100,100]( batch_size x dims x ht x wd)的分割掩码,我必须在 tensorboardX 中使用 RGB 图像批次显示它们[5,3,100,100]。我想在分割掩码的第二个轴上添加两个虚拟维度以使其[5,3,100,100]在将其传递给torch.utils.make_grid. 我曾尝试unsqueeze,expand并view但我不能够做到这一点。有什么建议?
df = pd.read_csv("school_data.csv")
col1 col2
0 [1,2,3] [4,5,6]
1 [0,5,3] [6,2,5]
Run Code Online (Sandbox Code Playgroud)
想要o/p
col1 col2 col3
0 [1,2,3] [4,5,6] [1,2,3,4,5,6]
1 [0,5,3] [6,2,5] [0,5,3,6,2,5]
Run Code Online (Sandbox Code Playgroud)
col1 和 col2 值是唯一的,使用熊猫
pytorch ×6
python ×5
nlp ×3
keras ×2
python-3.x ×2
tensorflow ×2
gpu ×1
lstm ×1
numpy ×1
pandas ×1
parsing ×1
prediction ×1
pyparsing ×1
tensorboard ×1
time-series ×1
vgg-net ×1