Change the values of a list? - list

liste = [1,2,8,12,19,78,34,197,1,-7,-45,-97,-32,23]
liste2 = []
def repetisjon(liste,liste2):
for count in liste:
if count > 0:
liste2.append(1)
elif count < 0:
liste2.append(0)
return liste2
return (liste2)
print (repetisjon(liste,liste2))
The point is to change all the values of the list. If it's greater than or equal to 0, it is to be replaced by the value 1. And if it's lower than 0, it is to be replaced by 0. But I wasn't able to change the current list. The only solution I found was to make a new list. But is there anyway to CHANGE the current list without making a new one? I tried this as well, but didnt work at all:
liste = [4,8,43,4,78,24,8,45,-78,-6,-7,-3,8,-12,4,36]
def repe (liste):
for count in liste:
if count > 0:
count == 1
else:
count == 0
print (liste)
repe(liste)

Here, I replace the content of liste with the transformed data. since sameliste points to the same list, its value changes too.
>>> sameliste = liste = [1,2,8,12,19,78,34,197,1,-7,-45,-97,-32,23]
>>> sameliste
[1, 2, 8, 12, 19, 78, 34, 197, 1, -7, -45, -97, -32, 23]
>>> liste
[1, 2, 8, 12, 19, 78, 34, 197, 1, -7, -45, -97, -32, 23]
>>> liste[:] = [int(x >= 0) for x in liste]
>>> liste
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1]
>>> sameliste
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1]
>>>

Related

Pytorch tensor dimension multiplication

I'm trying to implement the grad-camm algorithm:
https://arxiv.org/pdf/1610.02391.pdf
My arguments are:
activations: Tensor with shape torch.Size([1, 512, 14, 14])
alpha values : Tensor with shape torch.Size([512])
I want to multiply each activation (in dimension index 1 (sized 512)) in each corresponding alpha value: for example if the i'th index out of the 512 in the activation is 4 and the i'th alpha value is 5, then my new i'th activation would be 20.
The shape of the output should be torch.Size([1, 512, 14, 14])
Assuming the desired output is of shape (1, 512, 14, 14).
You can achieve this with torch.einsum:
torch.einsum('nchw,c->nchw', x, y)
Or with a simple dot product, but you will first need to add a couple of additional dimensions on y:
x*y[None, :, None, None]
Here's an example with x.shape = (1, 4, 2, 2) and y = (4,):
>>> x = torch.arange(16).reshape(1, 4, 2, 2)
tensor([[[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]]])
>>> y = torch.arange(1, 5)
tensor([1, 2, 3, 4])
>>> x*y[None, :, None, None]
tensor([[[[ 0, 1],
[ 2, 3]],
[[ 8, 10],
[12, 14]],
[[24, 27],
[30, 33]],
[[48, 52],
[56, 60]]]])

How to select rows by a column value in D with mir.ndslice?

I am browsing through mir.ndslice docs trying to figure out how to do a simple row selection by column.
In numpy I would do:
a = np.random.randint(0, 20, [4, 6])
# array([[ 8, 5, 4, 18, 1, 4],
# [ 2, 18, 15, 7, 18, 19],
# [16, 5, 4, 6, 11, 11],
# [15, 1, 14, 6, 1, 4]])
a[a[:,2] > 10] # select rows where the second column value is > 10
# array([[ 2, 18, 15, 7, 18, 19],
# [15, 1, 14, 6, 1, 4]])
Using mir library I naively tried:
import std.range;
import std.random;
import mir.ndslice;
auto a = generate!(() => uniform(0, 20)).take(24).array.sliced(4,6);
// [[12, 19, 3, 10, 19, 11],
// [19, 0, 0, 13, 9, 1],
// [ 0, 0, 4, 13, 1, 2],
// [ 6, 19, 14, 18, 14, 18]]
a[a[0..$,2] > 10];
But got
Error: incompatible types for `((ulong __dollar = a.length();) , a.opIndex(a.opSlice(0LU, __dollar), 2)) > (10)`: `Slice!(int*, 1LU, cast(mir_slice_kind)0)` and `int`
dmd failed with exit code 1.
So, I went through the docs and couldn't find anything that would look like np.where or similar. Is it even possible in mir?

