Проблемы с тегом image:image в картах сайтов. Обход непонимания валидатора Яндекс
Карта сайта — важный инструмент в настройке сайтов, которым не рискнет пренебречь ни один раскрутчик или веб-мастер. Естественно, что даже весьма незначительные и малочисленные замечания от поисковиков должны не только оперативно исправляться, но и не появляться в принципе. В данной статье будет разобрана популярная ошибка с тегом image:image и варианты ее решения.
О проблеме
Большинство начинающих веб-мастеров и продвинутых пользователей используют для генерации карты сайта специальное по — всевозможные настройки и плагины. Согласны, это удобно и быстро, но алгоритмы подобного софта никогда не смогут заменить живого вебмастера, поэтому нередко на свет появляются баги, неточности и просто ошибки, которые могут сильно «подпортить» индексацию и продвижение ресурса. Говоря о лидерах SEO-плагинов для WordPress (Yoast SEO и All In One SEO Pack), то ситуация точно такая же — при использовании встроенных генераторов карт «возмущения» валидатора Яндекс (а иногда и Google) неизбежны.
Самой распространенной ошибкой, с которой сталкивались и наши клиенты (многие из них приходят с других агентств и от фрилансеров) это непринятие валидатором Яндекс тегов для изображений, а именно предупреждение о теге image:image. С одной стороны, великий и могучий Платон Щукин уверяет, что если тег не используется Яндексом, то он просто пропускается. С другой — непонятно, почему же тогда выдается предупреждение, и почему оно появляется не у всех пользователей с аналогичным тегированием карт. Более того — сеть полна слезливых историй пользователей и даже начинающих веб-мастеров, которые приписывают данной ошибке все, что можно — от пессимизации в поиске до полного вылета из оного.
Варианты решения и профилактики
Естественно, подобные истории — не более чем некорректные выводы новичков, но проблема есть и решать ее нужно.
Сам тег создан для обозначения изображений. Google его прекрасно воспринимает, а вот Яндекс через раз — многие карты с этим текстом не вызывают у валидатора вопросов, некоторые получают предупреждение о неизвестном теге. Решений проблемы, на самом деле, несколько:
Вместо итога
Пофиксит ли Платон Щукин данную проблему — неизвестно. Пока можно советовать вообще отказаться от информации по изображениям в своей карте, если они не являются главным контентом на сайте. Ни для кого не секрет, что боты и без карт отлично справляются с индексированием графики.
Если же подобная информация в приоритете, то используйте рекомендованный плагин Google. Его настройка не вызовет проблем даже у ребенка.
Русские Блоги
Image Caption введение и реализация принципа описания изображения
Организовано на основе двух исходных сообщений в блоге
Спасибо за волнуЭтот блогИ lgd1234567
Код реализации может напрямую git по этому адресу, в нем уже существует сеть предварительного обучения, дополнительная загрузка данных модели не требуется.im2txt_demo
Структура кодировщика-декодера
Перед тем, как вводить технологии, связанные с Image Caption, необходимо рассмотреть структуру кодировщика-декодера RNN. Мы знаем, что в самой примитивной структуре RNN входная и выходная последовательности должны быть строго равными по длине. Но в таких задачах, как машинный перевод, длина предложения исходного языка и предложения целевого языка часто различается, поэтому нам нужно сопоставить исходную последовательность с последовательностью разной длины. Модель Encoder-Decoder решает такую проблему сопоставления с несогласованной длиной, и ее структура показана на рисунке ниже:
Структура кодировщика-декодера была первоначально предложена в статье «Изучение представлений фраз с использованием кодировщика-декодера RNN для статистического машинного перевода» и применена к системе машинного перевода. Заинтересованные студенты могут обратиться к исходной статье для получения подробной информации.Здесь мы вернемся к задаче Image Caption и посмотрим, как использовать структуру Encoder-Decoder для Image Caption.
1. Show and Tell: A Neural Image Caption Generator
2.Show, Attend and Tell: Neural Image Caption Generation with Visual Attention
Кодировать входную последовательность в семантические функции h n » role=»presentation» style=»position: relative;»> h n Расшифруйте снова, но потому что h n » role=»presentation» style=»position: relative;»> h n Ограничение длины снизит точность перевода длинных предложений. В статье «Нейронный машинный перевод путем совместного обучения выравниванию и переводу» предлагается механизм внимания, который больше не использует единые семантические функции и позволяет декодеру быть свободным во вводе. последовательность Выбор необходимых функций значительно улучшает производительность модели кодировщика-декодера. «Покажи, посети и расскажи: создание подписи к нейронным изображениям с визуальным вниманием» использует механизм внимания для улучшения исходного механизма кодировщика-декодера. В частности, он использует пространственные характеристики CNN для извлечения признака для различных положений изображения. С функцией, содержащей информацию о местоположении, декодер имеет возможность выбирать из этих 196 признаков местоположения во время декодирования. Это механизм внимания. На следующем рисунке показаны некоторые примеры. Каждое предложение автоматически генерируется моделью. На рисунке область, на которую модель обращает внимание при создании подчеркнутых слов, выделена белым цветом:
3.What Value Do Explicit High Level Concepts Have in Vision to Language Problems?
4.Mind’s Eye: A Recurrent Visual Representation for Image Caption Generation
» role=»presentation» style=»position: relative;»> v
» role=»presentation» style=»position: relative;»> v
, Требовать как можно больше при обучении v
≈ v » role=»presentation» style=»position: relative;»> v
Как показано на рисунке ниже, когда мы создаем текст, нам не нужно его использовать. v
» role=»presentation» style=»position: relative;»> v
5.From Captions to Visual Concepts and Back
Наконец, я должен упомянуть «От подписей к визуальным концепциям и обратно». Эта статья подготовлена Microsoft и аналогична первой статье Google. Все они участвовали в конкурсе Microsoft Image Caption (вызов MS COCO caption). Общий результат делится на первое место (как показано на рисунке ниже). имеет свои небольшие индикаторы, все из которых относятся к новаторской работе. Причина, по которой я помещаю его в конец, состоит в том, что он не принадлежит архитектуре кодировщика-декодера, а использует традиционный метод языкового моделирования.
Что касается извлечения признаков изображения, эта статья похожа на статью «Какое значение имеют явные концепции высокого уровня для видения языковых проблем?». Оба извлекают возможные слова из изображения, а затем моделируют язык. Разница в том, что в предыдущей статье используется метод обучения с несколькими метками, в то время как в этой статье используется метод обучения с несколькими экземплярами (Multiple Instance Learning), который может не только извлекать возможные слова из изображения, но и соответствовать словам К конкретному область изображения.
» role=»presentation» style=»position: relative;»> V
» role=»presentation» style=»position: relative;»> V l
, Представляет слово, которое не использовалось при создании l-го слова.
) » role=»presentation» style=»position: relative;»> V l
» role=»presentation» style=»position: relative;»> V l
Некоторые особенности извлечены из этих слов, как они используются в тексте. w i » role=»presentation» style=»position: relative;»> w i Это принадлежит V l
» role=»presentation» style=»position: relative;»> V l
Реализовать img2txt
1. Загрузите исходный код проекта и конфигурационную среду.
git скачать весь файл модели
На моем компьютере уже настроена среда, поэтому этот шаг пропущен. Для конкретных шагов см. Следующий текст или ссылку на мою среду установки выше:
Сначала следуйте инструкциям im2txt на Github, чтобы установить все необходимые пакеты.
Скачать модель и словарь
Если вы хотите обучить модель самостоятельно, согласно официальному сайту, вам необходимо загрузить несколько часов набора данных, затем потренироваться в течение 1-2 недель и, наконец, выполнить точную настройку через несколько недель. Обучение занимает много времени, поэтому используйте обученную модель. Адрес загрузки
Исходный адрес (если есть VPN)
Адрес веб-диска: Пароль: 9bun
Скачать адрес на github
После скачивания поместите в папку im2txt / model
Также скачивайте файлы, содержащие словаword_counts.txt, После скачивания кладем в папку data
Сценарии
Создайте новый файл сценария run.sh в папке im2txt и введите следующую команду
Переменные в нем заменяются их собственными путями, такими как путь, который я сейчас установил.
Затем установите рабочий каталог в верхний каталог im2txt и запустите скрипт
Случайно Baidu сделал снимок для теста
В то же время команда bazel build сгенерирует несколько папок в каталоге того же уровня WORKSPACE.
И под bazel-bin находится скомпилированный run_inference, который будет вызываться в run.sh
Сводка ошибок
1. При запуске run.sh команда сборки bazel может быть запущена только в рабочем каталоге.
Решение состоит в том, чтобы создать новое РАБОЧЕЕ МЕСТО в каталоге, в котором выполняется run.sh.
2. Не удается найти пакет im2txt.
При запуске run.sh возникла ошибка, что пакет im2txt не найден
Это связано с тем, что он не выполняется в верхнем каталоге im2txt, решение состоит в том, чтобы выполнить скрипт run.sh в верхнем каталоге im2txt.
Или напрямую добавьте команду для возврата в верхний каталог в run.sh
Затем выполните прямо в текущем каталоге run.sh
3. Не удается найти lstm / basic_lstm_cell / ×××
При запуске run.sh TensorFlow не может найти lstm / basic_lstm_cell / ××× в модели.
Это связано с тем, что LSTM TF1.0 и TF1.2 имеет различие в именовании. Именование перед TF1.0 отличается от TF1.0, поэтому вам необходимо изменить его самостоятельно в соответствии с сообщением об ошибке.
| TF1.0 | TF1.2 |
|---|---|
| lstm/basic_lstm_cell/weights | lstm/basic_lstm_cell/kernel |
| lstm/basic_lstm_cell/biases | lstm/basic_lstm_cell/bias |
Решение состоит в том, чтобы создать новый файл rename_ckpt.py и использовать следующий метод для преобразования исходной модели обучения.
Решение состоит в том, чтобы создать новый файл rename_ckpt.py и использовать следующий метод для преобразования исходной модели обучения.
Запустите скрипт rename_ckpt.py, и результат после успешной модификации будет следующим
На этом этапе в папке модели появится несколько новых файлов.
В то же время измените CHECKPOINT_PATH в скрипте run.sh на измененный файл ckpt.
Следующая ошибка не обнаружена
4. Ошибка чтения изображения.
При запуске run.sh появляется сообщение об ошибке кодирования, а информация отслеживания ошибок указывает, что это была ошибка при чтении изображения.
5. Выведите тот же повествовательный текст.
После выполнения сценария run.sh все выходные результаты представляют собой один и тот же повествовательный текст, а их много.
Я проверил код и обнаружил, что в сценарии caption_generator.py есть суждение, является ли это терминатором Приговор
Результатом этой строки кода всегда является False. Я сравниваю значение w со значением end_id и обнаруживаю, что w = 2 и end_id = 3.
Image captions on Web pages
(HTML and CSS techniques)
This document suggests three ways of presenting an image with a caption in HTML. Styling in CSS is also discussed.
Summary: three methods
Sadly enough, there is no markup for image captions in HTML, unless you count the figcaption element in HTML5 proposals. What comes closest to semantically associating some text content with some image is putting them into a table so that the image is in one cell and the text is either in another cell or in a caption element. Then there’s the “semantically empty” approach, which is better than semantically wrong (such as suggestions to use definition list markup).
There are two basic ways to use a table for an image and its caption, so as a whole, we have three alternative methods:
The two-cell approach
By default, text in a table cell ( td element) is left-aligned, but you can change this by using e.g. align=»center» in the td tag, or in CSS (e.g., td.caption < text-align: center ).
A table is normally left-aligned by default and appears with no other content on either side of it. You can affect this using a align attribute in the table or, more flexibly, using CSS. It might be a good idea to set just some left margin for the table, using e.g. the CSS code table.image < margin-left: 2em >.
A single-cell table with caption element
This approach is similar to the first one, but instead of putting the caption text into a cell, you put it inside a caption element. It is by definition a caption for the entire table, but in this case, the table has but one cell, containing the image.
By default, the caption would appear above the image, but the attribute align=»bottom» puts it below the image. You could do the same in CSS using table.image caption < caption-side: bottom; >, but this is poorly supported: no support in Internet Explorer.
Using div elements
This is the simplest method, using just div markup. The inner div element is used for two reasons: to make the caption text appear on a line of its own, and to make it an element, so that it can be referred to in CSS (using a selector like div.image div ).
It might be argued that it is even simpler to omit the inner div markup and use just
to create a line break between the image and the caption. Even the outer div markup could be omitted on similar grounds. However, the markup presented here is the simplest reasonable alternative. The use of div makes it possible to treat the caption text and the combination of the image and caption as styleable elements.
A div element has no top or bottom margin by default. You can change this in CSS. For example, div.image < margin: 1em 0; >would set a top and bottom margin of 1em. On the other hand, the construct is often preceded by an element that has a bottom margin, or followed by an element that has a top margin, such as a paragraph or a heading, so it does not need margins of its own.
Notes on styling
These three approaches give a tolerable rendering in non-CSS situations (showing the caption under the image), and they are each a relatively good starting point for styling. When using a table, you need to consider cell spacing and cell padding, which are by default nonzero. But there wouldn’t be strange browser idiosyncrasies to worry about. The rest really depends on the desired appearance as well as the properties of the image and the text.
The font in caption texts
Typically we’d probably want to set caption text size to a bit smaller than copy text, and maybe the font face to something different too, and we might wish to center the text (though this may depend on its length). In the first approach you could use the following:
Wrapping long captions
For long caption texts, you need to decide whether they should wrap according to the width of the image or be set to some other width. It’s probably best to make the width the same as that of the image or (for narrow images) just a little wider.
By default, browsers handle the second approach (using a table and a caption element) so that the the text is wrapped to the same width as the image. This is because they determine the width of the table according to the cell containing the image. If you wish to make sure of this, you could explicitly set the table width to the same as the image width. In the first approach, you would need to be explicit about the table width, either in CSS or in HTML.
![]() |
In the above example, the caption element has grey background to illustrate that it extends a bit to the left and to the right of the image width. This is usually not serious when the text there is centered. The phenomenon is caused by default cell padding and cell spacing that browsers apply when rendering a table. If it becomes a problem, you can fix it in HTML by setting cellspacing=»0″ cellpadding=»0″ in the table element or in CSS by setting table < border-collapse: collapse; >td < padding: 0; >.
In the third approach, the caption text by default uses the available width. The reason is that the width of a div element by default extends across the available width.
You could change the appearance by explicitly setting the width of the outer div element, e.g.
Of course, in many cases you could meaningfully use explicit line breaks (with
) markup inside the caption text, especially if the text has fairly separate parts. For example, you could write
Centering
As described above, the caption text can be centered relative to the image by setting a width the text and using align=»center» (HTML) or text-align: center (CSS) for it.
![]() |
| A Dalmatian dog. Drawing by Liisa Sarakontu. |
Floating the image and the caption

