我不确定我是否完全理解下面的小片段(在 Py v3.6.7 上)中发生的事情。如果有人能向我解释我们如何成功地改变列表,即使 Python 抛出了一个错误,那就太好了。
我知道我们可以改变一个列表并更新它,但是错误是什么?就像我的印象是,如果有错误,那么x应该保持不变。
x = ([1, 2], )
x[0] += [3,4] # ------ (1)
Run Code Online (Sandbox Code Playgroud)
第 (1) 行抛出的 Traceback 是
> TypeError: 'tuple' object doesn't support item assignment..
Run Code Online (Sandbox Code Playgroud)
我明白错误意味着什么,但我无法获得它的上下文。
但是现在如果我尝试打印变量的值x,Python 会说它是,
> TypeError: 'tuple' object doesn't support item assignment..
Run Code Online (Sandbox Code Playgroud)
据我所知,异常发生在 Python 允许列表的突变发生之后,然后希望它尝试重新分配它。我认为它吹到了那里,因为元组是不可变的。
有人可以解释一下引擎盖下发生了什么吗?
编辑 - 1 错误来自 ipython 控制台作为图像;
我想通过代码xor练习keras,但结果不对,接下来是我的代码,感谢大家帮助我.
from keras.models import Sequential
from keras.layers.core import Dense,Activation
from keras.optimizers import SGD
import numpy as np
model = Sequential()# two layers
model.add(Dense(input_dim=2,output_dim=4,init="glorot_uniform"))
model.add(Activation("sigmoid"))
model.add(Dense(input_dim=4,output_dim=1,init="glorot_uniform"))
model.add(Activation("sigmoid"))
sgd = SGD(l2=0.0,lr=0.05, decay=1e-6, momentum=0.11, nesterov=True)
model.compile(loss='mean_absolute_error', optimizer=sgd)
print "begin to train"
list1 = [1,1]
label1 = [0]
list2 = [1,0]
label2 = [1]
list3 = [0,0]
label3 = [0]
list4 = [0,1]
label4 = [1]
train_data = np.array((list1,list2,list3,list4)) #four samples for epoch = 1000
label = np.array((label1,label2,label3,label4))
model.fit(train_data,label,nb_epoch = 1000,batch_size = 4,verbose = …Run Code Online (Sandbox Code Playgroud) fast.ai的github存储库 (因为代码提升了构建在PyTorch之上的库)
请滚动讨论一下
我正在运行以下代码,并在尝试将数据传递给predict_array函数时出错
当我尝试使用它直接在单个图像上进行预测时代码失败但是当相同的图像在test文件夹中时它运行完美
from fastai.conv_learner import *
from planet import f2
PATH = 'data/shopstyle/'
metrics=[f2]
f_model = resnet34
def get_data(sz):
tfms = tfms_from_model(f_model, sz, aug_tfms=transforms_side_on, max_zoom=1.05)
return ImageClassifierData.from_csv(PATH, 'train', label_csv, tfms=tfms, suffix='.jpg', val_idxs=val_idxs, test_name='test')
def print_list(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
label_csv = f'{PATH}prod_train.csv'
n = len(list(open(label_csv)))-1
val_idxs = get_cv_idxs(n)
sz = 64
data = get_data(sz)
print("Loading model...")
learn = ConvLearner.pretrained(f_model, data, metrics=metrics)
learn.load(f'{sz}') …Run Code Online (Sandbox Code Playgroud) 版本1
import string, pandas as pd
def correct_contraction1(x, dic):
for word in dic.keys():
if word in x:
x = x.replace(word, " " + dic[word]+ " ")
return x
Run Code Online (Sandbox Code Playgroud)
版本2
import string, pandas as pd
def correct_contraction2(x, dic):
for word in dic.keys():
if " " + word + " " in x:
x = x.replace(" " + word + " ", " " + dic[word]+ " ")
return x
Run Code Online (Sandbox Code Playgroud)
我如何使用它们:
train['comment_text'] = train['comment_text'].apply(correct_contraction1,args=(contraction_mapping,))
#3 mins 40 sec without that space thing …Run Code Online (Sandbox Code Playgroud) 今天,我在Python 2.7.13 中运行了下面给出的代码,发现列表大小在为空时不是 0:
import sys
data = []
for k in range(n):
a = len(data)
b = sys.getsizeof(data)
print('Length:{0:3d};Size in bytes:{1:4d}'.format(a,b))
data.append(None)
Run Code Online (Sandbox Code Playgroud)
我机器上的输出:
Length: 0; Size in bytes : 72
Length: 1; Size in bytes : 104
Length: 2; Size in bytes : 104
Length: 3; Size in bytes : 104
Length: 4; Size in bytes : 104
Length: 5; Size in bytes : 136
Length: 6; Size in bytes : 136
Length: 7; Size in bytes …Run Code Online (Sandbox Code Playgroud) python ×5
python-3.x ×3
immutability ×1
keras ×1
list ×1
pandas ×1
python-2.7 ×1
pytorch ×1
regex ×1
torch ×1
tuples ×1
xor ×1