ValueError: Tensor A must be from the same graph as Tensor B

I'm doing text matching using tensorflow, before i call tf.nn.embedding_lookup(word_embedding_matrix, combine_result), I have to combine some words from 2 sentence(get m words from sentence S1 and also get m words from sentence S2, then combine them together as "combine_result"), but when the code gose to tf.nn.embedding_lookup(word_embedding_matrix, combine_result) it gives me the error:
ValueError: Tensor("Reshape_7:0", shape=(1, 6), dtype=int32) must be
from the same graph as Tensor("word_embedding_matrix:0", shape=(26320,
50), dtype=float32_ref).
the code is as bellow:
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
NUM_CLASS = 2
SEQUENCE_LENGTH = 47
# Placeholders for input, output and dropout
input_x = tf.placeholder(tf.int32, [None, 2, SEQUENCE_LENGTH], name="input_x")
input_y = tf.placeholder(tf.float32, [None, NUM_CLASS], name="input_y")
dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")
def n_grams(text, window_size):
text_left_window = []
# text_left_window = tf.convert_to_tensor(text_left_window, dtype=tf.int32)
for z in range(SEQUENCE_LENGTH-2):
text_left = tf.slice(text, [z], [window_size])
text_left_window = tf.concat(0, [text_left_window, text_left])
text_left_window = tf.reshape(text_left_window, [-1, window_size])
return text_left_window
def inference(vocab_size, embedding_size, batch_size, slide_window_size, conv_window_size):
# # Embedding layer
word_embedding_matrix = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),
name="word_embedding_matrix")
# convo_unit = tf.Variable(tf.random_uniform([slide_window_size*2, ], -1.0, 1.0), name="convo_unit")
text_comp_result = []
for x in range(batch_size):
# input_x_slice_reshape = [[1 1 1...]
# [2 2 2...]]
input_x_slice = tf.slice(input_x, [x, 0, 0], [1, 2, SEQUENCE_LENGTH])
input_x_slice_reshape = tf.reshape(input_x_slice, [2, SEQUENCE_LENGTH])
# text_left_flat: [294, 6, 2, 6, 2, 57, 2, 57, 147, 57, 147, 5, 147, 5, 2,...], length = SEQUENCE_LENGTH
# text_right_flat: [17, 2, 2325, 2, 2325, 5366, 2325, 5366, 81, 5366, 81, 1238,...]
text_left = tf.slice(input_x_slice_reshape, [0, 0], [1, SEQUENCE_LENGTH])
text_left_flat = tf.reshape(text_left, [-1])
text_right = tf.slice(input_x_slice_reshape, [1, 0], [1, SEQUENCE_LENGTH])
text_right_flat = tf.reshape(text_right, [-1])
# extract both text.
# text_left_window: [[294, 6, 2], [6, 2, 57], [2, 57, 147], [57, 147, 5], [147, 5, 2],...]
# text_right_window: [[17, 2, 2325], [2, 2325, 5366], [2325, 5366, 81], [5366, 81, 1238],...]
text_left_window = n_grams(text_left_flat, slide_window_size)
text_right_window = n_grams(text_right_flat, slide_window_size)
text_left_window_sha = text_left_window.get_shape()
print 'text_left_window_sha:', text_left_window_sha
# composite the slice
text_comp_list = []
# text_comp_list = tf.convert_to_tensor(text_comp_list, dtype=tf.float32)
for l in range(SEQUENCE_LENGTH-slide_window_size+1):
text_left_slice = tf.slice(text_left_window, [l, 0], [1, slide_window_size])
text_left_slice_flat = tf.reshape(text_left_slice, [-1])
for r in range(SEQUENCE_LENGTH-slide_window_size+1):
text_right_slice = tf.slice(text_right_window, [r, 0], [1, slide_window_size])
text_right_slice_flat = tf.reshape(text_right_slice, [-1])
# convo_unit = [294, 6, 2, 17, 2, 2325]
convo_unit = tf.concat(0, [text_left_slice_flat, text_right_slice_flat])
convo_unit_reshape = tf.reshape(convo_unit, [-1, slide_window_size*2])
# convo_unit_shape_val = convo_unit_reshape.get_shape()
# print 'convo_unit_shape_val:', convo_unit_shape_val
embedded_chars = tf.nn.embedding_lookup(word_embedding_matrix, convo_unit_reshape)
embedded_chars_expanded = tf.expand_dims(embedded_chars, -1)
...
could please someone help me? Thank you very much!
Yaroslav answered in a comment above - moving to an answer:
This error happens when you create new default graph. Try to do tf.reset_default_graph() before the computation and not create any more graphs (i.e., calls to tf.Graph)