![]() |
| A Dalmatian |
margin properties in CSS.
To end floating, you can either use
in HTML or clear: both in CSS (for the first element that should appear with no floating elements on either side).
Fluid galleries
If you have a set of images and you would like to present them as a collection on one page so that there are several images side by side, there are several approaches.
A common approch is to use a table, with images in one row, captions in another, then more images in a third row, etc. This approach does not linearize well, since when processed rowwise, the connection between images and captions is lost. But more importantly, it requires a fixed layout, with a fixed amount of images in one row. This means that the page requires a minimum width to be viewed without horizontal scrolling, and on the other hand it does not utilize the full available width in a wide window.
The goal here is to make an image gallery adapt to the available width. For simplicity, let’s assume that the images are of equal size.
In the simplest case, you could just write img elements in succession. A browser will then present the images so that it puts as many images side by side as fits to the available width. In effect, a browser treats img elements as big letters and processes a string of images as if it were text consisting of such letters. The following string of identical images illustrates this.






I use a space between the img elements in HTML source. This tends to cause some spacing between the images on common browsers. Whether this is correct is debatable. In any case, if you don’t want any spacing, don’t leave those spaces or line breaks between img elements. Instead, you can put line breaks e.g. after the element name img before the attributes, where they cause no effect. And if exact spacing is important, do the same and use CSS properties to suggest specific margin or padding.
If we wish to put captions under the images, things become more complicated, but not much. We can float the elements that contain an image and its caption. We would use the methods discussed above, except that we float to the left, using float: left in CSS or align=»left» in HTML for a table.
This leaves a 5 pixel space on the right of each image and 20px space below each each image:
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
Remember to stop floating after the gallery, using the techniques mentioned above.
If the caption texts vary essentially in length, you need to consider how to make their boxes equal in size in rendering. This usually requires you to guess a reasonable height for the boxes. Moreover, to make the texts vertically aligned to the top (that is, the bottom of the image), it is simplest to use the two-cell table approach. In that case, you can simply use valign=»top» (in HTML) or vertical-align : top (in CSS) for the cells. In the next example, the height of caption cells has been set to 4em.
![]() |
| An ornament |
![]() |
| This is a caption that is essentially longer than the other captions. |
![]() |
| An ornament |
![]() |
| An ornament |
![]() |
| An ornament |
Captions and accessibility
A caption should not be confused with an alt attribute, which specifies the textual alternative to be presented in place of the image, when the image itself is not presented (e.g., on a text-only browser). Neither of these should be confused with the title attribute, which specifies an “advisory title” for an element, typically implemented as a tooltip that is displayed when the pointer is moved over the element.
Why not dl markup?
The default rendering of
caption text
on your current browser is the following:

