In cases where the number of items in my population is equal to the number I want sample, I get the error.
Here is a minimal example
import random
subset = random.sample( set([312996, 529565, 312996, 130934]) , 4)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-b816cd5c3651> in <module>()
----> 1 subset = random.sample( set([312996, 529565, 312996, 130934]) , 4)
/opt/conda/lib/python3.6/random.py in sample(self, population, k)
318 n = len(population)
319 if not 0 <= k <= n:
--> 320 raise ValueError("Sample larger than population or is negative")
321 result = [None] * k
322 setsize = 21 # size of a small set minus size of an empty list
ValueError: Sample larger than population or is negative
EDIT
It seems that this only occurs for those 4 numbers. I tried
import random
subset = random.sample( set([2, 5, 8, 9]) , 4)
And I didn’t get an error. I can’t figure out what the issue is for the first one. . .
Hi,
I have a small dataset that I am trying to augment. For some of the questions, I am getting the following error:
ValueError Traceback (most recent call last)
<ipython-input-337-336aea02b7a2> in <module>
2 print(len(text))
3 aug = naw.BertAug(action="insert")
----> 4 augmented_text = aug.augment(text)
5 print("Original:")
6 print(text)
~/anaconda3/lib/python3.7/site-packages/nlpaug/base_augmenter.py in augment(self, data)
69
70 if self.action == Action.INSERT:
---> 71 return self.insert(data)
72 elif self.action == Action.SUBSTITUTE:
73 return self.substitute(data)
~/anaconda3/lib/python3.7/site-packages/nlpaug/augmenter/word/bert.py in insert(self, data)
85 for aug_idx in aug_idxes:
86 results.insert(aug_idx, nml.Bert.MASK)
---> 87 new_word = self.sample(self.model.predict(results, nml.Bert.MASK, self.aug_n), 1)[0]
88 results[aug_idx] = new_word
89
~/anaconda3/lib/python3.7/site-packages/nlpaug/base_augmenter.py in sample(cls, x, num)
109 @classmethod
110 def sample(cls, x, num):
--> 111 return random.sample(x, num)
112
113 def generate_aug_cnt(self, size, aug_p=None):
~/anaconda3/lib/python3.7/random.py in sample(self, population, k)
319 n = len(population)
320 if not 0 <= k <= n:
--> 321 raise ValueError("Sample larger than population or is negative")
322 result = [None] * k
323 setsize = 21 # size of a small set minus size of an empty list
ValueError: Sample larger than population or is negative
After some research, I came across this https://stackoverflow.com/questions/20861497/sample-larger-than-population-in-random-sample-python
but I am still not sure what exactly the issue is. It works sometimes but other times it returns this error. Is it something to do with my questions? Is there a specific format I need to follow for the questions?
Any help would be much appreciated.
Вы ищете random.shuffle? Это даст вам каждый элемент диапазона ровно один раз, в случайном порядке:
>>> import random
>>> l = list(range(1000,2000))
>>> random.shuffle(l)
>>> l
[1096, 1434, 1564, 1503, 1213, 1484, 1340, 1729, 1262, 1663, 1684, 1609, 1464, 1902, 1302, 1767, 1860, 1733, 1009, 1735, 1445, 1429, 1448, 1665, 1551, 1426, 1755, 1790, 1108, 1891, 1121, 1325, 1600, 1230, 1315, 1191, 1243, 1074, 1107, 1865, 1179, 1198, 1169, 1830, 1798, 1727, 1147, 1890, 1092, 1451, 1048, 1638, 1598, 1888, 1807, 1324, 1682, 1589, 1884, 1433, 1130, 1348, 1662, 1215, 1444, 1387, 1897, 1758, 1043, 1372, 1155, 1032, 1487, 1509, 1806, 1602, 1093, 1220, 1772, 1531, 1804, 1746, 1292, 1694, 1556, 1517, 1943, 1582, 1547, 1989, 1966, 1915, 1833, 1276, 1988, 1887, 1320, 1339, 1605, 1951, 1040, 1327, 1336, 1128, 1757, 1538, 1131, 1116, 1142, 1960, 1250, 1307, 1595, 1139, 1576, 1059, 1627, 1633, 1639, 1438, 1252, 1584, 1090, 1272, 1353, 1683, 1163, 1773, 1004, 1658, 1174, 1617, 1516, 1008, 1707, 1083, 1094, 1987, 1628, 1437, 1095, 1763, 1159, 1976, 1267, 1916, 1311, 1091, 1498, 1623, 1029, 1532, 1175, 1458, 1256, 1439, 1452, 1018, 1706, 1205, 1546, 1047, 1103, 1922, 1977, 1895, 1972, 1586, 1447, 1383, 1687, 1822, 1796, 1769, 1664, 1859, 1699, 1322, 1672, 1390, 1360, 1435, 1995, 1753, 1469, 1309, 1208, 1747, 1999, 1791, 1061, 1572, 1245, 1965, 1760, 1601, 1852, 1853, 1913, 1072, 1528, 1530, 1782, 1958, 1342, 1105, 1453, 1416, 1185, 1737, 1015, 1244, 1800, 1366, 1739, 1373, 1533, 1505, 1964, 1996, 1731, 1622, 1742, 1847, 1720, 1263, 1568, 1971, 1667, 1591, 1545, 1953, 1686, 1112, 1935, 1461, 1436, 1894, 1920, 1391, 1673, 1650, 1482, 1197, 1314, 1613, 1479, 1527, 1352, 1186, 1467, 1834, 1948, 1878, 1011, 1911, 1087, 1264, 1333, 1323, 1776, 1266, 1907, 1178, 1284, 1580, 1697, 1857, 1050, 1548, 1974, 1869, 1358, 1190, 1679, 1411, 1539, 1033, 1073, 1308, 1693, 1986, 1165, 1925, 1485, 1085, 1579, 1021, 1055, 1762, 1456, 1088, 1480, 1318, 1357, 1862, 1736, 1752, 1992, 1793, 1006, 1492, 1670, 1392, 1819, 1478, 1481, 1488, 1968, 1583, 1377, 1431, 1880, 1258, 1581, 1007, 1929, 1512, 1775, 1783, 1418, 1511, 1259, 1631, 1328, 1770, 1189, 1963, 1651, 1523, 1829, 1054, 1629, 1596, 1825, 1052, 1768, 1814, 1874, 1843, 1759, 1066, 1151, 1671, 1064, 1780, 1347, 1138, 1794, 1883, 1647, 1867, 1820, 1402, 1973, 1278, 1471, 1653, 1058, 1680, 1975, 1850, 1678, 1304, 1774, 1026, 1691, 1802, 1698, 1146, 1065, 1268, 1111, 1351, 1202, 1045, 1168, 1717, 1677, 1039, 1980, 1502, 1882, 1081, 1407, 1288, 1397, 1848, 1188, 1840, 1721, 1723, 1514, 1158, 1218, 1898, 1616, 1184, 1961, 1424, 1298, 1858, 1955, 1115, 1560, 1506, 1160, 1849, 1356, 1271, 1640, 1636, 1350, 1908, 1473, 1338, 1044, 1474, 1419, 1518, 1370, 1618, 1194, 1614, 1078, 1305, 1513, 1801, 1341, 1313, 1280, 1013, 1702, 1625, 1421, 1070, 1923, 1928, 1257, 1554, 1912, 1173, 1504, 1209, 1612, 1765, 1031, 1216, 1084, 1641, 1566, 1905, 1071, 1959, 1881, 1389, 1486, 1369, 1779, 1983, 1134, 1157, 1713, 1167, 1354, 1799, 1001, 1688, 1388, 1207, 1030, 1846, 1143, 1104, 1180, 1154, 1690, 1060, 1228, 1468, 1681, 1097, 1931, 1120, 1101, 1002, 1877, 1635, 1938, 1604, 1590, 1379, 1795, 1398, 1868, 1126, 1201, 1152, 1851, 1620, 1899, 1854, 1892, 1106, 1203, 1156, 1214, 1703, 1425, 1269, 1226, 1812, 1549, 1766, 1422, 1316, 1740, 1573, 1321, 1606, 1692, 1875, 1056, 1477, 1709, 1632, 1611, 1381, 1297, 1542, 1967, 1708, 1124, 1936, 1051, 1384, 1440, 1196, 1969, 1615, 1689, 1571, 1940, 1685, 1277, 1335, 1326, 1077, 1654, 1193, 1751, 1069, 1212, 1299, 1310, 1508, 1399, 1529, 1954, 1408, 1042, 1561, 1211, 1119, 1587, 1086, 1855, 1466, 1067, 1192, 1441, 1918, 1507, 1624, 1607, 1553, 1217, 1362, 1592, 1206, 1900, 1608, 1450, 1273, 1150, 1823, 1396, 1337, 1349, 1265, 1187, 1306, 1909, 1500, 1652, 1172, 1749, 1057, 1866, 1099, 1003, 1079, 1552, 1363, 1385, 1861, 1863, 1567, 1455, 1594, 1831, 1603, 1784, 1956, 1319, 1557, 1223, 1359, 1842, 1962, 1378, 1153, 1979, 1950, 1491, 1826, 1063, 1177, 1725, 1933, 1738, 1838, 1233, 1599, 1927, 1788, 1080, 1301, 1137, 1132, 1409, 1024, 1110, 1835, 1014, 1993, 1845, 1290, 1470, 1162, 1199, 1183, 1239, 1465, 1715, 1985, 1332, 1569, 1903, 1365, 1423, 1889, 1412, 1176, 1432, 1734, 1803, 1016, 1181, 1118, 1254, 1075, 1114, 1161, 1037, 1871, 1593, 1270, 1495, 1982, 1082, 1401, 1659, 1970, 1261, 1939, 1229, 1496, 1914, 1832, 1519, 1919, 1166, 1816, 1646, 1904, 1312, 1113, 1540, 1375, 1577, 1634, 1330, 1946, 1565, 1382, 1695, 1253, 1499, 1520, 1716, 1544, 1543, 1287, 1619, 1371, 1710, 1027, 1655, 1750, 1610, 1443, 1034, 1260, 1334, 1778, 1525, 1403, 1219, 1246, 1836, 1428, 1756, 1522, 1235, 1010, 1675, 1578, 1873, 1251, 1570, 1952, 1023, 1462, 1515, 1761, 1805, 1744, 1626, 1701, 1020, 1764, 1901, 1637, 1117, 1394, 1413, 1000, 1649, 1906, 1242, 1674, 1490, 1395, 1049, 1355, 1344, 1917, 1076, 1787, 1574, 1041, 1127, 1910, 1893, 1415, 1476, 1771, 1555, 1102, 1317, 1283, 1998, 1558, 1343, 1732, 1232, 1406, 1785, 1997, 1668, 1144, 1661, 1122, 1164, 1248, 1291, 1149, 1811, 1224, 1380, 1300, 1949, 1125, 1719, 1286, 1711, 1984, 1296, 1068, 1129, 1841, 1588, 1856, 1182, 1676, 1879, 1274, 1240, 1896, 1459, 1449, 1712, 1430, 1501, 1019, 1483, 1140, 1981, 1510, 1648, 1696, 1225, 1025, 1524, 1754, 1417, 1808, 1642, 1247, 1741, 1704, 1046, 1241, 1926, 1038, 1255, 1944, 1295, 1537, 1028, 1657, 1700, 1289, 1942, 1100, 1827, 1279, 1427, 1135, 1062, 1563, 1281, 1446, 1886, 1494, 1285, 1195, 1885, 1828, 1728, 1934, 1990, 1726, 1924, 1526, 1303, 1222, 1669, 1809, 1786, 1978, 1921, 1777, 1536, 1275, 1405, 1813, 1364, 1991, 1136, 1237, 1714, 1035, 1098, 1597, 1238, 1475, 1022, 1249, 1666, 1463, 1493, 1123, 1472, 1234, 1109, 1170, 1345, 1781, 1145, 1724, 1393, 1656, 1722, 1839, 1621, 1200, 1660, 1957, 1870, 1442, 1945, 1941, 1748, 1386, 1585, 1171, 1133, 1005, 1535, 1346, 1017, 1745, 1797, 1329, 1792, 1404, 1630, 1293, 1872, 1930, 1367, 1227, 1815, 1294, 1844, 1454, 1204, 1460, 1994, 1368, 1410, 1550, 1148, 1562, 1236, 1810, 1374, 1575, 1282, 1331, 1743, 1821, 1818, 1876, 1414, 1947, 1141, 1645, 1089, 1817, 1705, 1012, 1541, 1824, 1420, 1361, 1231, 1489, 1053, 1534, 1837, 1643, 1400, 1730, 1644, 1937, 1210, 1864, 1376, 1036, 1457, 1497, 1718, 1221, 1521, 1559, 1789, 1932]
3
Eric Duminil
5 Май 2017 в 08:54
Hello, readers! In this article, we will be focusing on the Python sample() function and its importance in the domain of data science.
So, let us get started!
What is the Python sample() method?
Let us first understand the existence of sample() method in the industry of Data science.
While solving problems with respect to the prediction of data, we often come across situations wherein we need to test the algorithm on a handful of data to estimate the accuracy of the algorithm applied.
This is when Python sample() method comes into picture.
The sample() method lets us pick a random sample from the available data for operations. Though, there are lot of techniques to sample the data, sample() method is considered as one of the easiest of its kind.
Python sample() method works will all the types of iterables such as list, tuple, sets, dataframe, etc. It randomly selects data from the iterable through the user defined number of data values.
Let us now understand the structure of the same in the below section.
Syntax of sample() method
Have a look at the below syntax!
Syntax:
sample(iterable, sample_amt)
We need to provide the function with the sample amount that we want the function to randomly pick from the provided iterable or data structure.
1. Python sample() with list
In this section, we have implemented sample() function alongside a Python list and have selected 4 samples out of the data randomly using the function.
Example:
from random import sample lst = [10,20,40,30,50,46,89] res = sample(lst, 4) print(res)
Output:
2. Python sample() with set
Here, we have created a Python set using alphabets as well as numeric values. Further, we have applied sample() function on the set and selected 4 values at random.
Example:
from random import sample
set_sample = {1,2,3,4,5,"s","a","f","a"}
res = sample(set_sample, 4)
print(res)
Output:
Error and Exceptions with sample() function
While dealing with the sample() function, we can come across a ValueError exception. If we provide the sample_amt as a value that is greater than the total count of data values present in the iterable, this exception is invoked.
Example:
from random import sample
set_sample = {1,2,3,4,5,"s","a","f","a"}
res = sample(set_sample, 15)
print(res)
Output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-284724c4b7db> in <module>
2
3 set_sample = {1,2,3,4,5,"s","a","f","a"}
----> 4 res = sample(set_sample, 15)
5 print(res)
c:usershpappdatalocalprogramspythonpython36librandom.py in sample(self, population, k)
316 n = len(population)
317 if not 0 <= k <= n:
--> 318 raise ValueError("Sample larger than population or is negative")
319 result = [None] * k
320 setsize = 21 # size of a small set minus size of an empty list
ValueError: Sample larger than population or is negative
Conclusion
By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.
For more such posts related to Python, Stay tuned and till then, Happy Learning! 🙂
#python #anomaly-detection
Вопрос:
я получил эту ошибку:
File "C:UsersLucaOneDriveDesktopPythonINSTAGRAM BOT FINALE ( FORSE)Python-Instagram-Bot-Scripts-mainselenium_script.py", line 105, in like_post_by_tag
choices = random.sample(posts_list, amount)
File "C:Program FilesPython39librandom.py", line 450, in sample
raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative
это для бота instagram, и он выходит из строя, когда пытается нажать на сообщение
Комментарии:
1. Пожалуйста, предоставьте достаточно кода, чтобы другие могли лучше понять или воспроизвести проблему.
Ответ №1:
Если вы пытаетесь выбрать количество элементов, превышающее количество элементов, из которых вы делаете выборку, вы столкнетесь с этой ошибкой значения. Вы можете либо обработать ошибку с исключением, except ValueError: choices = random.sample(posts_list, len(posts_list)) а затем выполнить повторную выборку с меньшим значением, например размером списка сообщений, num_posts_list = len(posts_list) либо проверить размеры списка сообщений перед выборкой, а затем уменьшить количество. if amount > num_posts_list: amount = num_posts_list
Я написал код, чтобы случайным образом собрать группу людей. Цель состоит в том, чтобы, когда один человек уже выбран случайным образом, программа должна удалить его. У меня есть польза random.sample() функция и она хорошо работает для n=1,2,3,4 когда я достигаю 5, это выдает мне ошибку, и до сих пор я пытаюсь понять, что происходит за этой функцией. Любое объяснение и подсказка будут полезны. Спасибо!
import random
ma_list =["anne","aline","gros","eve","armand","yves","elv","allo","sonia","luc","marc","jules","kevin"]
#this will contain an occurence of our list
maListOc = ma_list
#this list will contain our random list
random_list = None
groupe = 1
#for each element in ma_list, we randome and put into our variable
for i in ma_list:
random_list = random.sample(ma_list, 5)
#then we remove data already randomize in our list, but the complexity is high for this little program
for element in random_list:
ma_list.remove(element)
print("Goupe N°:",groupe)
#and we finally print our randomized list
print(random_list)
print("______________________________")
groupe += 1
print(maListOc)
вот результат:
Goupe N°: 1
['aline', 'gros', 'armand', 'sonia', 'anne']
______________________________
Goupe N°: 2
['kevin', 'allo', 'eve', 'elv', 'marc']
______________________________
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-29-c2d13d61c8d1> in <module>
8 #for each element in ma_list, we randome and put into our variable
9 for i in ma_list:
---> 10 random_list = random.sample(ma_list, 5)
11 #then we remove data already randomize in our list, but the complexity is high for this little program
12 for element in random_list:
~anaconda3librandom.py in sample(self, population, k)
361 n = len(population)
362 if not 0 <= k <= n:
--> 363 raise ValueError("Sample larger than population or is negative")
364 result = [None] * k
365 setsize = 21 # size of a small set minus size of an empty list
ValueError: Sample larger than population or is negative