creating list of lists alimented with data from database gives empty list

I'm trying to plot a graph that shows the average call duration every day each minute for 7 days in the same plot, now I'm defining the function that will give me the data asked according to conditions which will be plotted but I'm always getting a list of empty lists.can any one help me tof ind the bug? (acc is just an example of data from the global database)
This is the function:
import time
import calendar
from datetime import datetime
from itertools import repeat
acc=[{u'switch_id': 3, u'hangup_cause_id': 7, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 1), u'duration': 32}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 8), u'duration': 20}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 10), u'duration': 17}]
t = datetime.now()
y = t.year
m = t.month
d = t.day
donnees=[]
for k in range(7):
try:
m = t.month
data=[]
liste=[]
liste_time=[]
for i in acc:
if (i["start_uepoch"].year == y and i["start_uepoch"].month == m and i["start_uepoch"].day == d-k):
liste.append([i["start_uepoch"],i["duration"]])
for q in range(24):
for mnt in range(60):
liste2=[]
ACD=0
somme_duration=0
n=0
for p in liste:
if (p[0].hour==q and p[0].minute == mnt):
liste2.append(p[1])
temps=p[0]
if len(liste2)!=0:
for j in liste2:
somme_duration+=j
n+=1
ACD=round((float(somme_duration)/n)*100)/100
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(ACD)
else:
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(0)
except:
pass
donnees.append(data)
print donnees
This is due to your try / except condition, if you remove it by settings temps = None after your loop it solves you issue :
import time
import calendar
from datetime import datetime
from itertools import repeat
acc=[{u'switch_id': 3, u'hangup_cause_id': 7, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 1), u'duration': 32}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 8), u'duration': 20}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 10), u'duration': 17}]
t = datetime.now()
y = t.year
m = t.month
d = t.day
donnees=[]
for k in range(7):
m = t.month
data=[]
liste=[]
liste_time=[]
for i in acc:
if (i["start_uepoch"].year == y and i["start_uepoch"].month == m and i["start_uepoch"].day == d-k):
liste.append([i["start_uepoch"],i["duration"]])
for q in range(24):
for mnt in range(60):
temps = None
liste2=[]
ACD=0
somme_duration=0
n=0
for p in liste:
if (p[0].hour==q and p[0].minute == mnt):
liste2.append(p[1])
temps=p[0]
if temps:
if len(liste2)!=0:
for j in liste2:
somme_duration+=j
n+=1
ACD=round((float(somme_duration)/n)*100)/100
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(ACD)
else:
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(0)
donnees.append(data)
print donnees

How to replace values in a list at indexed positions?

I have following list of text positions with all values being set to '-999' as default:
List = [(70, 55), (170, 55), (270, 55), (370, 55),
(70, 85), (170, 85), (270, 85), (370, 85)]
for val in List:
self.depth = wx.TextCtrl(panel, -1, value='-999', pos=val, size=(60,25))
I have indexed list and corresponding values at them such as:
indx = ['2','3']
val = ['3.10','4.21']
I want to replace index locations '2' and '3' with values '3.10' and '4.21' respectively in 'List' and keep the rest as '-999'. Any suggestions?
Solved. I used following example:
>>> s, l, m
([5, 4, 3, 2, 1, 0], [0, 1, 3, 5], [0, 0, 0, 0])
>>> d = dict(zip(l, m))
>>> d #dict is better then using two list i think
{0: 0, 1: 0, 3: 0, 5: 0}
>>> [d.get(i, j) for i, j in enumerate(s)]
[0, 0, 3, 0, 1, 0]
from similar question.