The reason why browsers render the construct that way has nothing to do with images or captions. They render a dl element so that the dt elements are indented somewhat and the dd elements are indented even more, and each of those elements starts on a new line:
term a word or expression that has a precise meaning in some uses or is peculiar to a science, art, profession, or subject terminology terms of a particular subject area; (study of) proper ways of creating and using terms
So this is why the caption text gets indented relative to the image. Such indentation is generally not suitable, since normally captions should be either left-aligned or centered with respect to the image. But if desired, the indentation can be achieved very simply, and with a controlled amount of indentation, in the approaches described above, e.g. by setting a left margin for the caption.
If a speech-based browser implemented a dl element according to its defined semantics (ignoring any examples in the specification that contradict that), it would be natural to read
xxx yyy
as follows: “Definition list. Term: xxx. Definition data: yyy. End of definition list.” Current browsers probably don’t do that, but would you really like to fear that some browsers start behaving by the specs? (Maybe there is no fear, because the HTML5 drafts effectively turn dl to a list of paired items with no real semantics.)
Using a definition list with a single dt element and a single dd element inside would be semantically odd. A list can have just one element, though it’s a rather pathetic list and makes sense in special case only. But this is not the main point. The point is that neither an image nor its caption is a term being defined. Well, except in a very special example like the following, which illustrates the absurdity of using dl markup for normal combinations of an image and its caption:
The dl element is in practice just a visual layout trick, and a coarse and unreliable trick at that. Quite often the layout would not even be suitable but needs tedious styling. Besides, the dl is more difficult to style than most elements, since its default rendering is complicated and hard to describe, and there are quirks in CSS implementations that make the styling even harder.
The HTML5 figure and figcaption markup
According to HTML drafts, figure markup can be used as a container for an illustration (such as one or more images), with figcaption element inside it giving a caption for the image or images. This means markup like the following:
This would solve the problem of semantic association between captions and images, if supported by relevant software. It remains to be seen whether search engines will recognize such associations.
For minimally acceptable rendering, you currently need at least the following (the script is needed for IE up to and including IE�8 to make it recognize the markup at all):
You should probably also add some top and bottom margin for figure and also some left margin. HTML5 drafts suggest a left margin of 40px, but this is currently not what browsers usually do. So you should explicitly specify the left margin you want.
In order to have the caption rendered e.g. below the image in a box that is as wide as the image, it is probably best to use a small script on the page. The script can traverse the figure elements on the page and set the width of such an element equal to the img element contained in it, if there is just one img element there. Similar techniques can, of course, be also applied when some other markup is used for image captions.

For comparison
For a different view on image captions, see CSS: figures & captions by Bert Bos. I don’t see any reason to use paragraph ( p ) markup in a simple structure consisting of an image and its caption. But if you use it, note that paragraphs typically have default rendering that involves top and bottom margins, though they might be suppressed if the paragraph is inside a table cell.
See also Scalable Figures and Captions with CSS and HTML by Robert J. O’Hara. It discusses, among other things, the distinction between a legend (extended prose) and a caption (a descriptive word or phrase only). Both are treated as captions in my document, but it is useful to note that there can be different “captions” that should be styled differently.




